gmyth/src/gmyth_socket.c
author rosfran
Mon Jan 29 14:14:26 2007 +0000 (2007-01-29)
branchtrunk
changeset 309 311da9c88a53
parent 278 a24bacc8d752
child 313 f8d246310650
permissions -rw-r--r--
[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.
     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 #if defined(HAVE_IFADDRS_H)
    57 	#include <ifaddrs.h>
    58 #else
    59 	#include <sys/ioctl.h>
    60 #endif
    61 
    62 #include "gmyth_stringlist.h"
    63 #include "gmyth_uri.h"
    64 #include "gmyth_debug.h"
    65 
    66 #define BUFLEN 				        			512
    67 #define MYTH_SEPARATOR 			    		"[]:[]"
    68 #define MYTH_PROTOCOL_FIELD_SIZE		8
    69 
    70 /* max number of iterations */
    71 #define MYTHTV_MAX_VERSION_CHECKS		40
    72 
    73 // FIXME: put this in the right place
    74 #define  MYTHTV_VERSION_DEFAULT			30
    75 
    76 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
    77 
    78 static gchar* local_hostname = NULL;
    79 
    80 static void gmyth_socket_class_init          (GMythSocketClass *klass);
    81 static void gmyth_socket_init                (GMythSocket *object);
    82 
    83 static void gmyth_socket_dispose  (GObject *object);
    84 static void gmyth_socket_finalize (GObject *object);
    85 
    86 G_DEFINE_TYPE(GMythSocket, gmyth_socket, G_TYPE_OBJECT)
    87 
    88 static void
    89 gmyth_socket_class_init (GMythSocketClass *klass)
    90 {
    91     GObjectClass *gobject_class;
    92 
    93     gobject_class = (GObjectClass *) klass;
    94 
    95     gobject_class->dispose  = gmyth_socket_dispose;
    96     gobject_class->finalize = gmyth_socket_finalize;	
    97 }
    98 
    99 static void
   100 gmyth_socket_init (GMythSocket *gmyth_socket)
   101 {
   102 	
   103 	/* gmyth_socket->local_hostname = NULL; */
   104 	
   105 }
   106 
   107 /** Gets the some important address translation info, from the client socket
   108  * that will open a connection.
   109  * 
   110  * @return gint that represents the error number from getaddrinfo(). 
   111  */
   112 static gint
   113 gmyth_socket_toaddrinfo (const gchar *addr, gint port, struct addrinfo **addrInfo )
   114 {
   115     struct addrinfo hints;
   116     gchar *portStr = NULL;
   117     gint errorn = EADDRNOTAVAIL;
   118  
   119     g_return_val_if_fail ( addr != NULL, -1 );
   120 
   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; */
   126     
   127     if ( port != -1 )	
   128         portStr = g_strdup_printf ( "%d", port );
   129     else
   130 				portStr = NULL;
   131 
   132     if ( ( errorn = getaddrinfo(addr, portStr, &hints, addrInfo) ) != 0 ) {
   133 		g_printerr( "[%s] Socket ERROR: %s\n", __FUNCTION__, gai_strerror(errorn) );
   134     }
   135     g_free (portStr);
   136     /* g_free (hints); */
   137     return errorn;
   138 }
   139 
   140 static gint
   141 gmyth_socket_find_match_address_uri( GMythURI* uri, gchar *address ) {
   142 
   143         if ( g_ascii_strcasecmp( gmyth_uri_get_host( uri ), address ) == 0 ) {
   144                 //g_printerr( "Found URI: %s !!!\n", rui_uri_getvalue(uri) );
   145                 return 0;
   146         } else {
   147                 return -1;
   148         }
   149 
   150 }
   151 
   152 #if defined(HAVE_IFADDRS_H)
   153 
   154 /** Gets the list of all local network interfaces.
   155  * 
   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. 
   159  */
   160 static GList *
   161 gmyth_socket_get_local_addrs( GList *current_connections ) {
   162 	
   163 	GList *local_addrs = NULL;
   164 	
   165 	struct ifaddrs *ifaddr = g_malloc0( sizeof(struct ifaddrs) );	
   166 	struct ifaddrs *i = g_malloc0( sizeof(struct ifaddrs) );
   167 
   168 	gchar *addr = g_new0( gchar, NI_MAXHOST+1 );
   169 	gchar *ifname;
   170 	gint ifIdx;
   171 	
   172 	if (getifaddrs(&ifaddr) != 0)
   173 	{
   174 		g_printerr("No addresses for interfaces!\n");
   175 		return NULL;
   176 	}
   177 	
   178 	for ( i = ifaddr; i != NULL; i = i->ifa_next ) {
   179 		if (!(i->ifa_flags & IFF_UP))
   180 			continue;
   181 		if (i->ifa_flags & IFF_LOOPBACK)
   182 			continue;
   183 		if ( getnameinfo(i->ifa_addr, sizeof(struct sockaddr), addr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0 ) {
   184 
   185 			ifname = i->ifa_name;
   186 			ifIdx = if_nametoindex(ifname);
   187 
   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 ) )
   191 			{
   192 				local_addrs = g_list_append( local_addrs, g_strdup( addr ) );				
   193 			}
   194 			
   195 			if ( addr != NULL ) {
   196 				g_free( addr );
   197 				addr = g_new0( gchar, NI_MAXHOST+1 );
   198 			}
   199 
   200 		}
   201 	} /* iterates over network interfaces */
   202 	
   203 	freeifaddrs(ifaddr);
   204 	
   205 	return local_addrs;
   206 
   207 }
   208 
   209 #else
   210 
   211 static const gchar *PATH_PROC_NET_DEV = "/proc/net/dev";
   212 
   213 /** Gets the list of all local network interfaces (using the /proc/net/dev directory).
   214  * 
   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. 
   218  */
   219 static GList *
   220 gmyth_socket_get_local_addrs( GList *current_connections )
   221 {
   222 
   223 	GList *local_addrs = NULL;
   224 	FILE *fd;
   225 	gint s;
   226 	gchar buffer[256+1];
   227 	gchar ifaddr[20+1];
   228 	gchar *ifname;
   229 	gchar *sep;
   230 	
   231 	s = socket(AF_INET, SOCK_DGRAM, 0);
   232 	if (s < 0)
   233 		return 0;
   234 	fd = fopen(PATH_PROC_NET_DEV, "r");
   235 	fgets(buffer, sizeof(buffer)-1, fd);
   236 	fgets(buffer, sizeof(buffer)-1, fd);
   237 	while (!feof(fd)) {
   238 		ifname = buffer;
   239 		sep;
   240 		if (fgets(buffer, sizeof(buffer)-1, fd) == NULL)
   241 			break;
   242 		sep = strrchr(buffer, ':');
   243 		if (sep)
   244 			*sep = 0;
   245 		while (*ifname == ' ')
   246 			ifname++;
   247 		struct ifreq req;
   248 		strcpy(req.ifr_name, ifname);
   249 		if (ioctl(s, SIOCGIFFLAGS, &req) < 0)
   250 			continue;
   251 		if (!(req.ifr_flags & IFF_UP))
   252 			continue;
   253 		if (req.ifr_flags & IFF_LOOPBACK)
   254 			continue;
   255 		if (ioctl(s, SIOCGIFADDR, &req) < 0)
   256 			continue;
   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 ) );
   259 
   260 		gmyth_debug( "( from the /proc/net/dev) Interface name: %s, address: %s\n", 
   261 								ifname, ifaddr );
   262 	}
   263 	fclose(fd);
   264 	close(s);
   265 	return local_addrs;
   266 
   267 }
   268 
   269 #endif
   270 
   271 /**
   272  * Get only the local addresses from the primary interface
   273  */
   274 static gchar *
   275 gmyth_socket_get_primary_addr()
   276 {
   277 	
   278 	gchar *if_eth0 = g_new0( gchar, sizeof(struct ifaddr)-1 );
   279 	GList *if_tmp = NULL;
   280 	
   281 	GList *interfs = gmyth_socket_get_local_addrs( NULL );
   282 	
   283 	if ( interfs != NULL && ( g_list_length( interfs ) > 0 ) ) 
   284 	{
   285 		/* get the first occurrence (primary interface) */
   286 		if_tmp = g_list_first( interfs );
   287 		
   288 		if ( if_tmp != NULL )
   289 			g_strlcpy (if_eth0, (gchar *)if_tmp->data, sizeof(struct ifaddr)-1 );
   290 
   291 	}
   292 	
   293 	if ( interfs != NULL )
   294 		g_list_free( interfs );
   295 	
   296 	return if_eth0;
   297 }
   298 
   299 /** This function retrieves the local hostname of the 
   300  * client machine.
   301  *
   302  * @return GString* get local hostname.
   303  */
   304 GString *
   305 gmyth_socket_get_local_hostname  ()
   306 {
   307     GString *str = NULL;
   308     
   309     if ( local_hostname != NULL && strlen(local_hostname) > 0 )
   310     	return g_string_new( local_hostname );
   311 
   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];
   317 
   318     if (gethostname (localhostname, MAXHOSTNAMELEN) != 0 ) {
   319     	gmyth_debug ( "Error on gethostname" );
   320     }
   321     localhostname[MAXHOSTNAMELEN-1] = 0;
   322 
   323     gint err = gmyth_socket_toaddrinfo (localhostname, -1,  &addr_info_data );
   324     
   325     if ( err == EADDRNOTAVAIL )
   326     {
   327     	g_warning( "[%s] Address (%s) not available. (reason = %d)\n", __FUNCTION__, localhostname, err );
   328     	return str;
   329     }
   330     
   331     g_static_mutex_lock( &mutex );    	
   332 
   333     addr_info0 = addr_info_data;
   334 
   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 );
   338 
   339 	    if ( localaddr != NULL && ( g_strrstr( localaddr, "127" ) == NULL ) ) {
   340 	        str = g_string_new (localaddr);
   341 	        found_addr = TRUE;
   342 		g_free (localaddr);
   343 	        break;
   344 	    }
   345 /*
   346 	    if (localaddr != NULL) {
   347 		g_free (localaddr);
   348 		localaddr = NULL;
   349 	    }
   350 	    */
   351 
   352 	    addr_info0 = addr_info0->ai_next;
   353     };
   354     
   355     freeaddrinfo (addr_info_data);
   356     addr_info_data = NULL;
   357     
   358     if ( found_addr == FALSE ) {
   359         gchar *prim_addr = gmyth_socket_get_primary_addr();
   360 
   361     	if ( prim_addr != NULL ) {
   362 		g_warning("[%s] Could not determine the local alphanumerical hostname. Setting to %s\n",
   363     	        __FUNCTION__, prim_addr );
   364       
   365 	        str = g_string_new (prim_addr);
   366 	        g_free (prim_addr);
   367     	} else {
   368         	str = g_string_new (localhostname);
   369     	}
   370     }
   371 
   372     g_static_mutex_unlock (&mutex);
   373     
   374     if ( str != NULL && str->str != NULL )
   375     	local_hostname = g_strdup( str->str );
   376 
   377     return str;
   378 }
   379 
   380 static void
   381 gmyth_socket_dispose  (GObject *object)
   382 {
   383     GMythSocket *gmyth_socket = GMYTH_SOCKET(object);
   384 
   385     /* disconnect socket */
   386     gmyth_socket_close_connection (gmyth_socket);
   387 
   388     g_free (gmyth_socket->hostname);
   389     gmyth_socket->hostname = NULL;
   390     
   391     g_free (local_hostname);
   392     
   393     local_hostname = NULL;
   394 
   395     G_OBJECT_CLASS (gmyth_socket_parent_class)->dispose (object);
   396 }
   397 
   398 static void
   399 gmyth_socket_finalize (GObject *object)
   400 {
   401     g_signal_handlers_destroy (object);
   402 
   403     G_OBJECT_CLASS (gmyth_socket_parent_class)->finalize (object);
   404 }
   405 
   406 /** Creates a new instance of GMythSocket.
   407  * 
   408  * @return a new instance of GMythSocket.
   409  */
   410 GMythSocket*
   411 gmyth_socket_new ()
   412 {
   413     GMythSocket *gmyth_socket = GMYTH_SOCKET (g_object_new(GMYTH_SOCKET_TYPE, NULL));
   414 
   415     gmyth_socket->mythtv_version = MYTHTV_VERSION_DEFAULT;
   416 
   417     return gmyth_socket;
   418 }
   419 
   420 /** Try to open an asynchronous connection to the MythTV backend.
   421  * 
   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.
   428  */
   429 static gint 
   430 gmyth_socket_try_connect ( gint fd, struct sockaddr *remote, gint len,
   431                struct timeval *timeout, gint *err)
   432 {
   433 	  /*g_return_val_if_fail( timeout != NULL, 0 );*/	  
   434 	  gint saveflags, ret, back_err;
   435 	  
   436 	  fd_set fd_w;
   437 	
   438 	  saveflags = fcntl( fd, F_GETFL, 0 );
   439 	  if( saveflags < 0 ) {
   440 	    g_warning( "[%s] Problems when getting socket flags on fcntl.\n", __FUNCTION__ );
   441 	    *err=errno;
   442 	    return -1;
   443 	  }
   444 	
   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__ );
   448 	    *err=errno;
   449 	    return -1;
   450 	  }
   451 	
   452 	  /* This will return immediately */
   453 	  *err= connect ( fd, remote, len );
   454 		back_err=errno;
   455 	
   456 		/* restore flags */
   457 	  if( fcntl( fd, F_SETFL, saveflags ) < 0) {
   458 	    g_warning( "[%s] Problems when trying to restore flags with fcntl.\n", __FUNCTION__ );
   459 	    *err=errno;
   460 	    return -1;
   461 	  }
   462 	
   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__ );
   467 	    *err = errno;
   468 	    return -1;
   469 	  }
   470 	
   471 	  FD_ZERO( &fd_w );
   472 	  FD_SET( fd, &fd_w );
   473 	
   474 	  *err = select( FD_SETSIZE, NULL, &fd_w, NULL, timeout);
   475 	  if ( *err < 0 ) {
   476 	    g_warning( "[%s] Connection unsucessfull (timed out).\n", __FUNCTION__ );
   477 	    *err=errno;
   478 	    return -1;
   479 	  }
   480 	
   481 	  /* 0 means it timeout out & no fds changed */
   482 	  if(*err==0) {
   483 	    close(fd);
   484 	    *err=ETIMEDOUT;
   485 	    return -1;
   486 	  }
   487 	
   488 	  /* Get the return code from the connect */
   489 	  len = sizeof( ret );
   490 	  *err=getsockopt( fd, SOL_SOCKET, SO_ERROR, &ret, (socklen_t *) &len);
   491 	  
   492 	  if( *err < 0 ) {
   493 	    g_warning( "[%s] Connection usnsucessfull.\n", __FUNCTION__ );
   494 	    *err=errno;
   495 	    return -1;
   496 	  }
   497 	
   498 	  /* ret=0 means success, otherwise it contains the errno */
   499 	  if (ret) {
   500 	    *err=ret;
   501 	    return -1;
   502 	  }
   503 	
   504 	  *err=0;
   505 	  return 0;
   506 }
   507 
   508 /** Connects to the backend.
   509  * 
   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.
   514  */
   515 
   516 
   517 gboolean
   518 gmyth_socket_connect (GMythSocket *gmyth_socket,
   519 	const gchar *hostname, gint port)
   520 {
   521     return gmyth_socket_connect_with_timeout (gmyth_socket,
   522 		    hostname, port, 0);
   523 }
   524 
   525 gboolean
   526 gmyth_socket_connect_with_timeout (GMythSocket *gmyth_socket,
   527 	const gchar *hostname, gint port, guint timeout)
   528 {
   529     struct addrinfo *addr_info_data = NULL, *addr_info0 = NULL;
   530     gint ret_code = -1;
   531     gint errno;
   532     gboolean ret = TRUE;
   533 
   534     gmyth_debug ("CONNECTING %s:%d", hostname, port);
   535 
   536     if ( hostname == NULL )
   537         gmyth_debug ( "Invalid hostname parameter!\n");
   538 
   539     /* store hostname and port number */
   540     if (gmyth_socket->hostname != NULL) {
   541         //g_free (gmyth_socket->hostname);
   542         gmyth_socket->hostname = NULL;
   543     }
   544 
   545     errno = gmyth_socket_toaddrinfo ( hostname, port, &addr_info_data );
   546 
   547     g_return_val_if_fail( addr_info_data != NULL && hostname != NULL, FALSE );
   548 
   549     gmyth_socket->hostname = g_strdup( hostname );
   550     gmyth_socket->port = port;
   551 
   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 );
   556 
   557         if ( gmyth_socket->sd < 0 )
   558             continue;
   559 
   560         struct timeval *timeout_val = g_new0 (struct timeval, 1);
   561 	if (timeout != 0) {
   562 	    /*timeout_val = g_new0 (struct timeval, 1);*/
   563 	    
   564             timeout_val->tv_sec = timeout;
   565             timeout_val->tv_usec = 0;
   566 	} else {
   567             timeout_val->tv_sec = 5;
   568             timeout_val->tv_usec = 100;
   569 	}
   570         
   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 )
   573         {
   574             g_printerr( "[%s] Error connecting to backend!\n", __FUNCTION__ );
   575             if (ret_code == ETIMEDOUT)
   576                 g_printerr( "[%s]\tBackend host unreachable!\n", __FUNCTION__ );
   577 
   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);
   582             continue;
   583         }
   584 
   585 	g_free (timeout_val);
   586 
   587         /* only will be reached if none of the error above occurred */
   588         break;
   589     }
   590 
   591     freeaddrinfo (addr_info_data);
   592     addr_info_data = NULL;
   593 
   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;
   597     }
   598 
   599     gmyth_socket->sd_io_ch = g_io_channel_unix_new (gmyth_socket->sd);
   600     
   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
   605 		 * that */
   606 		//g_io_channel_set_flags (gmyth_socket->sd_io_ch, flags, NULL);
   607 
   608     ret = ( ret_code == 0 ) ? TRUE : FALSE ;
   609     return ret;
   610 }
   611 
   612 /** Gets the GIOChannel associated to the given GMythSocket.
   613  * 
   614  * @param gmyth_socket The GMythSocket instance.
   615  */
   616 GIOChannel *
   617 gmyth_socket_get_io_channel( GMythSocket *gmyth_socket )
   618 {
   619     g_return_val_if_fail( gmyth_socket != NULL, NULL );
   620 
   621     return gmyth_socket->sd_io_ch;
   622 }
   623 
   624 /** Verifies if the socket is able to read.
   625  * 
   626  * @param gmyth_socket The GMythSocket instance.
   627  * @return TRUE if the socket is able to read, FALSE if not.
   628  */
   629 gboolean
   630 gmyth_socket_is_able_to_read( GMythSocket *gmyth_socket )
   631 {
   632     gboolean ret = TRUE;
   633 
   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 );
   636 
   637     if ( ( io_cond & G_IO_IN ) == 0 ) {
   638 	g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
   639 	ret = FALSE;
   640     }
   641 
   642     return ret;
   643 
   644 }
   645 
   646 /** Verifies if the socket is able to write.
   647  * 
   648  * @param gmyth_socket The GMythSocket instance.
   649  * @return TRUE if the socket is able to write, FALSE if not.
   650  */
   651 gboolean
   652 gmyth_socket_is_able_to_write( GMythSocket *gmyth_socket )
   653 {
   654     gboolean ret = TRUE;
   655 
   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 );
   658 
   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__);
   661 	ret = FALSE;
   662     }
   663 
   664     return ret;
   665 
   666 }
   667 
   668 /** Sends a command to the backend.
   669  * 
   670  * @param gmyth_socket the GMythSocket instance.
   671  * @param command The string command to be sent.
   672  */
   673 gboolean
   674 gmyth_socket_send_command(GMythSocket *gmyth_socket, GString *command) 
   675 {
   676     gboolean ret = TRUE;
   677 
   678     GIOStatus io_status = G_IO_STATUS_NORMAL;
   679     //GIOCondition io_cond;
   680     GError* error = NULL;
   681    
   682     
   683     gchar *buffer = NULL;
   684 
   685     gsize bytes_written = 0;
   686 
   687     if( command == NULL || ( command->len <= 0 ) || command->str == NULL ) {
   688 		g_warning ("[%s] Invalid NULL command parameter!\n", __FUNCTION__);
   689 		ret = FALSE;
   690 		goto done;
   691     }
   692 
   693     //g_static_mutex_lock( &mutex );
   694     gmyth_debug ("Sending command to backend: %s\n", command->str);
   695 
   696     buffer = g_strnfill( BUFLEN, ' ' );
   697     g_snprintf( buffer, MYTH_PROTOCOL_FIELD_SIZE+1, "%-8d", command->len);
   698 
   699     command = g_string_prepend(command, buffer);
   700 
   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 );
   704 
   705 
   706     if( (io_status == G_IO_STATUS_ERROR) || ( bytes_written <= 0 ) ) {
   707 		g_warning ("[%s] Error while writing to socket", __FUNCTION__);
   708 		ret = FALSE;
   709     } else if ( bytes_written < command->len ) {
   710 		g_warning ("[%s] Not all data was written socket", __FUNCTION__);
   711 		ret = FALSE;
   712     }
   713 
   714     io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
   715 
   716     if ( ( bytes_written != command->len ) || ( io_status == G_IO_STATUS_ERROR ) )
   717     {
   718 		g_warning ("[%s] Some problem occurred when sending data to the socket\n", __FUNCTION__);
   719 	
   720 		ret = TRUE;
   721     }
   722 
   723     //g_static_mutex_unlock( &mutex );
   724 done:
   725     if ( error != NULL ) {
   726 		g_printerr( "[%s] Error found reading data from IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
   727 		ret = FALSE;
   728 		g_error_free( error );
   729     }
   730 
   731     if ( buffer!= NULL )
   732 		g_free( buffer );
   733 
   734     return ret;
   735 }
   736 
   737 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   738  * supported by the backend and send the "ANN" command.
   739  * 
   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. 
   746  */
   747 static gboolean
   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)
   751 {
   752     if (!gmyth_socket_connect (gmyth_socket, hostname_backend, port)) {
   753 		g_warning ("[%s] Could not open socket to backend machine [%s]\n", __FUNCTION__,
   754 					hostname_backend );
   755 		return FALSE;
   756     }
   757 
   758     if ( gmyth_socket_check_protocol_version (gmyth_socket) ) {
   759 
   760 	GString *result;
   761 	GString *base_str = g_string_new("");
   762 	GString *hostname = NULL;
   763 
   764 	hostname = gmyth_socket_get_local_hostname();
   765 
   766 	g_string_printf(base_str, "ANN %s %s %u", 
   767 		(blocking_client ? "Playback" : "Monitor"),
   768 		hostname->str, with_events);
   769 
   770 	gmyth_socket_send_command (gmyth_socket, base_str);
   771 	result = gmyth_socket_receive_response (gmyth_socket);
   772 
   773 	if (result != NULL) {
   774 	    gmyth_debug ("Response received from backend: %s", result->str);
   775 	    g_string_free (result, TRUE);
   776 	}
   777 
   778 	g_string_free (hostname, TRUE);
   779 	g_string_free (base_str, TRUE);
   780 
   781 	return TRUE;
   782     } else {
   783 	g_warning ("[%s] GMythSocket could not connect to the backend", __FUNCTION__);	
   784 	return FALSE;
   785     }
   786 }
   787 
   788 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   789  * supported by the backend and send the "ANN" command.
   790  * 
   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 
   795  */
   796 gboolean
   797 gmyth_socket_connect_to_backend (GMythSocket *gmyth_socket, 
   798 	const gchar *hostname_backend, gint port, gboolean blocking_client)
   799 {
   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",
   803 					hostname_backend );
   804 		return FALSE;
   805     }
   806     
   807     return TRUE;
   808 
   809 }
   810 
   811 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
   812  * supported by the backend and send the "ANN" command.
   813  * 
   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 
   818  */
   819 gboolean
   820 gmyth_socket_connect_to_backend_events (GMythSocket *gmyth_socket, 
   821 	const gchar *hostname_backend, gint port, gboolean blocking_client)
   822 {
   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",
   826 					hostname_backend );
   827 		return FALSE;
   828     }
   829     
   830     return TRUE;
   831 }
   832 
   833 /** Closes the socket connection to the backend.
   834  * 
   835  * @param gmyth_socket The GMythSocket instance.
   836  */
   837 void
   838 gmyth_socket_close_connection (GMythSocket *gmyth_socket)
   839 {
   840     close (gmyth_socket->sd);	
   841     gmyth_socket->sd = -1;
   842 
   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;
   846     }
   847 }
   848 
   849 
   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.
   853  * 
   854  * @param gmyth_socket The GMythSocket instance.
   855  * @param mythtv_version The Mythtv protocol version to be tested
   856  * 
   857  * @return The actual MythTV the client is connected to.
   858  */
   859 gint
   860 gmyth_socket_check_protocol_version_number (GMythSocket *gmyth_socket, gint mythtv_version)
   861 {
   862     GString *response = NULL;
   863     GString *payload = NULL;
   864     gboolean res = TRUE;
   865     gint mythtv_new_version = MYTHTV_CANNOT_NEGOTIATE_VERSION;
   866     guint max_iterations = MYTHTV_MAX_VERSION_CHECKS;
   867 
   868 try_new_version:
   869     payload = g_string_new ("MYTH_PROTO_VERSION");
   870     g_string_append_printf( payload, " %d", mythtv_version );
   871 
   872     gmyth_socket_send_command(gmyth_socket, payload);
   873     response = gmyth_socket_receive_response(gmyth_socket);
   874 
   875     if (response == NULL) {
   876 		g_warning ("[%s] Check protocol version error! Not answered!", __FUNCTION__);
   877 		res = FALSE;	
   878 		goto done;
   879     }
   880 
   881     res = g_str_has_prefix (response->str, "ACCEPT");
   882     if (!res) {
   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 );
   895             new_version =NULL;
   896 		    if ( --max_iterations > 0 ) 
   897 		    	goto try_new_version;
   898 		    else
   899 		    	goto done;
   900 		}
   901 	    }
   902 	}
   903     }
   904     
   905     /* change the return value to a valid one */
   906     if ( res ) {
   907     	mythtv_new_version = mythtv_version;
   908     	gmyth_socket->mythtv_version = mythtv_new_version;
   909     }
   910 
   911 done:
   912     if ( payload != NULL )
   913 		g_string_free (payload, TRUE);
   914     if ( response != NULL )
   915 		g_string_free (response, TRUE);
   916 
   917     return mythtv_new_version;
   918 }
   919 
   920 /** Verifies if the Mythtv backend supported the GMyth supported version.
   921  * 
   922  * @param gmyth_socket The GMythSocket instance.
   923  * @return TRUE if supports, FALSE if not.
   924  */
   925 gboolean
   926 gmyth_socket_check_protocol_version (GMythSocket *gmyth_socket)
   927 {
   928     return ( ( gmyth_socket->mythtv_version = 
   929     		gmyth_socket_check_protocol_version_number ( gmyth_socket, 
   930     							MYTHTV_VERSION_DEFAULT ) ) != MYTHTV_CANNOT_NEGOTIATE_VERSION );
   931 }
   932 
   933 /** Returns the Mythtv backend supported version.
   934  * 
   935  * @param gmyth_socket The GMythSocket instance.
   936  * @return The actual MythTV version number.
   937  */
   938 gint
   939 gmyth_socket_get_protocol_version (GMythSocket *gmyth_socket) 
   940 {
   941 	return gmyth_socket->mythtv_version;
   942 }
   943 
   944 /** Receives a backend answer after a gmyth_socket_send_command_call ().
   945  * 
   946  * @param gmyth_socket The GMythSocket instance.
   947  * @return The response received, or NULL if error or nothing was received.
   948  */
   949 GString*
   950 gmyth_socket_receive_response(GMythSocket *gmyth_socket)
   951 {
   952     GIOStatus io_status = G_IO_STATUS_NORMAL;
   953     GError* error = NULL;
   954     gchar *buffer;
   955 
   956     GString *str = NULL;
   957 
   958     gsize bytes_read = 0;
   959     gint  len = 0;
   960     GIOCondition io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
   961 
   962     g_return_val_if_fail( gmyth_socket != NULL, NULL );
   963 
   964     /* verify if the input (read) buffer is ready to receive data */
   965 
   966     //g_static_mutex_lock( &mutex );
   967 
   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);
   971 
   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);
   974 
   975     gmyth_debug ( "[%s] Bytes read = %d\n", __FUNCTION__, bytes_read );
   976 
   977     if( (io_status == G_IO_STATUS_ERROR) || (bytes_read <= 0) ) {
   978 		g_warning ("[%s] Error in mythprotocol response from backend\n", __FUNCTION__);
   979 		str = NULL;
   980 		//return NULL;
   981     } else {
   982 
   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 );
   986 	
   987 		//if ( ( io_cond & G_IO_IN ) != 0 ) {
   988             //gchar *buffer_aux = NULL;
   989 
   990 		    /* removes trailing whitespace */
   991 		    //buffer_aux = g_strstrip (buffer);
   992 		    len = (gint)g_ascii_strtoull ( g_strstrip (buffer), NULL, 10 );
   993 
   994             if (buffer != NULL) {
   995                 g_free (buffer);
   996                 buffer = NULL;
   997             }
   998             
   999             /*            
  1000             if (buffer_aux != NULL) {
  1001                 g_free (buffer_aux);
  1002                 buffer_aux = NULL;
  1003             }
  1004             */
  1005 
  1006             buffer = g_new0 (gchar, len+1);
  1007 	
  1008 		    bytes_read = 0;
  1009 		    io_status = g_io_channel_read_chars( gmyth_socket->sd_io_ch, buffer, len, &bytes_read, &error);
  1010 		    buffer[bytes_read] = '\0';
  1011 		//}
  1012     }  
  1013 
  1014     //g_static_mutex_unlock( &mutex );
  1015 
  1016     gmyth_debug ("Response received from backend: {%s}\n", buffer);
  1017 
  1018     if ( ( bytes_read != len ) || ( io_status == G_IO_STATUS_ERROR ) )
  1019 		str = NULL;
  1020     else
  1021 		str = g_string_new (buffer);
  1022 
  1023     if ( error != NULL ) {
  1024 		g_printerr( "[%s] Error found receiving response from the IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
  1025 		str = NULL;
  1026 		g_error_free (error);
  1027     }
  1028 
  1029     g_free (buffer);
  1030     return str;
  1031 }
  1032 
  1033 /** Format a Mythtv command from the str_list entries and send it to backend.
  1034  * 
  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.
  1038  */
  1039 gboolean
  1040 gmyth_socket_write_stringlist(GMythSocket *gmyth_socket, GMythStringList* str_list)
  1041 {
  1042 
  1043     GList *tmp_list = NULL;
  1044     GPtrArray *ptr_array = NULL;
  1045     gchar *str_array = NULL;
  1046 
  1047     g_static_mutex_lock( &mutex );
  1048 
  1049     ptr_array = g_ptr_array_sized_new (g_list_length(str_list->glist));
  1050 
  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);
  1056 	} else {
  1057 	    g_ptr_array_add (ptr_array, "");
  1058 	}
  1059     }
  1060     g_ptr_array_add(ptr_array, NULL); // g_str_joinv() needs a NULL terminated string
  1061 
  1062     str_array = g_strjoinv (MYTH_SEPARATOR, (gchar **) (ptr_array->pdata));
  1063 
  1064     g_static_mutex_unlock( &mutex );
  1065 
  1066     gmyth_debug ( "[%s] Sending socket request: %s\n", __FUNCTION__, str_array );
  1067 
  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);
  1073 
  1074     g_free (str_array);
  1075     g_ptr_array_free (ptr_array, TRUE);
  1076 
  1077     return TRUE;
  1078 }
  1079 
  1080 /* Receives a backend command response and split it into the given string list.
  1081  * 
  1082  * @param gmyth_socket The GMythSocket instance.
  1083  * @param str_list the string list to be filled.
  1084  * @return The number of received strings.
  1085  */
  1086 gint
  1087 gmyth_socket_read_stringlist (GMythSocket *gmyth_socket, GMythStringList* str_list)
  1088 {
  1089     GString *response;
  1090     gchar **str_array;
  1091     gint i;
  1092 
  1093     response = gmyth_socket_receive_response(gmyth_socket);
  1094     g_static_mutex_lock( &mutex );
  1095 
  1096     gmyth_string_list_clear_all (str_list);	
  1097     str_array = g_strsplit (response->str, MYTH_SEPARATOR, -1);
  1098 
  1099     for (i=0; i< g_strv_length (str_array); i++) {
  1100 	gmyth_string_list_append_char_array (str_list, str_array[i] );
  1101     }
  1102     g_static_mutex_unlock( &mutex );
  1103 
  1104     g_string_free (response, TRUE);
  1105     g_strfreev (str_array);
  1106 
  1107     return gmyth_string_list_length (str_list);
  1108 }
  1109 
  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.
  1112  *
  1113  * @param gmyth_socket The GMythSocket instance.
  1114  * @param str_list The string list to be sent, and on which the answer 
  1115  * will be written.
  1116  * @return TRUE if command was sent and an answer was received, FALSE if any
  1117  * error happens.
  1118  */
  1119 gint
  1120 gmyth_socket_sendreceive_stringlist (GMythSocket *gmyth_socket, GMythStringList *str_list)
  1121 {
  1122     gmyth_socket_write_stringlist (gmyth_socket, str_list);
  1123 
  1124     return gmyth_socket_read_stringlist (gmyth_socket, str_list);
  1125 }