[svn r367] Itsn't mandatory to have database information in the GMyth URI.
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 #include <sys/ioctl.h>
58 #include "gmyth_stringlist.h"
59 #include "gmyth_uri.h"
60 #include "gmyth_debug.h"
63 #define MYTH_SEPARATOR "[]:[]"
64 #define MYTH_PROTOCOL_FIELD_SIZE 8
66 /* max number of iterations */
67 #define MYTHTV_MAX_VERSION_CHECKS 40
69 // FIXME: put this in the right place
70 #define MYTHTV_VERSION_DEFAULT 30
72 static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
74 static gchar* local_hostname = NULL;
76 static void gmyth_socket_class_init (GMythSocketClass *klass);
77 static void gmyth_socket_init (GMythSocket *object);
79 static void gmyth_socket_dispose (GObject *object);
80 static void gmyth_socket_finalize (GObject *object);
82 G_DEFINE_TYPE(GMythSocket, gmyth_socket, G_TYPE_OBJECT)
85 gmyth_socket_class_init (GMythSocketClass *klass)
87 GObjectClass *gobject_class;
89 gobject_class = (GObjectClass *) klass;
91 gobject_class->dispose = gmyth_socket_dispose;
92 gobject_class->finalize = gmyth_socket_finalize;
96 gmyth_socket_init (GMythSocket *gmyth_socket)
99 /* gmyth_socket->local_hostname = NULL; */
103 /** Gets the some important address translation info, from the client socket
104 * that will open a connection.
106 * @return gint that represents the error number from getaddrinfo().
109 gmyth_socket_toaddrinfo (const gchar *addr, gint port, struct addrinfo **addrInfo )
111 struct addrinfo hints;
112 gchar *portStr = NULL;
113 gint errorn = EADDRNOTAVAIL;
115 g_return_val_if_fail ( addr != NULL, -1 );
116 g_debug ("Calling %s\n", __FUNCTION__);
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; */
125 portStr = g_strdup_printf ( "%d", port );
129 gmyth_debug ("Getting name resolution for: %s, %d\n", addr, port);
131 if ( ( errorn = getaddrinfo(addr, portStr, &hints, addrInfo) ) != 0 ) {
132 g_printerr( "[%s] Socket ERROR: %s\n", __FUNCTION__, gai_strerror(errorn) );
135 /* g_free (hints); */
140 gmyth_socket_find_match_address_uri( GMythURI* uri, gchar *address ) {
142 if ( g_ascii_strcasecmp( gmyth_uri_get_host( uri ), address ) == 0 ) {
143 //g_printerr( "Found URI: %s !!!\n", rui_uri_getvalue(uri) );
151 static const gchar *PATH_PROC_NET_DEV = "/proc/net/dev";
153 /** Gets the list of all local network interfaces (using the /proc/net/dev directory).
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.
160 gmyth_socket_get_local_addrs( GList *current_connections )
163 GList *local_addrs = NULL;
171 s = socket(AF_INET, SOCK_DGRAM, 0);
174 fd = fopen(PATH_PROC_NET_DEV, "r");
175 fgets(buffer, sizeof(buffer)-1, fd);
176 fgets(buffer, sizeof(buffer)-1, fd);
180 if (fgets(buffer, sizeof(buffer)-1, fd) == NULL)
182 sep = strrchr(buffer, ':');
185 while (*ifname == ' ')
188 strcpy(req.ifr_name, ifname);
189 if (ioctl(s, SIOCGIFFLAGS, &req) < 0)
191 if (!(req.ifr_flags & IFF_UP))
193 if (req.ifr_flags & IFF_LOOPBACK)
195 if (ioctl(s, SIOCGIFADDR, &req) < 0)
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 ) );
200 gmyth_debug( "( from the /proc/net/dev) Interface name: %s, address: %s\n",
211 * Get only the local addresses from the primary interface
214 gmyth_socket_get_primary_addr()
217 gchar *if_eth0 = g_new0( gchar, sizeof(struct ifaddr)-1 );
218 GList *if_tmp = NULL;
220 GList *interfs = gmyth_socket_get_local_addrs( NULL );
222 if ( interfs != NULL && ( g_list_length( interfs ) > 0 ) )
224 /* get the first occurrence (primary interface) */
225 if_tmp = g_list_first( interfs );
227 if ( if_tmp != NULL )
228 g_strlcpy (if_eth0, (gchar *)if_tmp->data, sizeof(struct ifaddr)-1 );
232 if ( interfs != NULL )
233 g_list_free( interfs );
238 /** This function retrieves the local hostname of the
241 * @return GString* get local hostname.
244 gmyth_socket_get_local_hostname ()
248 gint res = gethostname (hname, 50);
251 g_debug ("Error while getting hostname");
255 return g_string_new (hname);
260 if ( local_hostname != NULL && strlen(local_hostname) > 0 )
261 return g_string_new( local_hostname );
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];
270 if (gethostname (localhostname, MAXHOSTNAMELEN) != 0 ) {
271 gmyth_debug ( "Error on gethostname" );
273 localhostname[MAXHOSTNAMELEN-1] = 0;
275 gint err = gmyth_socket_toaddrinfo (localhostname, -1, &addr_info_data );
277 if ( err == EADDRNOTAVAIL )
279 g_warning( "[%s] Address (%s) not available. (reason = %d)\n", __FUNCTION__, localhostname, err );
283 g_static_mutex_lock( &mutex );
285 addr_info0 = addr_info_data;
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 );
291 if ( localaddr != NULL && ( g_strrstr( localaddr, "127" ) == NULL ) ) {
292 str = g_string_new (localaddr);
298 if (localaddr != NULL) {
304 addr_info0 = addr_info0->ai_next;
307 freeaddrinfo (addr_info_data);
308 addr_info_data = NULL;
310 if ( found_addr == FALSE ) {
311 gchar *prim_addr = gmyth_socket_get_primary_addr();
313 if ( prim_addr != NULL ) {
314 g_warning("[%s] Could not determine the local alphanumerical hostname. Setting to %s\n",
315 __FUNCTION__, prim_addr );
317 str = g_string_new (prim_addr);
320 str = g_string_new (localhostname);
324 g_static_mutex_unlock (&mutex);
326 if ( str != NULL && str->str != NULL )
327 local_hostname = g_strdup( str->str );
334 gmyth_socket_dispose (GObject *object)
336 GMythSocket *gmyth_socket = GMYTH_SOCKET(object);
338 /* disconnect socket */
339 gmyth_socket_close_connection (gmyth_socket);
341 g_free (gmyth_socket->hostname);
342 gmyth_socket->hostname = NULL;
344 g_free (local_hostname);
346 local_hostname = NULL;
348 G_OBJECT_CLASS (gmyth_socket_parent_class)->dispose (object);
352 gmyth_socket_finalize (GObject *object)
354 g_signal_handlers_destroy (object);
356 G_OBJECT_CLASS (gmyth_socket_parent_class)->finalize (object);
359 /** Creates a new instance of GMythSocket.
361 * @return a new instance of GMythSocket.
366 GMythSocket *gmyth_socket = GMYTH_SOCKET (g_object_new(GMYTH_SOCKET_TYPE, NULL));
368 gmyth_socket->mythtv_version = MYTHTV_VERSION_DEFAULT;
373 /** Try to open an asynchronous connection to the MythTV backend.
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.
383 gmyth_socket_try_connect ( gint fd, struct sockaddr *remote, gint len,
384 struct timeval *timeout, gint *err)
386 /*g_return_val_if_fail( timeout != NULL, 0 );*/
387 gint saveflags, ret, back_err;
391 saveflags = fcntl( fd, F_GETFL, 0 );
392 if( saveflags < 0 ) {
393 g_warning( "[%s] Problems when getting socket flags on fcntl.\n", __FUNCTION__ );
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__ );
405 /* This will return immediately */
406 *err= connect ( fd, remote, len );
410 if( fcntl( fd, F_SETFL, saveflags ) < 0) {
411 g_warning( "[%s] Problems when trying to restore flags with fcntl.\n", __FUNCTION__ );
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__ );
427 *err = select( FD_SETSIZE, NULL, &fd_w, NULL, timeout);
429 g_warning( "[%s] Connection unsucessfull (timed out).\n", __FUNCTION__ );
434 /* 0 means it timeout out & no fds changed */
441 /* Get the return code from the connect */
443 *err=getsockopt( fd, SOL_SOCKET, SO_ERROR, &ret, (socklen_t *) &len);
446 g_warning( "[%s] Connection usnsucessfull.\n", __FUNCTION__ );
451 /* ret=0 means success, otherwise it contains the errno */
461 /** Connects to the backend.
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.
471 gmyth_socket_connect (GMythSocket *gmyth_socket,
472 const gchar *hostname, gint port)
474 return gmyth_socket_connect_with_timeout (gmyth_socket,
479 gmyth_socket_connect_with_timeout (GMythSocket *gmyth_socket,
480 const gchar *hostname, gint port, guint timeout)
482 struct addrinfo *addr_info_data = NULL, *addr_info0 = NULL;
487 gmyth_debug ("CONNECTING %s:%d", hostname, port);
489 if ( hostname == NULL )
490 gmyth_debug ( "Invalid hostname parameter!\n");
492 /* store hostname and port number */
493 if (gmyth_socket->hostname != NULL) {
494 //g_free (gmyth_socket->hostname);
495 gmyth_socket->hostname = NULL;
498 errno = gmyth_socket_toaddrinfo ( hostname, port, &addr_info_data );
500 g_return_val_if_fail( addr_info_data != NULL && hostname != NULL, FALSE );
502 gmyth_socket->hostname = g_strdup( hostname );
503 gmyth_socket->port = port;
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 );
510 if ( gmyth_socket->sd < 0 )
513 struct timeval *timeout_val = g_new0 (struct timeval, 1);
515 /*timeout_val = g_new0 (struct timeval, 1);*/
517 timeout_val->tv_sec = timeout;
518 timeout_val->tv_usec = 0;
520 timeout_val->tv_sec = 5;
521 timeout_val->tv_usec = 100;
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 )
527 g_printerr( "[%s] Error connecting to backend!\n", __FUNCTION__ );
528 if (ret_code == ETIMEDOUT)
529 g_printerr( "[%s]\tBackend host unreachable!\n", __FUNCTION__ );
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);
538 g_free (timeout_val);
540 /* only will be reached if none of the error above occurred */
544 freeaddrinfo (addr_info_data);
545 addr_info_data = NULL;
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;
552 gmyth_socket->sd_io_ch = g_io_channel_unix_new (gmyth_socket->sd);
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
559 //g_io_channel_set_flags (gmyth_socket->sd_io_ch, flags, NULL);
561 ret = ( ret_code == 0 ) ? TRUE : FALSE ;
565 /** Gets the GIOChannel associated to the given GMythSocket.
567 * @param gmyth_socket The GMythSocket instance.
570 gmyth_socket_get_io_channel( GMythSocket *gmyth_socket )
572 g_return_val_if_fail( gmyth_socket != NULL, NULL );
574 return gmyth_socket->sd_io_ch;
577 /** Verifies if the socket is able to read.
579 * @param gmyth_socket The GMythSocket instance.
580 * @return TRUE if the socket is able to read, FALSE if not.
583 gmyth_socket_is_able_to_read( GMythSocket *gmyth_socket )
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 );
590 if ( ( io_cond & G_IO_IN ) == 0 ) {
591 g_warning ("[%s] IO channel is not able to send data!\n", __FUNCTION__);
599 /** Verifies if the socket is able to write.
601 * @param gmyth_socket The GMythSocket instance.
602 * @return TRUE if the socket is able to write, FALSE if not.
605 gmyth_socket_is_able_to_write( GMythSocket *gmyth_socket )
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 );
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__);
621 /** Sends a command to the backend.
623 * @param gmyth_socket the GMythSocket instance.
624 * @param command The string command to be sent.
627 gmyth_socket_send_command(GMythSocket *gmyth_socket, GString *command)
631 GIOStatus io_status = G_IO_STATUS_NORMAL;
632 //GIOCondition io_cond;
633 GError* error = NULL;
636 gchar *buffer = NULL;
638 gsize bytes_written = 0;
640 if( command == NULL || ( command->len <= 0 ) || command->str == NULL ) {
641 g_warning ("[%s] Invalid NULL command parameter!\n", __FUNCTION__);
646 //g_static_mutex_lock( &mutex );
647 gmyth_debug ("Sending command to backend: %s\n", command->str);
649 buffer = g_strnfill( BUFLEN, ' ' );
650 g_snprintf( buffer, MYTH_PROTOCOL_FIELD_SIZE+1, "%-8d", command->len);
652 command = g_string_prepend(command, buffer);
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 );
659 if( (io_status == G_IO_STATUS_ERROR) || ( bytes_written <= 0 ) ) {
660 g_warning ("[%s] Error while writing to socket", __FUNCTION__);
662 } else if ( bytes_written < command->len ) {
663 g_warning ("[%s] Not all data was written socket", __FUNCTION__);
667 io_status = g_io_channel_flush( gmyth_socket->sd_io_ch, &error );
669 if ( ( bytes_written != command->len ) || ( io_status == G_IO_STATUS_ERROR ) )
671 g_warning ("[%s] Some problem occurred when sending data to the socket\n", __FUNCTION__);
676 //g_static_mutex_unlock( &mutex );
678 if ( error != NULL ) {
679 g_printerr( "[%s] Error found reading data from IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
681 g_error_free( error );
690 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
691 * supported by the backend and send the "ANN" command.
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.
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)
705 if (!gmyth_socket_connect (gmyth_socket, hostname_backend, port)) {
706 g_warning ("[%s] Could not open socket to backend machine [%s]\n", __FUNCTION__,
711 if ( gmyth_socket_check_protocol_version (gmyth_socket) ) {
714 GString *base_str = g_string_new("");
715 GString *hostname = NULL;
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");
723 g_string_printf(base_str, "ANN %s %s %u",
724 (blocking_client ? "Playback" : "Monitor"),
725 hostname->str, with_events);
727 gmyth_socket_send_command (gmyth_socket, base_str);
728 result = gmyth_socket_receive_response (gmyth_socket);
730 if (result != NULL) {
731 gmyth_debug ("Response received from backend: %s", result->str);
732 g_string_free (result, TRUE);
735 g_string_free (hostname, TRUE);
736 g_string_free (base_str, TRUE);
740 g_warning ("[%s] GMythSocket could not connect to the backend", __FUNCTION__);
745 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
746 * supported by the backend and send the "ANN" command.
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
754 gmyth_socket_connect_to_backend (GMythSocket *gmyth_socket,
755 const gchar *hostname_backend, gint port, gboolean blocking_client)
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",
768 /** Starts Mythtv protocol level connection. Checks Mythtv protocol version
769 * supported by the backend and send the "ANN" command.
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
777 gmyth_socket_connect_to_backend_events (GMythSocket *gmyth_socket,
778 const gchar *hostname_backend, gint port, gboolean blocking_client)
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",
790 /** Closes the socket connection to the backend.
792 * @param gmyth_socket The GMythSocket instance.
795 gmyth_socket_close_connection (GMythSocket *gmyth_socket)
797 close (gmyth_socket->sd);
798 gmyth_socket->sd = -1;
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;
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.
811 * @param gmyth_socket The GMythSocket instance.
812 * @param mythtv_version The Mythtv protocol version to be tested
814 * @return The actual MythTV the client is connected to.
817 gmyth_socket_check_protocol_version_number (GMythSocket *gmyth_socket, gint mythtv_version)
819 GString *response = NULL;
820 GString *payload = NULL;
822 gint mythtv_new_version = MYTHTV_CANNOT_NEGOTIATE_VERSION;
823 guint max_iterations = MYTHTV_MAX_VERSION_CHECKS;
826 payload = g_string_new ("MYTH_PROTO_VERSION");
827 g_string_append_printf( payload, " %d", mythtv_version );
829 gmyth_socket_send_command(gmyth_socket, payload);
830 response = gmyth_socket_receive_response(gmyth_socket);
832 if (response == NULL) {
833 g_warning ("[%s] Check protocol version error! Not answered!", __FUNCTION__);
838 res = g_str_has_prefix (response->str, "ACCEPT");
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 );
853 if ( --max_iterations > 0 )
854 goto try_new_version;
862 /* change the return value to a valid one */
864 mythtv_new_version = mythtv_version;
865 gmyth_socket->mythtv_version = mythtv_new_version;
869 if ( payload != NULL )
870 g_string_free (payload, TRUE);
871 if ( response != NULL )
872 g_string_free (response, TRUE);
874 return mythtv_new_version;
877 /** Verifies if the Mythtv backend supported the GMyth supported version.
879 * @param gmyth_socket The GMythSocket instance.
880 * @return TRUE if supports, FALSE if not.
883 gmyth_socket_check_protocol_version (GMythSocket *gmyth_socket)
885 return ( ( gmyth_socket->mythtv_version =
886 gmyth_socket_check_protocol_version_number ( gmyth_socket,
887 MYTHTV_VERSION_DEFAULT ) ) != MYTHTV_CANNOT_NEGOTIATE_VERSION );
890 /** Returns the Mythtv backend supported version.
892 * @param gmyth_socket The GMythSocket instance.
893 * @return The actual MythTV version number.
896 gmyth_socket_get_protocol_version (GMythSocket *gmyth_socket)
898 return gmyth_socket->mythtv_version;
901 /** Receives a backend answer after a gmyth_socket_send_command_call ().
903 * @param gmyth_socket The GMythSocket instance.
904 * @return The response received, or NULL if error or nothing was received.
907 gmyth_socket_receive_response(GMythSocket *gmyth_socket)
909 GIOStatus io_status = G_IO_STATUS_NORMAL;
910 GError* error = NULL;
915 gsize bytes_read = 0;
917 GIOCondition io_cond = g_io_channel_get_buffer_condition (gmyth_socket->sd_io_ch);
919 g_return_val_if_fail( gmyth_socket != NULL, NULL );
921 /* verify if the input (read) buffer is ready to receive data */
923 //g_static_mutex_lock( &mutex );
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);
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);
932 gmyth_debug ( "[%s] Bytes read = %d\n", __FUNCTION__, bytes_read );
934 if( (io_status == G_IO_STATUS_ERROR) || (bytes_read <= 0) ) {
935 g_warning ("[%s] Error in mythprotocol response from backend\n", __FUNCTION__);
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 );
944 //if ( ( io_cond & G_IO_IN ) != 0 ) {
945 //gchar *buffer_aux = NULL;
947 /* removes trailing whitespace */
948 //buffer_aux = g_strstrip (buffer);
949 len = (gint)g_ascii_strtoull ( g_strstrip (buffer), NULL, 10 );
951 if (buffer != NULL) {
957 if (buffer_aux != NULL) {
963 buffer = g_new0 (gchar, len+1);
966 io_status = g_io_channel_read_chars( gmyth_socket->sd_io_ch, buffer, len, &bytes_read, &error);
967 buffer[bytes_read] = '\0';
971 //g_static_mutex_unlock( &mutex );
973 gmyth_debug ("Response received from backend: {%s}\n", buffer);
975 if ( ( bytes_read != len ) || ( io_status == G_IO_STATUS_ERROR ) )
978 str = g_string_new (buffer);
980 if ( error != NULL ) {
981 g_printerr( "[%s] Error found receiving response from the IO channel: (%d, %s)\n", __FUNCTION__, error->code, error->message );
983 g_error_free (error);
990 /** Format a Mythtv command from the str_list entries and send it to backend.
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.
997 gmyth_socket_write_stringlist(GMythSocket *gmyth_socket, GMythStringList* str_list)
1000 GList *tmp_list = NULL;
1001 GPtrArray *ptr_array = NULL;
1002 gchar *str_array = NULL;
1004 g_static_mutex_lock( &mutex );
1006 ptr_array = g_ptr_array_sized_new (g_list_length(str_list->glist));
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);
1014 g_ptr_array_add (ptr_array, "");
1017 g_ptr_array_add(ptr_array, NULL); // g_str_joinv() needs a NULL terminated string
1019 str_array = g_strjoinv (MYTH_SEPARATOR, (gchar **) (ptr_array->pdata));
1021 g_static_mutex_unlock( &mutex );
1023 gmyth_debug ( "[%s] Sending socket request: %s\n", __FUNCTION__, str_array );
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);
1032 g_ptr_array_free (ptr_array, TRUE);
1037 /* Receives a backend command response and split it into the given string list.
1039 * @param gmyth_socket The GMythSocket instance.
1040 * @param str_list the string list to be filled.
1041 * @return The number of received strings.
1044 gmyth_socket_read_stringlist (GMythSocket *gmyth_socket, GMythStringList* str_list)
1050 response = gmyth_socket_receive_response(gmyth_socket);
1051 g_static_mutex_lock( &mutex );
1053 gmyth_string_list_clear_all (str_list);
1054 str_array = g_strsplit (response->str, MYTH_SEPARATOR, -1);
1056 for (i=0; i< g_strv_length (str_array); i++) {
1057 gmyth_string_list_append_char_array (str_list, str_array[i] );
1059 g_static_mutex_unlock( &mutex );
1061 g_string_free (response, TRUE);
1062 g_strfreev (str_array);
1064 return gmyth_string_list_length (str_list);
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.
1070 * @param gmyth_socket The GMythSocket instance.
1071 * @param str_list The string list to be sent, and on which the answer
1073 * @return TRUE if command was sent and an answer was received, FALSE if any
1077 gmyth_socket_sendreceive_stringlist (GMythSocket *gmyth_socket, GMythStringList *str_list)
1079 gmyth_socket_write_stringlist (gmyth_socket, str_list);
1081 return gmyth_socket_read_stringlist (gmyth_socket, str_list);