branches/gmyth-0.1b/src/gmyth_socket.c
author renatofilho
Thu Feb 01 18:42:01 2007 +0000 (2007-02-01)
branchtrunk
changeset 320 22a17127789e
permissions -rw-r--r--
[svn r322] created branch gmyth-0.1b
     1 /**
     2  * GMyth Library
     3  *
     4  * @file gmyth/gmyth_socket.c
     5  * 
     6  * @brief <p> MythTV socket implementation, according to the MythTV Project
     7  * (www.mythtv.org). 
     8  * 
     9  * This component provides basic socket functionalities to interact with
    10  * the Mythtv backend.
    11  * <p>
    12  *
    13  * Copyright (C) 2006 INdT - Instituto Nokia de Tecnologia.
    14  * @author Rosfran Lins Borges <rosfran.borges@indt.org.br> 
    15  *
    16  *//*
    17  * 
    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.
    22  *
    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.
    27  *
    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
    31  */
    32 
    33 #ifdef HAVE_CONFIG_H
    34 #include "config.h"
    35 #endif
    36 
    37 #include "gmyth_socket.h"
    38 
    39 #include <glib.h> 
    40 #include <glib/gprintf.h>
    41 
    42 #include <arpa/inet.h>
    43 #include <sys/types.h>
    44 #include <sys/socket.h>
    45 #include <sys/param.h>
    46 #include <netdb.h>
    47 #include <net/if.h>
    48 #include <errno.h>
    49 #include <stdlib.h>
    50 
    51 #include <unistd.h>
    52 #include <netinet/in.h>
    53 #include <fcntl.h>
    54 #include <signal.h>
    55 
    56 #include <sys/ioctl.h>
    57 
    58 #include "gmyth_stringlist.h"
    59 #include "gmyth_uri.h"
    60 #include "gmyth_debug.h"
    61 
    62 #define BUFLEN 				   	512
    63 #define MYTH_SEPARATOR 			    	"[]:[]"
    64 #define MYTH_PROTOCOL_FIELD_SIZE		8
    65 
    66 /* max number of iterations */
    67 #define MYTHTV_MAX_VERSION_CHECKS		40
    68 
    69 // FIXME: put this in the right place
    70 #define  MYTHTV_VERSION_DEFAULT			30
    71 
    72 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
    73 
    74 static gchar* local_hostname = NULL;
    75 
    76 static void gmyth_socket_class_init          (GMythSocketClass *klass);
    77 static void gmyth_socket_init                (GMythSocket *object);
    78 
    79 static void gmyth_socket_dispose  (GObject *object);
    80 static void gmyth_socket_finalize (GObject *object);
    81 
    82 G_DEFINE_TYPE(GMythSocket, gmyth_socket, G_TYPE_OBJECT)
    83 
    84 static void
    85 gmyth_socket_class_init (GMythSocketClass *klass)
    86 {
    87     GObjectClass *gobject_class;
    88 
    89     gobject_class = (GObjectClass *) klass;
    90 
    91     gobject_class->dispose  = gmyth_socket_dispose;
    92     gobject_class->finalize = gmyth_socket_finalize;	
    93 }
    94 
    95 static void
    96 gmyth_socket_init (GMythSocket *gmyth_socket)
    97 {
    98 	
    99 	/* gmyth_socket->local_hostname = NULL; */
   100 	
   101 }
   102 
   103 /** Gets the some important address translation info, from the client socket
   104  * that will open a connection.
   105  * 
   106  * @return gint that represents the error number from getaddrinfo(). 
   107  */
   108 static gint
   109 gmyth_socket_toaddrinfo (const gchar *addr, gint port, struct addrinfo **addrInfo )
   110 {
   111     struct addrinfo hints;
   112     gchar *portStr = NULL;
   113     gint errorn = EADDRNOTAVAIL;
   114  
   115     g_return_val_if_fail ( addr != NULL, -1 );
   116     g_debug ("Calling %s\n", __FUNCTION__);
   117 
   118     /* hints = g_malloc0 ( sizeof(struct addrinfo) ); */
   119     memset ( &hints, 0, sizeof(struct addrinfo) );
   120     hints.ai_family = AF_INET;
   121     hints.ai_socktype = SOCK_STREAM;
   122     /* hints.ai_flags = AI_NUMERICHOST; */
   123     
   124     if ( port != -1 )	
   125         portStr = g_strdup_printf ( "%d", port );
   126     else
   127 	portStr = NULL;
   128 
   129     gmyth_debug ("Getting name resolution for: %s, %d\n", addr, port);
   130 
   131     if ( ( errorn = getaddrinfo(addr, portStr, &hints, addrInfo) ) != 0 ) {
   132 		g_printerr( "[%s] Socket ERROR: %s\n", __FUNCTION__, gai_strerror(errorn) );
   133     }
   134     g_free (portStr);
   135     /* g_free (hints); */
   136     return errorn;
   137 }
   138 
   139 static gint
   140 gmyth_socket_find_match_address_uri( GMythURI* uri, gchar *address ) {
   141 
   142         if ( g_ascii_strcasecmp( gmyth_uri_get_host( uri ), address ) == 0 ) {
   143                 //g_printerr( "Found URI: %s !!!\n", rui_uri_getvalue(uri) );
   144                 return 0;
   145         } else {
   146                 return -1;
   147         }
   148 
   149 }
   150 
   151 static const gchar *PATH_PROC_NET_DEV = "/proc/net/dev";
   152 
   153 /** Gets the list of all local network interfaces (using the /proc/net/dev directory).
   154  * 
   155  * @param current_connections	A list with all the network interfaces are valid, 
   156  * 		to be applied just like a filter.
   157  * @return List with all the local net interfaces. 
   158  */
   159 static GList *
   160 gmyth_socket_get_local_addrs( GList *current_connections )
   161 {
   162 
   163 	GList *local_addrs = NULL;
   164 	FILE *fd;
   165 	gint s;
   166 	gchar buffer[256+1];
   167 	gchar ifaddr[20+1];
   168 	gchar *ifname;
   169 	gchar *sep;
   170 	
   171 	s = socket(AF_INET, SOCK_DGRAM, 0);
   172 	if (s < 0)
   173 		return 0;
   174 	fd = fopen(PATH_PROC_NET_DEV, "r");
   175 	fgets(buffer, sizeof(buffer)-1, fd);
   176 	fgets(buffer, sizeof(buffer)-1, fd);
   177 	while (!feof(fd)) {
   178 		ifname = buffer;
   179 		sep;
   180 		if (fgets(buffer, sizeof(buffer)-1, fd) == NULL)
   181 			break;
   182 		sep = strrchr(buffer, ':');
   183 		if (sep)
   184 			*sep = 0;
   185 		while (*ifname == ' ')
   186 			ifname++;
   187 		struct ifreq req;
   188 		strcpy(req.ifr_name, ifname);
   189 		if (ioctl(s, SIOCGIFFLAGS, &req) < 0)
   190 			continue;
   191 		if (!(req.ifr_flags & IFF_UP))
   192 			continue;
   193 		if (req.ifr_flags & IFF_LOOPBACK)
   194 			continue;
   195 		if (ioctl(s, SIOCGIFADDR, &req) < 0)
   196 			continue;
   197 		g_strlcpy( ifaddr, inet_ntoa(((struct sockaddr_in*)&req.ifr_addr)->sin_addr), sizeof(struct ifaddr)-1 );
   198 		local_addrs = g_list_append( local_addrs, g_strdup( ifaddr ) );
   199 
   200 		gmyth_debug( "( from the /proc/net/dev) Interface name: %s, address: %s\n", 
   201 								ifname, ifaddr );
   202 	}
   203 	fclose(fd);
   204 	close(s);
   205 	return local_addrs;
   206 
   207 }
   208 
   209 
   210 /**
   211  * Get only the local addresses from the primary interface
   212  */
   213 static gchar *
   214 gmyth_socket_get_primary_addr()
   215 {
   216 	
   217 	gchar *if_eth0 = g_new0( gchar, sizeof(struct ifaddr)-1 );
   218 	GList *if_tmp = NULL;
   219 	
   220 	GList *interfs = gmyth_socket_get_local_addrs( NULL );
   221 	
   222 	if ( interfs != NULL && ( g_list_length( interfs ) > 0 ) ) 
   223 	{
   224 		/* get the first occurrence (primary interface) */
   225 		if_tmp = g_list_first( interfs );
   226 		
   227 		if ( if_tmp != NULL )
   228 			g_strlcpy (if_eth0, (gchar *)if_tmp->data, sizeof(struct ifaddr)-1 );
   229 
   230 	}
   231 	
   232 	if ( interfs != NULL )
   233 		g_list_free( interfs );
   234 	
   235 	return if_eth0;
   236 }
   237 
   238 /** This function retrieves the local hostname of the 
   239  * client machine.
   240  *
   241  * @return GString* get local hostname.
   242  */
   243 GString *
   244 gmyth_socket_get_local_hostname  ()
   245 {
   246 
   247     char hname[50];
   248     gint res = gethostname (hname, 50);
   249 
   250     if (res == -1) {
   251 	g_debug ("Error while getting hostname");
   252 	return NULL;
   253     }
   254 
   255     return g_string_new (hname);
   256     
   257 #if 0	
   258     GString *str = NULL;
   259     
   260     if ( local_hostname != NULL && strlen(local_hostname) > 0 )
   261     	return g_string_new( local_hostname );
   262 
   263     gchar *localaddr = NULL; 
   264     gboolean found_addr = FALSE;
   265     struct addrinfo* addr_info_data = NULL, *addr_info0 = NULL;
   266     struct sockaddr_in* sa = NULL;
   267     gchar localhostname[MAXHOSTNAMELEN];
   268 
   269 
   270     if (gethostname (localhostname, MAXHOSTNAMELEN) != 0 ) {
   271     	gmyth_debug ( "Error on gethostname" );
   272     }
   273     localhostname[MAXHOSTNAMELEN-1] = 0;
   274 
   275     gint err = gmyth_socket_toaddrinfo (localhostname, -1,  &addr_info_data );
   276     
   277     if ( err == EADDRNOTAVAIL )
   278     {
   279     	g_warning( "[%s] Address (%s) not available. (reason = %d)\n", __FUNCTION__, localhostname, err );
   280     	return str;
   281     }
   282     
   283     g_static_mutex_lock( &mutex );    	
   284 
   285     addr_info0 = addr_info_data;
   286 
   287     while( addr_info0 != NULL && addr_info0->ai_addr != NULL && 
   288 	    ( sa = (struct sockaddr_in*)addr_info0->ai_addr ) != NULL && !found_addr ) {
   289     	localaddr = inet_ntoa( sa->sin_addr );
   290 
   291 	    if ( localaddr != NULL && ( g_strrstr( localaddr, "127" ) == NULL ) ) {
   292 	        str = g_string_new (localaddr);
   293 	        found_addr = TRUE;
   294 		g_free (localaddr);
   295 	        break;
   296 	    }
   297 /*
   298 	    if (localaddr != NULL) {
   299 		g_free (localaddr);
   300 		localaddr = NULL;
   301 	    }
   302 	    */
   303 
   304 	    addr_info0 = addr_info0->ai_next;
   305     };
   306     
   307     freeaddrinfo (addr_info_data);
   308     addr_info_data = NULL;
   309     
   310     if ( found_addr == FALSE ) {
   311         gchar *prim_addr = gmyth_socket_get_primary_addr();
   312 
   313     	if ( prim_addr != NULL ) {
   314 		g_warning("[%s] Could not determine the local alphanumerical hostname. Setting to %s\n",
   315     	        __FUNCTION__, prim_addr );
   316       
   317 	        str = g_string_new (prim_addr);
   318 	        g_free (prim_addr);
   319     	} else {
   320         	str = g_string_new (localhostname);
   321     	}
   322     }
   323 
   324     g_static_mutex_unlock (&mutex);
   325     
   326     if ( str != NULL && str->str != NULL )
   327     	local_hostname = g_strdup( str->str );
   328 
   329     return str;
   330 #endif    
   331 }
   332 
   333 static void
   334 gmyth_socket_dispose  (GObject *object)
   335 {
   336     GMythSocket *gmyth_socket = GMYTH_SOCKET(object);
   337 
   338     /* disconnect socket */
   339     gmyth_socket_close_connection (gmyth_socket);
   340 
   341     g_free (gmyth_socket->hostname);
   342     gmyth_socket->hostname = NULL;
   343     
   344     g_free (local_hostname);
   345     
   346     local_hostname = NULL;
   347 
   348     G_OBJECT_CLASS (gmyth_socket_parent_class)->dispose (object);
   349 }
   350 
   351 static void
   352 gmyth_socket_finalize (GObject *object)
   353 {
   354     g_signal_handlers_destroy (object);
   355 
   356     G_OBJECT_CLASS (gmyth_socket_parent_class)->finalize (object);
   357 }
   358 
   359 /** Creates a new instance of GMythSocket.
   360  * 
   361  * @return a new instance of GMythSocket.
   362  */
   363 GMythSocket*
   364 gmyth_socket_new ()
   365 {
   366     GMythSocket *gmyth_socket = GMYTH_SOCKET (g_object_new(GMYTH_SOCKET_TYPE, NULL));
   367 
   368     gmyth_socket->mythtv_version = MYTHTV_VERSION_DEFAULT;
   369 
   370     return gmyth_socket;
   371 }
   372 
   373 /** Try to open an asynchronous connection to the MythTV backend.
   374  * 
   375  * @param fd 			Socket descriptor.
   376  * @param remote 	Remote address.
   377  * @param len 		Newly created socket length field.
   378  * @param timeout	Timeval argument with the time interval to timeout before closing.
   379  * @param err			Error message number.
   380  * @return Any numerical value below 0, if an error had been found.
   381  */
   382 static gint 
   383 gmyth_socket_try_connect ( gint fd, struct sockaddr *remote, gint len,
   384                struct timeval *timeout, gint *err)
   385 {
   386 	  /*g_return_val_if_fail( timeout != NULL, 0 );*/	  
   387 	  gint saveflags, ret, back_err;
   388 	  
   389 	  fd_set fd_w;
   390 	
   391 	  saveflags = fcntl( fd, F_GETFL, 0 );
   392 	  if( saveflags < 0 ) {
   393 	    g_warning( "[%s] Problems when getting socket flags on fcntl.\n", __FUNCTION__ );
   394 	    *err=errno;
   395 	    return -1;
   396 	  }
   397 	
   398 	  /* Set non blocking */
   399 	  if( fcntl( fd, F_SETFL, saveflags | O_NONBLOCK ) < 0) {
   400 	  	g_warning( "[%s] Problems when setting non-blocking using fcntl.\n", __FUNCTION__ );
   401 	    *err=errno;
   402 	    return -1;
   403 	  }
   404 	
   405 	  /* This will return immediately */
   406 	  *err= connect ( fd, remote, len );
   407 		back_err=errno;
   408 	
   409 		/* restore flags */
   410 	  if( fcntl( fd, F_SETFL, saveflags ) < 0) {
   411 	    g_warning( "[%s] Problems when trying to restore flags with fcntl.\n", __FUNCTION__ );
   412 	    *err=errno;
   413 	    return -1;
   414 	  }
   415 	
   416 	  /* return unless the connection was successful or the connect is
   417 	     still in progress. */
   418 	  if( *err < 0 && back_err != EINPROGRESS) {
   419 	    g_warning( "[%s] Connection unsucessfully (it is not in progress).\n", __FUNCTION__ );
   420 	    *err = errno;
   421 	    return -1;
   422 	  }
   423 	
   424 	  FD_ZERO( &fd_w );
   425 	  FD_SET( fd, &fd_w );
   426 	
   427 	  *err = select( FD_SETSIZE, NULL, &fd_w, NULL, timeout);
   428 	  if ( *err < 0 ) {
   429 	    g_warning( "[%s] Connection unsucessfull (timed out).\n", __FUNCTION__ );
   430 	    *err=errno;
   431 	    return -1;
   432 	  }
   433 	
   434 	  /* 0 means it timeout out & no fds changed */
   435 	  if(*err==0) {
   436 	    close(fd);
   437 	    *err=ETIMEDOUT;
   438 	    return -1;
   439 	  }
   440 	
   441 	  /* Get the return code from the connect */
   442 	  len = sizeof( ret );
   443 	  *err=getsockopt( fd, SOL_SOCKET, SO_ERROR, &ret, (socklen_t *) &len);
   444 	  
   445 	  if( *err < 0 ) {
   446 	    g_warning( "[%s] Connection usnsucessfull.\n", __FUNCTION__ );
   447 	    *err=errno;
   448 	    return -1;
   449 	  }
   450 	
   451 	  /* ret=0 means success, otherwise it contains the errno */
   452 	  if (ret) {
   453 	    *err=ret;
   454 	    return -1;
   455 	  }
   456 	
   457 	  *err=0;
   458 	  return 0;
   459 }
   460 
   461 /** Connects to the backend.
   462  * 
   463  * @param gmyth_socket The GMythSocket instance.
   464  * @param hostname The backend hostname or IP address.
   465  * @param port The backend port.
   466  * @return TRUE if success, FALSE if error.
   467  */
   468 
   469 
   470 gboolean
   471 gmyth_socket_connect (GMythSocket *gmyth_socket,
   472 	const gchar *hostname, gint port)
   473 {
   474     return gmyth_socket_connect_with_timeout (gmyth_socket,
   475 		    hostname, port, 0);
   476 }
   477 
   478 gboolean
   479 gmyth_socket_connect_with_timeout (GMythSocket *gmyth_socket,
   480 	const gchar *hostname, gint port, guint timeout)
   481 {
   482     struct addrinfo *addr_info_data = NULL, *addr_info0 = NULL;
   483     gint ret_code = -1;
   484     gint errno;
   485     gboolean ret = TRUE;
   486 
   487     gmyth_debug ("CONNECTING %s:%d", hostname, port);
   488 
   489     if ( hostname == NULL )
   490         gmyth_debug ( "Invalid hostname parameter!\n");
   491 
   492     /* store hostname and port number */
   493     if (gmyth_socket->hostname != NULL) {
   494         //g_free (gmyth_socket->hostname);
   495         gmyth_socket->hostname = NULL;
   496     }
   497 
   498     errno = gmyth_socket_toaddrinfo ( hostname, port, &addr_info_data );
   499 
   500     g_return_val_if_fail( addr_info_data != NULL && hostname != NULL, FALSE );
   501 
   502     gmyth_socket->hostname = g_strdup( hostname );
   503     gmyth_socket->port = port;
   504 
   505     for ( addr_info0 = addr_info_data; addr_info0; addr_info0 = addr_info_data->ai_next ) {
   506         /* init socket descriptor */
   507         gmyth_socket->sd = socket( addr_info0->ai_family, addr_info0->ai_socktype,
   508                          addr_info0->ai_protocol );
   509 
   510         if ( gmyth_socket->sd < 0 )
   511             continue;
   512 
   513         struct timeval *timeout_val = g_new0 (struct timeval, 1);
   514 	if (timeout != 0) {
   515 	    /*timeout_val = g_new0 (struct timeval, 1);*/
   516 	    
   517             timeout_val->tv_sec = timeout;
   518             timeout_val->tv_usec = 0;
   519 	} else {
   520             timeout_val->tv_sec = 5;
   521             timeout_val->tv_usec = 100;
   522 	}
   523         
   524         if (gmyth_socket_try_connect (gmyth_socket->sd, (struct sockaddr *)addr_info0->ai_addr,
   525                 addr_info0->ai_addrlen, timeout_val, &ret_code ) < 0 )
   526         {
   527             g_printerr( "[%s] Error connecting to backend!\n", __FUNCTION__ );
   528             if (ret_code == ETIMEDOUT)
   529                 g_printerr( "[%s]\tBackend host unreachable!\n", __FUNCTION__ );
   530 
   531             close (gmyth_socket->sd);
   532             gmyth_socket->sd = -1;
   533             g_printerr ("ERROR: %s\n", gai_strerror(ret_code));
   534 	    g_free (timeout_val);
   535             continue;
   536         }
   537 
   538 	g_free (timeout_val);
   539 
   540         /* only will be reached if none of the error above occurred */
   541         break;
   542     }
   543 
   544     freeaddrinfo (addr_info_data);
   545     addr_info_data = NULL;
   546 
   547     if (gmyth_socket->sd_io_ch != NULL) {
   548         g_io_channel_unref (gmyth_socket->sd_io_ch);
   549         gmyth_socket->sd_io_ch = NULL;
   550     }
   551 
   552     gmyth_socket->sd_io_ch = g_io_channel_unix_new (gmyth_socket->sd);
   553     
   554     //GIOFlags flags = g_io_channel_get_flags (gmyth_socket->sd_io_ch);
   555 		/* unset the nonblock flag */
   556 		//flags &= ~G_IO_FLAG_NONBLOCK;
   557 		/* unset the nonblocking stuff for some time, because GNUTLS doesn't like
   558 		 * that */
   559 		//g_io_channel_set_flags (gmyth_socket->sd_io_ch, flags, NULL);
   560 
   561     ret = ( ret_code == 0 ) ? TRUE : FALSE ;
   562     return ret;
   563 }
   564 
   565 /** Gets the GIOChannel associated to the given GMythSocket.
   566  * 
   567  * @param gmyth_socket The GMythSocket instance.
   568  */
   569 GIOChannel *
   570 gmyth_socket_get_io_channel( GMythSocket *gmyth_socket )
   571 {
   572     g_return_val_if_fail( gmyth_socket != NULL, NULL );
   573 
   574     return gmyth_socket->sd_io_ch;
   575 }
   576 
   577 /** Verifies if the socket is able to read.
   578  * 
   579  * @param gmyth_socket The GMythSocket instance.
   580  * @return TRUE if the socket is able to read, FALSE if not.
   581  */
   582 gboolean
   583 gmyth_socket_is_able_to_read( GMythSocket *gmyth_socket )
   584 {
   585     gboolean ret = TRUE;
   586 
   587     /* verify if the input (read) buffer is ready to receive data */
   588     GIOCondition io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
   589 
   590     if ( ( io_cond & G_IO_IN ) == 0 ) {
   591 	g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
   592 	ret = FALSE;
   593     }
   594 
   595     return ret;
   596 
   597 }
   598 
   599 /** Verifies if the socket is able to write.
   600  * 
   601  * @param gmyth_socket The GMythSocket instance.
   602  * @return TRUE if the socket is able to write, FALSE if not.
   603  */
   604 gboolean
   605 gmyth_socket_is_able_to_write( GMythSocket *gmyth_socket )
   606 {
   607     gboolean ret = TRUE;
   608 
   609     /* verify if the input (read) buffer is ready to receive data */
   610     GIOCondition io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
   611 
   612     if ( ( ( io_cond & G_IO_OUT ) == 0 ) || ( ( io_cond & G_IO_HUP ) == 0 ) ) {
   613 	g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
   614 	ret = FALSE;
   615     }
   616 
   617     return ret;
   618 
   619 }
   620 
   621 /** Sends a command to the backend.
   622  * 
   623  * @param gmyth_socket the GMythSocket instance.
   624  * @param command The string command to be sent.
   625  */
   626 gboolean
   627 gmyth_socket_send_command(GMythSocket *gmyth_socket, GString *command) 
   628 {
   629     gboolean ret = TRUE;
   630 
   631     GIOStatus io_status = G_IO_STATUS_NORMAL;
   632     //GIOCondition io_cond;
   633     GError* error = NULL;
   634    
   635     
   636     gchar *buffer = NULL;
   637 
   638     gsize bytes_written = 0;
   639 
   640     if( command == NULL || ( command->len <= 0 ) || command->str == NULL ) {
   641 		g_warning ("[%s] Invalid NULL command parameter!\n", __FUNCTION__);
   642 		ret = FALSE;
   643 		goto done;
   644     }
   645 
   646     //g_static_mutex_lock( &mutex );
   647     gmyth_debug ("Sending command to backend: %s\n", command->str);
   648 
   649     buffer = g_strnfill( BUFLEN, ' ' );
   650     g_snprintf( buffer, MYTH_PROTOCOL_FIELD_SIZE+1, "%-8d", command->len);
   651 
   652     command = g_string_prepend(command, buffer);
   653 
   654     /* write bytes to socket */    
   655     io_status = g_io_channel_write_chars( gmyth_socket->sd_io_ch, command->str, 
   656 	    command->len, &bytes_written, &error );
   657 
   658 
   659     if( (io_status == G_IO_STATUS_ERROR) || ( bytes_written <= 0 ) ) {
   660 		g_warning ("[%s] Error while writing to socket", __FUNCTION__);
   661 		ret = FALSE;
   662     } else if ( bytes_written < command->len ) {
   663 		g_warning ("[%s] Not all data was written socket", __FUNCTION__);
   664 		ret = FALSE;
   665     }
   666 
   667     io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
   668 
   669     if ( ( bytes_written != command->len ) || ( io_status == G_IO_STATUS_ERROR ) )
   670     {
   671 		g_warning ("[%s] Some problem occurred when sending data to the socket\n", __FUNCTION__);
   672 	
   673 		ret = TRUE;
   674     }
   675 
   676     //g_static_mutex_unlock( &mutex );
   677 done:
   678     if ( error != NULL ) {
   679 		g_printerr( "[%s] Error found reading data from IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
   680 		ret = FALSE;
   681 		g_error_free( error );
   682     }
   683 
   684     if ( buffer!= NULL )
   685 		g_free( buffer );
   686 
   687     return ret;
   688 }
   689 
   690 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   691  * supported by the backend and send the "ANN" command.
   692  * 
   693  * @param gmyth_socket the GMythSocket instance.
   694  * @param hostname_backend The backend hostname or IP address.
   695  * @param port The backend port to connect.
   696  * @param blocking_client A flag to choose between blocking and non-blocking
   697  * @param with_events	Sets the connection flag to receive events.
   698  * 										backend connection. 
   699  */
   700 static gboolean
   701 gmyth_socket_connect_to_backend_and_events (GMythSocket *gmyth_socket, 
   702 	const gchar *hostname_backend, gint port, gboolean blocking_client,
   703 	gboolean with_events)
   704 {
   705     if (!gmyth_socket_connect (gmyth_socket, hostname_backend, port)) {
   706 		g_warning ("[%s] Could not open socket to backend machine [%s]\n", __FUNCTION__,
   707 					hostname_backend );
   708 		return FALSE;
   709     }
   710 
   711     if ( gmyth_socket_check_protocol_version (gmyth_socket) ) {
   712 
   713 	GString *result;
   714 	GString *base_str = g_string_new("");
   715 	GString *hostname = NULL;
   716 
   717 	hostname = gmyth_socket_get_local_hostname();
   718 	if (hostname == NULL) {
   719 	    g_debug ("Hostname not available, setting to n800frontend\n");
   720 	    hostname = g_strdup ("n800frontend");
   721 	}
   722 
   723 	g_string_printf(base_str, "ANN %s %s %u", 
   724 		(blocking_client ? "Playback" : "Monitor"),
   725 		hostname->str, with_events);
   726 
   727 	gmyth_socket_send_command (gmyth_socket, base_str);
   728 	result = gmyth_socket_receive_response (gmyth_socket);
   729 
   730 	if (result != NULL) {
   731 	    gmyth_debug ("Response received from backend: %s", result->str);
   732 	    g_string_free (result, TRUE);
   733 	}
   734 
   735 	g_string_free (hostname, TRUE);
   736 	g_string_free (base_str, TRUE);
   737 
   738 	return TRUE;
   739     } else {
   740 	g_warning ("[%s] GMythSocket could not connect to the backend", __FUNCTION__);	
   741 	return FALSE;
   742     }
   743 }
   744 
   745 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   746  * supported by the backend and send the "ANN" command.
   747  * 
   748  * @param gmyth_socket the GMythSocket instance.
   749  * @param hostname_backend The backend hostname or IP address.
   750  * @param port The backend port to connect.
   751  * @param blocking_client A flag to choose between blocking and non-blocking 
   752  */
   753 gboolean
   754 gmyth_socket_connect_to_backend (GMythSocket *gmyth_socket, 
   755 	const gchar *hostname_backend, gint port, gboolean blocking_client)
   756 {
   757     if (!gmyth_socket_connect_to_backend_and_events ( gmyth_socket, hostname_backend, port,
   758     		blocking_client, FALSE) ) {
   759 		gmyth_debug ("Could not open socket to backend machine [%s]\n",
   760 					hostname_backend );
   761 		return FALSE;
   762     }
   763     
   764     return TRUE;
   765 
   766 }
   767 
   768 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   769  * supported by the backend and send the "ANN" command.
   770  * 
   771  * @param gmyth_socket the GMythSocket instance.
   772  * @param hostname_backend The backend hostname or IP address.
   773  * @param port The backend port to connect.
   774  * @param blocking_client A flag to choose between blocking and non-blocking 
   775  */
   776 gboolean
   777 gmyth_socket_connect_to_backend_events (GMythSocket *gmyth_socket, 
   778 	const gchar *hostname_backend, gint port, gboolean blocking_client)
   779 {
   780     if (!gmyth_socket_connect_to_backend_and_events ( gmyth_socket, hostname_backend, port,
   781     		blocking_client, TRUE) ) {
   782 		gmyth_debug ("Could not open socket to backend machine in order to receive events [%s]\n",
   783 					hostname_backend );
   784 		return FALSE;
   785     }
   786     
   787     return TRUE;
   788 }
   789 
   790 /** Closes the socket connection to the backend.
   791  * 
   792  * @param gmyth_socket The GMythSocket instance.
   793  */
   794 void
   795 gmyth_socket_close_connection (GMythSocket *gmyth_socket)
   796 {
   797     close (gmyth_socket->sd);	
   798     gmyth_socket->sd = -1;
   799 
   800     if (gmyth_socket->sd_io_ch != NULL) {
   801         g_io_channel_unref (gmyth_socket->sd_io_ch);
   802         gmyth_socket->sd_io_ch = NULL;
   803     }
   804 }
   805 
   806 
   807 /** Try the MythTV version numbers, and get the version returned by
   808  * the possible REJECT message, in order to contruct a new
   809  * MythTV version request.
   810  * 
   811  * @param gmyth_socket The GMythSocket instance.
   812  * @param mythtv_version The Mythtv protocol version to be tested
   813  * 
   814  * @return The actual MythTV the client is connected to.
   815  */
   816 gint
   817 gmyth_socket_check_protocol_version_number (GMythSocket *gmyth_socket, gint mythtv_version)
   818 {
   819     GString *response = NULL;
   820     GString *payload = NULL;
   821     gboolean res = TRUE;
   822     gint mythtv_new_version = MYTHTV_CANNOT_NEGOTIATE_VERSION;
   823     guint max_iterations = MYTHTV_MAX_VERSION_CHECKS;
   824 
   825 try_new_version:
   826     payload = g_string_new ("MYTH_PROTO_VERSION");
   827     g_string_append_printf( payload, " %d", mythtv_version );
   828 
   829     gmyth_socket_send_command(gmyth_socket, payload);
   830     response = gmyth_socket_receive_response(gmyth_socket);
   831 
   832     if (response == NULL) {
   833 		g_warning ("[%s] Check protocol version error! Not answered!", __FUNCTION__);
   834 		res = FALSE;	
   835 		goto done;
   836     }
   837 
   838     res = g_str_has_prefix (response->str, "ACCEPT");
   839     if (!res) {
   840 		g_warning ("[%s] Protocol version request error: %s", __FUNCTION__, response->str);
   841 	/* get the version number returned by the REJECT message */
   842 	if ( ( res = g_str_has_prefix (response->str, "REJECT") ) == TRUE ) {
   843         gchar *new_version = NULL;
   844 	    new_version = g_strrstr( response->str, "]" );
   845 	    if (new_version!=NULL) {
   846 		++new_version; /* skip ']' character */
   847 		if ( new_version != NULL ) {
   848 		    gmyth_debug ( "[%s] got MythTV version = %s.\n", __FUNCTION__, new_version );
   849 		    mythtv_version = (gint)g_ascii_strtoull (new_version, NULL, 10 );
   850 		    /* do reconnection to the socket (socket is closed if the MythTV version was wrong) */
   851 		    gmyth_socket_connect( gmyth_socket, gmyth_socket->hostname, gmyth_socket->port );
   852             new_version =NULL;
   853 		    if ( --max_iterations > 0 ) 
   854 		    	goto try_new_version;
   855 		    else
   856 		    	goto done;
   857 		}
   858 	    }
   859 	}
   860     }
   861     
   862     /* change the return value to a valid one */
   863     if ( res ) {
   864     	mythtv_new_version = mythtv_version;
   865     	gmyth_socket->mythtv_version = mythtv_new_version;
   866     }
   867 
   868 done:
   869     if ( payload != NULL )
   870 		g_string_free (payload, TRUE);
   871     if ( response != NULL )
   872 		g_string_free (response, TRUE);
   873 
   874     return mythtv_new_version;
   875 }
   876 
   877 /** Verifies if the Mythtv backend supported the GMyth supported version.
   878  * 
   879  * @param gmyth_socket The GMythSocket instance.
   880  * @return TRUE if supports, FALSE if not.
   881  */
   882 gboolean
   883 gmyth_socket_check_protocol_version (GMythSocket *gmyth_socket)
   884 {
   885     return ( ( gmyth_socket->mythtv_version = 
   886     		gmyth_socket_check_protocol_version_number ( gmyth_socket, 
   887     							MYTHTV_VERSION_DEFAULT ) ) != MYTHTV_CANNOT_NEGOTIATE_VERSION );
   888 }
   889 
   890 /** Returns the Mythtv backend supported version.
   891  * 
   892  * @param gmyth_socket The GMythSocket instance.
   893  * @return The actual MythTV version number.
   894  */
   895 gint
   896 gmyth_socket_get_protocol_version (GMythSocket *gmyth_socket) 
   897 {
   898 	return gmyth_socket->mythtv_version;
   899 }
   900 
   901 /** Receives a backend answer after a gmyth_socket_send_command_call ().
   902  * 
   903  * @param gmyth_socket The GMythSocket instance.
   904  * @return The response received, or NULL if error or nothing was received.
   905  */
   906 GString*
   907 gmyth_socket_receive_response(GMythSocket *gmyth_socket)
   908 {
   909     GIOStatus io_status = G_IO_STATUS_NORMAL;
   910     GError* error = NULL;
   911     gchar *buffer;
   912 
   913     GString *str = NULL;
   914 
   915     gsize bytes_read = 0;
   916     gint  len = 0;
   917     GIOCondition io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
   918 
   919     g_return_val_if_fail( gmyth_socket != NULL, NULL );
   920 
   921     /* verify if the input (read) buffer is ready to receive data */
   922 
   923     //g_static_mutex_lock( &mutex );
   924 
   925     //buffer = g_new0 (gchar, MYTH_PROTOCOL_FIELD_SIZE);
   926     buffer = g_strnfill (MYTH_PROTOCOL_FIELD_SIZE, ' ');
   927     io_status = g_io_channel_read_chars (gmyth_socket->sd_io_ch, buffer, MYTH_PROTOCOL_FIELD_SIZE, &bytes_read, &error);
   928 
   929     /* verify if the input (read) buffer is ready to receive data */
   930     io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
   931 
   932     gmyth_debug ( "[%s] Bytes read = %d\n", __FUNCTION__, bytes_read );
   933 
   934     if( (io_status == G_IO_STATUS_ERROR) || (bytes_read <= 0) ) {
   935 		g_warning ("[%s] Error in mythprotocol response from backend\n", __FUNCTION__);
   936 		str = NULL;
   937 		//return NULL;
   938     } else {
   939 
   940 		io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
   941 		/* verify if the input (read) buffer is ready to receive data */
   942 		io_cond = g_io_channel_get_buffer_condition( gmyth_socket->sd_io_ch );
   943 	
   944 		//if ( ( io_cond & G_IO_IN ) != 0 ) {
   945             //gchar *buffer_aux = NULL;
   946 
   947 		    /* removes trailing whitespace */
   948 		    //buffer_aux = g_strstrip (buffer);
   949 		    len = (gint)g_ascii_strtoull ( g_strstrip (buffer), NULL, 10 );
   950 
   951             if (buffer != NULL) {
   952                 g_free (buffer);
   953                 buffer = NULL;
   954             }
   955             
   956             /*            
   957             if (buffer_aux != NULL) {
   958                 g_free (buffer_aux);
   959                 buffer_aux = NULL;
   960             }
   961             */
   962 
   963             buffer = g_new0 (gchar, len+1);
   964 	
   965 		    bytes_read = 0;
   966 		    io_status = g_io_channel_read_chars( gmyth_socket->sd_io_ch, buffer, len, &bytes_read, &error);
   967 		    buffer[bytes_read] = '\0';
   968 		//}
   969     }  
   970 
   971     //g_static_mutex_unlock( &mutex );
   972 
   973     gmyth_debug ("Response received from backend: {%s}\n", buffer);
   974 
   975     if ( ( bytes_read != len ) || ( io_status == G_IO_STATUS_ERROR ) )
   976 		str = NULL;
   977     else
   978 		str = g_string_new (buffer);
   979 
   980     if ( error != NULL ) {
   981 		g_printerr( "[%s] Error found receiving response from the IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
   982 		str = NULL;
   983 		g_error_free (error);
   984     }
   985 
   986     g_free (buffer);
   987     return str;
   988 }
   989 
   990 /** Format a Mythtv command from the str_list entries and send it to backend.
   991  * 
   992  * @param gmyth_socket The GMythSocket instance.
   993  * @param str_list The string list to form the command
   994  * @return TRUE if command was sent, FALSE if any error happens.
   995  */
   996 gboolean
   997 gmyth_socket_write_stringlist(GMythSocket *gmyth_socket, GMythStringList* str_list)
   998 {
   999 
  1000     GList *tmp_list = NULL;
  1001     GPtrArray *ptr_array = NULL;
  1002     gchar *str_array = NULL;
  1003 
  1004     g_static_mutex_lock( &mutex );
  1005 
  1006     ptr_array = g_ptr_array_sized_new (g_list_length(str_list->glist));
  1007 
  1008     // FIXME: change this implementation!
  1009     tmp_list = str_list->glist;
  1010     for(; tmp_list; tmp_list = tmp_list->next) {
  1011 	if ( tmp_list->data != NULL ) {
  1012 	    g_ptr_array_add(ptr_array, ((GString*)tmp_list->data)->str);
  1013 	} else {
  1014 	    g_ptr_array_add (ptr_array, "");
  1015 	}
  1016     }
  1017     g_ptr_array_add(ptr_array, NULL); // g_str_joinv() needs a NULL terminated string
  1018 
  1019     str_array = g_strjoinv (MYTH_SEPARATOR, (gchar **) (ptr_array->pdata));
  1020 
  1021     g_static_mutex_unlock( &mutex );
  1022 
  1023     gmyth_debug ( "[%s] Sending socket request: %s\n", __FUNCTION__, str_array );
  1024 
  1025     // Sends message to backend	
  1026     // TODO: implement looping to send remaining data, and add timeout testing!    
  1027     GString *command = g_string_new(str_array);
  1028     gmyth_socket_send_command(gmyth_socket, command);
  1029     g_string_free (command, TRUE);
  1030 
  1031     g_free (str_array);
  1032     g_ptr_array_free (ptr_array, TRUE);
  1033 
  1034     return TRUE;
  1035 }
  1036 
  1037 /* Receives a backend command response and split it into the given string list.
  1038  * 
  1039  * @param gmyth_socket The GMythSocket instance.
  1040  * @param str_list the string list to be filled.
  1041  * @return The number of received strings.
  1042  */
  1043 gint
  1044 gmyth_socket_read_stringlist (GMythSocket *gmyth_socket, GMythStringList* str_list)
  1045 {
  1046     GString *response;
  1047     gchar **str_array;
  1048     gint i;
  1049 
  1050     response = gmyth_socket_receive_response(gmyth_socket);
  1051     g_static_mutex_lock( &mutex );
  1052 
  1053     gmyth_string_list_clear_all (str_list);	
  1054     str_array = g_strsplit (response->str, MYTH_SEPARATOR, -1);
  1055 
  1056     for (i=0; i< g_strv_length (str_array); i++) {
  1057 	gmyth_string_list_append_char_array (str_list, str_array[i] );
  1058     }
  1059     g_static_mutex_unlock( &mutex );
  1060 
  1061     g_string_free (response, TRUE);
  1062     g_strfreev (str_array);
  1063 
  1064     return gmyth_string_list_length (str_list);
  1065 }
  1066 
  1067 /** Formats a Mythtv protocol command based on str_list and sends it to
  1068  * the connected backend. The backend response is overwritten into str_list.
  1069  *
  1070  * @param gmyth_socket The GMythSocket instance.
  1071  * @param str_list The string list to be sent, and on which the answer 
  1072  * will be written.
  1073  * @return TRUE if command was sent and an answer was received, FALSE if any
  1074  * error happens.
  1075  */
  1076 gint
  1077 gmyth_socket_sendreceive_stringlist (GMythSocket *gmyth_socket, GMythStringList *str_list)
  1078 {
  1079     gmyth_socket_write_stringlist (gmyth_socket, str_list);
  1080 
  1081     return gmyth_socket_read_stringlist (gmyth_socket, str_list);
  1082 }