Ejemplo n.º 1
0
void lllp_connected_cb(GObject *listener, GAsyncResult *res, gpointer pstore_library) {
	GtkListStore *store_library = GTK_LIST_STORE(pstore_library);
	GSocketConnection *connection;
	GSocketAddress *address;
	gchar *address_char;
	GInputStream *stream;
	GFile *output_file;
	GOutputStream *file_stream;
	gsize count;
	gboolean valid = FALSE;


	connection = g_socket_listener_accept_finish(G_SOCKET_LISTENER(listener), res, NULL, NULL);
	address = g_socket_connection_get_remote_address(connection, NULL);
	address_char = g_inet_address_to_string(g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(address)));
	printf("%s\n", address_char);

	output_file = g_file_new_for_path(address_char);
	g_file_delete(output_file, NULL, NULL);
	file_stream = (GOutputStream*)g_file_replace(output_file, NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION, NULL, NULL);

	stream = g_io_stream_get_input_stream(G_IO_STREAM(connection));
	g_output_stream_splice(file_stream, stream, 
		G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE & G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET, NULL, NULL);
	g_output_stream_close(file_stream, NULL, NULL);

	convert_library_to_list_store(store_library, address_char);

	printf("%s CONNECTED\n", address_char);

	g_socket_listener_accept_async(G_SOCKET_LISTENER(listener), NULL, lllp_connected_cb, store_library);
}
Ejemplo n.º 2
0
void lllp_quit_cb(GObject *listener, GAsyncResult *res, gpointer pstore_library) {
	GtkListStore *store_library = GTK_LIST_STORE(pstore_library);
	gsize i;
	GtkTreeIter iter;
	gboolean valid;
	GSocketConnection *connection;
	GSocketAddress *remote_socket_addr;
	GInetAddress *remote_addr;
	gchar *remote_addr_char;
	gchar *tempchar;

	connection = g_socket_listener_accept_finish(G_SOCKET_LISTENER(listener), res, NULL, NULL);
	remote_socket_addr = g_socket_connection_get_remote_address(connection, NULL);
	remote_addr = g_inet_socket_address_get_address((GInetSocketAddress *)(remote_socket_addr));
	remote_addr_char = g_inet_address_to_string(remote_addr);

	if(connection != NULL) {
		valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store_library), &iter);
		while(valid == TRUE) {
			gtk_tree_model_get(GTK_TREE_MODEL(store_library), &iter, INET_ADDRESS, &tempchar, -1);
			if(g_strcmp0(tempchar, remote_addr_char) == 0)
				gtk_list_store_remove(store_library, &iter);
			valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store_library), &iter);
		}
		
		printf("LLLP %s DISCONNECTED\n", remote_addr_char);
	}
	g_socket_listener_accept_async(G_SOCKET_LISTENER(listener), NULL, lllp_quit_cb, store_library);
}
Ejemplo n.º 3
0
GSocketAddress *
g_vfs_ftp_connection_get_address (GVfsFtpConnection *conn, GError **error)
{
  g_return_val_if_fail (conn != NULL, NULL);

  return g_socket_connection_get_remote_address (conn->connection, error);
}
Ejemplo n.º 4
0
GSocketAddress *
g_vfs_ftp_connection_get_address (GVfsFtpConnection *conn, GError **error)
{
  g_return_val_if_fail (conn != NULL, NULL);

  return g_socket_connection_get_remote_address (G_SOCKET_CONNECTION (conn->commands), error);
}
Ejemplo n.º 5
0
static void
_socket_connect_cb (GObject *object,
		    GAsyncResult *result,
		    gpointer user_data)
{
  GError *error = NULL;
  GMainLoop *loop = user_data;
  GSocketClient *client = G_SOCKET_CLIENT (object);
  GSocketConnection *connection;

  connection = g_socket_client_connect_to_uri_finish (client,
						      result,
						      &error);
  if (connection)
    {
      GSocketAddress *proxy_addr;
      proxy_addr = g_socket_connection_get_remote_address (connection, NULL);
      print_proxy_address (proxy_addr);
    }
  else
    {
      print_and_free_error (error);
    }

  g_main_loop_quit (loop);
}
Ejemplo n.º 6
0
static gchar *
get_remote_address (GIOStream *io)
{
  GSocketAddress *remote = NULL;
  GSocketConnection *connection = NULL;
  GIOStream *base;
  gchar *result = NULL;

  if (G_IS_TLS_CONNECTION (io))
    {
      g_object_get (io, "base-io-stream", &base, NULL);
      if (G_IS_SOCKET_CONNECTION (base))
        connection = g_object_ref (base);
      g_object_unref (base);
    }
  else if (G_IS_SOCKET_CONNECTION (io))
    {
      connection = g_object_ref (io);
    }

  if (connection)
    remote = g_socket_connection_get_remote_address (connection, NULL);
  if (remote && G_IS_INET_SOCKET_ADDRESS (remote))
    result = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (remote)));

  if (remote)
    g_object_unref (remote);
  if (connection)
    g_object_unref (connection);

  return result;
}
Ejemplo n.º 7
0
/**
 * replay_network_server_load_file:
 * @self: A #ReplayNetworkServer
 * @conn: The #GSocketConnection to load events from
 *
 */
void
replay_network_server_load_events(ReplayNetworkServer *self,
                               GSocketConnection *conn)
{
  GError *error = NULL;
  GSocketAddress *address;
  GInetAddress *inet;
  guint16 port;
  gchar *inet_str;
  gchar *description;

  g_return_if_fail(REPLAY_IS_NETWORK_SERVER(self));

  REPLAY_NETWORK_SERVER_GET_CLASS(self)->load_events(self, conn);

  /* set description to the remote address and port */
  address = g_socket_connection_get_remote_address(conn, &error);
  if (address) {
    inet = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(address));
    port = g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(address));
    inet_str = g_inet_address_to_string(inet);
    description = g_strdup_printf("Remote client %s, port %d", inet_str, port);
    replay_event_source_set_description(REPLAY_EVENT_SOURCE(self), description);
    g_free(description);
    g_free(inet_str);
    g_object_unref(address);
  } else {
    g_assert(error);
    replay_event_source_set_description(REPLAY_EVENT_SOURCE(self), error->message);
    g_clear_error(&error);
  }
}
Ejemplo n.º 8
0
static gboolean xingzhe_comes(GSocketService    *service,
                          GSocketConnection *connection,
                          GObject           *src_obj,
                          gpointer           user_data)
{
    GSocketAddress     *addr;
    GInetAddress       *ip_addr;
    gchar *str;
    GSocketFamily  ip_type;
    
    addr = g_socket_connection_get_remote_address(connection, NULL);
    ip_addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(addr));
    ip_type = g_inet_address_get_family(ip_addr);

//    gdk_threads_enter();
    
    g_printf("[WATCHER] Here comes an monkey: ");
    
    str = g_inet_address_to_string(ip_addr);
    g_printf(str);
    g_printf("\n");
//    gdk_threads_leave();
    
    return TRUE;
}
static gboolean
sig_match_conn (TpStreamTubeChannel *self,
    SigWaitingConn *sig,
    ConnWaitingSig *c)
{
  if (self->priv->access_control == TP_SOCKET_ACCESS_CONTROL_PORT)
    {
      /* Use the port to identify the connection */
      guint port;
      GSocketAddress *address;
      GError *error = NULL;

      address = g_socket_connection_get_remote_address (c->conn, &error);
      if (address == NULL)
        {
          DEBUG ("Failed to get connection address: %s", error->message);

          g_error_free (error);
          return FALSE;
        }

      dbus_g_type_struct_get (sig->param, 1, &port, G_MAXINT);

      if (port == g_inet_socket_address_get_port (
            G_INET_SOCKET_ADDRESS (address)))
        {
          DEBUG ("Identified connection %u using port %u",
              port, sig->connection_id);

          g_object_unref (address);
          return TRUE;
        }

      g_object_unref (address);
    }
  else if (self->priv->access_control == TP_SOCKET_ACCESS_CONTROL_CREDENTIALS)
    {
      guchar byte;

      byte = g_value_get_uchar (sig->param);

      return byte == c->byte;
    }
  else
    {
      DEBUG ("Can't properly identify connection as we are using "
          "access control %u. Assume it's the head of the list",
          self->priv->access_control);

      return TRUE;
    }

  return FALSE;
}
Ejemplo n.º 10
0
static void
identd_read_ready (GInputStream *in_stream, GAsyncResult *res, ident_info *info)
{
    GSocketAddress *sok_addr;
    GOutputStream *out_stream;
    guint64 local, remote;
    gchar buf[512], *p;

    if (g_input_stream_read_finish (in_stream, res, NULL))
    {
        local = g_ascii_strtoull (info->read_buf, NULL, 0);
        p = strchr (info->read_buf, ',');
        if (!p)
            goto cleanup;

        remote = g_ascii_strtoull (p + 1, NULL, 0);

        if (!local || !remote || local > G_MAXUINT16 || remote > G_MAXUINT16)
            goto cleanup;

        info->username = g_strdup (g_hash_table_lookup (responses, GINT_TO_POINTER (local)));
        if (!info->username)
            goto cleanup;
        g_hash_table_remove (responses, GINT_TO_POINTER (local));

        if ((sok_addr = g_socket_connection_get_remote_address (info->conn, NULL)))
        {
            GInetAddress *inet_addr;
            gchar *addr;

            inet_addr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (sok_addr));
            addr = g_inet_address_to_string (inet_addr);

            hextor_printf (ph, _("*\tServicing ident request from %s as %s"), addr, info->username);

            g_object_unref (sok_addr);
            g_object_unref (inet_addr);
            g_free (addr);
        }

        g_snprintf (buf, sizeof (buf), "%"G_GUINT16_FORMAT", %"G_GUINT16_FORMAT" : USERID : UNIX : %s\r\n", (guint16)local, (guint16)remote, info->username);
        out_stream = g_io_stream_get_output_stream (G_IO_STREAM (info->conn));
        g_output_stream_write_async (out_stream, buf, strlen (buf), G_PRIORITY_DEFAULT,
                                     NULL, (GAsyncReadyCallback)identd_write_ready, info);
    }

    return;

cleanup:
    g_object_unref (info->conn);
    g_free (info);
}
Ejemplo n.º 11
0
static void
use_socket_client (gboolean synchronous)
{
  GError *error = NULL;
  GSocketClient *client;

  client = g_socket_client_new ();

  printf ("Proxies for URI '%s' are:\n", info);

  if (synchronous)
    {
      GSocketConnection *connection;
      GSocketAddress *proxy_addr;

      connection = g_socket_client_connect_to_uri (client,
						   info,
						   0,
      						   cancellable,
						   &error);

      if (connection)
	{
	  proxy_addr = g_socket_connection_get_remote_address (connection, NULL);
	  print_proxy_address (proxy_addr);
	}
      else
	{
	  print_and_free_error (error);
	}
    }
  else
    {
      GMainLoop *loop = g_main_loop_new (NULL, FALSE);

      g_socket_client_connect_to_uri_async (client,
					    info,
					    0,
					    cancellable,
					    _socket_connect_cb,
					    loop);

      g_main_loop_run (loop);
      g_main_loop_unref (loop);
    }

  g_object_unref (client);
}
static gboolean
on_new_connection (GSocketService * service, GSocketConnection * connection,
    GObject * source_object, gpointer user_data)
{
  Client *client = g_slice_new0 (Client);
  GSocketAddress *addr;
  GInetAddress *iaddr;
  gchar *ip;
  guint16 port;

  addr = g_socket_connection_get_remote_address (connection, NULL);
  iaddr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (addr));
  port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (addr));
  ip = g_inet_address_to_string (iaddr);
  client->name = g_strdup_printf ("%s:%u", ip, port);
  g_free (ip);
  g_object_unref (addr);

  g_print ("New connection %s\n", client->name);

  client->connection = (GSocketConnection *) g_object_ref (connection);
  client->socket = g_socket_connection_get_socket (connection);
  client->istream =
      g_io_stream_get_input_stream (G_IO_STREAM (client->connection));
  client->ostream =
      g_io_stream_get_output_stream (G_IO_STREAM (client->connection));
  client->current_message = g_byte_array_sized_new (1024);

  client->tosource = g_timeout_source_new_seconds (5);
  g_source_set_callback (client->tosource, (GSourceFunc) on_timeout, client,
      NULL);
  g_source_attach (client->tosource, NULL);

  client->isource =
      g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM
      (client->istream), NULL);
  g_source_set_callback (client->isource, (GSourceFunc) on_read_bytes, client,
      NULL);
  g_source_attach (client->isource, NULL);

  G_LOCK (clients);
  clients = g_list_prepend (clients, client);
  G_UNLOCK (clients);

  return TRUE;
}
static void
g_tls_client_connection_gnutls_constructed (GObject *object)
{
  GTlsClientConnectionGnutls *gnutls = G_TLS_CLIENT_CONNECTION_GNUTLS (object);
  GSocketConnection *base_conn;
  GSocketAddress *remote_addr;
  GInetAddress *iaddr;
  guint port;

  /* Create a TLS session ID. We base it on the IP address since
   * different hosts serving the same hostname/service will probably
   * not share the same session cache. We base it on the
   * server-identity because at least some servers will fail (rather
   * than just failing to resume the session) if we don't.
   * (https://bugs.launchpad.net/bugs/823325)
   */
  g_object_get (G_OBJECT (gnutls), "base-io-stream", &base_conn, NULL);
  if (G_IS_SOCKET_CONNECTION (base_conn))
    {
      remote_addr = g_socket_connection_get_remote_address (base_conn, NULL);
      if (G_IS_INET_SOCKET_ADDRESS (remote_addr))
	{
	  GInetSocketAddress *isaddr = G_INET_SOCKET_ADDRESS (remote_addr);
	  const gchar *server_hostname;
	  gchar *addrstr, *session_id;

	  iaddr = g_inet_socket_address_get_address (isaddr);
	  port = g_inet_socket_address_get_port (isaddr);

	  addrstr = g_inet_address_to_string (iaddr);
	  server_hostname = get_server_identity (gnutls);
	  session_id = g_strdup_printf ("%s/%s/%d", addrstr,
					server_hostname ? server_hostname : "",
					port);
	  gnutls->priv->session_id = g_bytes_new_take (session_id, strlen (session_id));
	  g_free (addrstr);
	}
      g_object_unref (remote_addr);
    }
  g_object_unref (base_conn);

  if (G_OBJECT_CLASS (g_tls_client_connection_gnutls_parent_class)->constructed)
    G_OBJECT_CLASS (g_tls_client_connection_gnutls_parent_class)->constructed (object);
}
Ejemplo n.º 14
0
char* xr_servlet_get_client_ip(xr_servlet* servlet)
{
  g_return_val_if_fail(servlet != NULL, NULL);
  g_return_val_if_fail(servlet->conn != NULL, NULL);

  GSocketAddress* addr = g_socket_connection_get_remote_address(servlet->conn->conn, NULL);
  if (addr)
  {
    GInetAddress* inet_addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(addr));

    char* str = g_inet_address_to_string(inet_addr);

    g_object_unref(addr);

    return str;
  }

  return  NULL;
}
Ejemplo n.º 15
0
static gboolean
BP_TCPService_IncomingConnection (GSocketService *service,
              GSocketConnection *incomingConnection,
              GObject *source_object,
              gpointer user_data)
{
  BPTCPService *filter = BP_TCPSERVICE (user_data);

  GSocket *socket = g_socket_connection_get_socket(incomingConnection);
  GSocketAddress *sockaddr = g_socket_connection_get_remote_address(incomingConnection, NULL);
  GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
  gchar* remoteHost = g_inet_address_to_string(addr);
  gint fd = g_socket_get_fd(socket);
  GIOChannel *channel = g_io_channel_unix_new(fd);

  if (filter->mode == BP_MODE_SINK_ONLY) {
    GST_ERROR ("Attempt to accept connection but in sink-only mode");
    return FALSE;
  }

  // Ref connection
  g_object_ref (incomingConnection);

  // Get remote host & port
  filter->remotePort = g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(sockaddr));
  g_string_assign(filter->remoteAddress, remoteHost);
  g_free (remoteHost);

  g_message ("New connection from %s:%d", filter->remoteAddress->str, (int) filter->remotePort);
  g_message ("Attaching IO channel watch ...");

  // Add IO watch with pointer to connection handle as user data for callback
  g_io_add_watch(channel, G_IO_IN, (GIOFunc) BP_TCPService_IncomingConnectionReceive, filter);
  g_io_channel_unref (channel);

  g_message ("Registering connection");

  BP_TCPService_UpdateUID (filter);

  ServerPool_AddInstance (filter->uid, filter->service, incomingConnection);

	return FALSE;
}
Ejemplo n.º 16
0
//New tcp conection
gboolean new_connection(GSocketService *service, GSocketConnection *connection, GObject *source_object, gpointer user_data) {

  //New client connected
  GSocketAddress *sockaddr = g_socket_connection_get_remote_address(connection, NULL);
  GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
  guint16 port = g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(sockaddr));

  if (verbose) {
    printf("App Server: New Connection from %s:%d\n", g_inet_address_to_string(addr), port);
    fflush(stdout);
  }

  //Record client (if new)
  add_client(g_inet_address_to_string(addr), connection);

  g_object_ref (connection);
  GSocket *socket = g_socket_connection_get_socket(connection);

  gint fd = g_socket_get_fd(socket);
  GIOChannel *channel = g_io_channel_unix_new(fd);
  g_io_add_watch(channel, G_IO_IN, (GIOFunc) network_read, connection);
  return TRUE;
}
Ejemplo n.º 17
0
static void
on_socket_client_event (GSocketClient      *client,
                        GSocketClientEvent  event,
                        GSocketConnectable *connectable,
                        GIOStream          *connection,
                        gpointer            user_data)
{
  HotSshTab *self = HOTSSH_TAB (user_data);
  HotSshTabPrivate *priv = hotssh_tab_get_instance_private (self);
  switch (event)
    {
    case G_SOCKET_CLIENT_RESOLVING:
      set_status_printf (self, _("Resolving '%s'…"),
                         priv->hostname);
      break;
    case G_SOCKET_CLIENT_CONNECTING:
      {
        GSocketConnection *socketconn = G_SOCKET_CONNECTION (connection);
        gs_unref_object GSocketAddress *remote_address =
          g_socket_connection_get_remote_address (socketconn, NULL);

        g_debug ("socket connecting remote=%p", remote_address);
        if (remote_address && G_IS_INET_SOCKET_ADDRESS (remote_address))
          {
            GInetAddress *inetaddr =
              g_inet_socket_address_get_address ((GInetSocketAddress*)remote_address);
            gs_free char *inet_str = g_inet_address_to_string (inetaddr);
            set_status_printf (self, _("Connecting to '%s'…"),
                               inet_str);
          }
        break;
      }
    default:
      break;
    }
}
Ejemplo n.º 18
0
//Read tcp requests of connected clients
gboolean network_read(GIOChannel *source, GIOCondition cond, gpointer data) {

  GString *s = g_string_new(NULL);
  GError *error = NULL;
  GIOStatus ret = g_io_channel_read_line_string(source, s, NULL, &error);

  if (ret == G_IO_STATUS_ERROR) {
    //unref connection
    GSocketAddress *sockaddr = g_socket_connection_get_remote_address(data, NULL);
    GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
    //Read sender ip
    if (verbose) {
      printf("App Server: Communication error.. Removing client.. ->%s\n", g_inet_address_to_string(addr));
      fflush(stdout);
    }
    //Remove client
    remove_client(g_inet_address_to_string(addr));
    //Free objects
    g_string_free(s, TRUE);
    g_object_unref(sockaddr);
    g_object_unref(addr);
    g_object_unref(data);
    //Return false to stop listening this socket
    return FALSE;
  }
  else{
    //Read request command
    gchar  *RecString;
    RecString=s->str;
    //check client password
    if ((strncmp(RecString, AppPass, strlen(AppPass))) == 0) {
      //Password ok can send command
      GString *incs = g_string_new(s->str);
      incs = g_string_erase(s,0,(strlen(AppPass)+1));
      IvySendMsg("%s",incs->str);
      if (verbose) {
        printf("App Server: Command passed to ivy: %s\n",incs->str);
        fflush(stdout);
      }
    }
    //AC data request. (Ignore client password)
    else if ((strncmp(RecString, "getac ", strlen("getac "))) == 0) {
      //AC data request
      char AcData[BUFLEN];
      //Read ac data
      if (get_ac_data(RecString, AcData)) {
        //Send requested data to client
        GOutputStream * ostream = g_io_stream_get_output_stream (data);
        g_output_stream_write(ostream, AcData, strlen(AcData), NULL, &error);
      }
    }
    //Waypoint data request (Ignore client password)
    else if ((strncmp(RecString, "getwp ", strlen("getwp "))) == 0) {
      char AcData[BUFLEN];
      //Read wp data of ac
      if (get_wp_data(RecString, AcData)) {
        //Send requested data to client
        GOutputStream * ostream = g_io_stream_get_output_stream (data);
        g_output_stream_write(ostream, AcData, strlen(AcData), NULL, &error);
      }
    }
    //Waypoint data request (Ignore client password)
    else if ((strncmp(RecString, "getbl ", strlen("getbl "))) == 0) {
      char AcData[BUFLEN];
      //Read block data of AC
      if (get_bl_data(RecString, AcData)) {
        //Send requested data to client
        GOutputStream * ostream = g_io_stream_get_output_stream (data);
        g_output_stream_write(ostream, AcData, strlen(AcData), NULL, &error);
      }
    }

    //If client sends removeme command, remove it from broadcast list
    else if ((strncmp( RecString, "removeme", strlen("removeme"))) == 0) {
      GSocketAddress *sockaddr = g_socket_connection_get_remote_address(data, NULL);
      GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
      //Read sender ip
      if (verbose) {
        printf("App Server: need to remove %s\n", g_inet_address_to_string(addr));
        fflush(stdout);
      }
      //Remove client
      remove_client(g_inet_address_to_string(addr));
      //Free objects
      g_string_free(s, TRUE);
      g_object_unref(sockaddr);
      g_object_unref(addr);
      g_object_unref(data);
      //Return false to stop listening this socket
      return FALSE;
    }
    else {
      //Unknown command
      if (verbose) {
        printf("App Server: Client send an unknown command or wrong password: (%s)\n",RecString);
        fflush(stdout);
      }
    }
  }

  if (ret == G_IO_STATUS_EOF) {
    //Client disconnected
    if (verbose) {
      GSocketAddress *sockaddr = g_socket_connection_get_remote_address(data, NULL);
      GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
      printf("App Server: Client disconnected without saying 'bye':( ->%s\n", g_inet_address_to_string(addr));
      remove_client(g_inet_address_to_string(addr));
      fflush(stdout);
    }
    g_string_free(s, TRUE);
    //Unref the socket and return false to allow the client to reconnect
    g_object_unref(data);
    return FALSE;
  }
  //None above.. Keep listening the socket
  g_string_free(s, TRUE);
  return TRUE;
}
Ejemplo n.º 19
0
static gboolean
on_socket_input (GSocket *socket,
                 GIOCondition condition,
                 gpointer user_data)
{
  CockpitRequest *request = user_data;
  guchar first_byte;
  GInputVector vector[1] = { { &first_byte, 1 } };
  gint flags = G_SOCKET_MSG_PEEK;
  gboolean redirect_tls;
  gboolean is_tls;
  GSocketAddress *addr;
  GInetAddress *inet;
  GError *error = NULL;
  GIOStream *tls_stream;
  gssize num_read;

  num_read = g_socket_receive_message (socket,
                                       NULL, /* out GSocketAddress */
                                       vector,
                                       1,
                                       NULL, /* out GSocketControlMessage */
                                       NULL, /* out num_messages */
                                       &flags,
                                       NULL, /* GCancellable* */
                                       &error);
  if (num_read < 0)
    {
      /* Just wait and try again */
      if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
        {
          g_error_free (error);
          return TRUE;
        }

      if (!should_suppress_request_error (error))
        g_warning ("couldn't read from socket: %s", error->message);

      cockpit_request_finish (request);
      g_error_free (error);
      return FALSE;
    }

  is_tls = TRUE;
  redirect_tls = FALSE;

  /*
   * TLS streams are guaranteed to start with octet 22.. this way we can distinguish them
   * from regular HTTP requests
   */
  if (first_byte != 22 && first_byte != 0x80)
    {
      is_tls = FALSE;
      redirect_tls = TRUE;
      addr = g_socket_connection_get_remote_address (G_SOCKET_CONNECTION (request->io), NULL);
      if (G_IS_INET_SOCKET_ADDRESS (addr))
        {
          inet = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (addr));
          redirect_tls = !g_inet_address_get_is_loopback (inet);
        }
      g_clear_object (&addr);
    }

  if (is_tls)
    {
      tls_stream = g_tls_server_connection_new (request->io,
                                                request->web_server->certificate,
                                                &error);
      if (tls_stream == NULL)
        {
          g_warning ("couldn't create new TLS stream: %s", error->message);
          cockpit_request_finish (request);
          g_error_free (error);
          return FALSE;
        }

      g_object_unref (request->io);
      request->io = G_IO_STREAM (tls_stream);
    }
  else if (redirect_tls)
    {
      request->delayed_reply = 301;
    }

  start_request_input (request);

  /* No longer run *this* source */
  return FALSE;
}
Ejemplo n.º 20
0
static gboolean
handler (GThreadedSocketService *service,
         GSocketConnection      *connection,
         GSocketListener        *listener,
         gpointer                user_data)
{
  GLibJsonRpcServerPrivate *jsonrpc_server = (GLibJsonRpcServerPrivate*)user_data;
  GError *error = NULL;
  
  // Check if it is a local connection. - This doesn't work!
  GSocketAddress *sockaddr
    = g_socket_connection_get_remote_address(connection,
                                             &error);
  GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));

  if (!jsonrpc_server->allow_non_loopback_connections)
    {
#if 0
      // Why doesn't this work?
      if (!g_inet_address_get_is_loopback(addr))
        return TRUE; // just fail
#endif
      
      gchar *addr_string = g_inet_address_to_string(addr);
      gboolean is_local = g_strstr_len(addr_string, -1, "127.0.0.1") != NULL;
      g_free(addr_string);
      if (!is_local) 
        return TRUE; // silently fail
    }

  GOutputStream *out;
  GInputStream *in;
  char buffer[1024];
  gssize size;

  out = g_io_stream_get_output_stream (G_IO_STREAM (connection));
  in = g_io_stream_get_input_stream (G_IO_STREAM (connection));

  // Read the http header
  gboolean skip_header = TRUE;
  JsonParser *parser = json_parser_new();
  GString *json_string = g_string_new("");
  while (0 < (size = g_input_stream_read (in, buffer,
                                          sizeof buffer, NULL, NULL)))
    {
      int header_size = 0;
      
      if (skip_header)
        {
          gchar *head_end = g_strstr_len(buffer, size,
                                         "\r\n\r\n");
          if (head_end > 0)
            header_size = head_end - buffer;
          else
            continue;
        }
      
      g_string_append_len(json_string, buffer+header_size, size-header_size);
      if (json_parser_load_from_data(parser, json_string->str, -1, &error))
        break;
      else
        g_error_free(error);
    }

  // TBD:   raise error if there was a syntax error
  g_string_free(json_string, TRUE);

  // Get params object without the reader 
  JsonNode *root = json_parser_get_root(parser);
  JsonObject *root_object = json_node_get_object(root);
  JsonNode* params = json_object_get_member(root_object, "params");

  // Use reader for method and id
  JsonReader *reader = json_reader_new(json_parser_get_root(parser));
  json_reader_read_member (reader, "method");
  const gchar *method = json_reader_get_string_value (reader);
  json_reader_end_member (reader);
  
  json_reader_read_member (reader, "id");
  gint64 id = json_reader_get_int_value(reader);
  json_reader_end_member (reader);

  // Build the response which is either a response object or an error object
  JsonNode *response = NULL;
  
  /* Call the callback */
  command_hash_value_t *command_val = NULL;
  if (method)
    command_val = g_hash_table_lookup(jsonrpc_server->command_hash,
                                      method);
  if (!command_val)
    response = create_fault_msg_response(-2, "No such method!",id);
  else if (command_val->async_callback)
    {
      if (jsonrpc_server->async_busy)
        response = create_fault_msg_response(-2, "Busy!",id);
      else
        {
          // With the embedding of the mutex in the query we should
          // be able to handle more than one connection, so there
          // is no need to protect against a busy state.
          // jsonrpc_server->async_busy = TRUE;
          GLibJsonRpcAsyncQueryPrivate *query = glib_jsonrpc_server_query_new((GLibJsonRpcServer*)jsonrpc_server);
          
          // Create a secondary main loop
          (*command_val->async_callback)((GLibJsonRpcServer*)jsonrpc_server,
                                         (GLibJsonRpcAsyncQuery*)query,
                                         method,
                                         params,
                                         command_val->user_data);
          
          // Lock on a mutex
          g_mutex_lock(&query->mutex);
          g_cond_wait(&query->cond, &query->mutex);
          g_mutex_unlock(&query->mutex);

          if (query->error_num != 0)
            response = create_fault_value_response(query->error_num,query->reply,id);
          else
            response = create_response(query->reply, id);
          jsonrpc_server->async_busy = FALSE;

          // Erase the query
          glib_jsonrpc_async_query_free(query);
        }
    }
  else
    {
      JsonNode *reply;

      int ret = (*command_val->callback)((GLibJsonRpcServer*)jsonrpc_server,
                                         method,
                                         params,
                                         &reply,
                                         command_val->user_data);

      if (ret == 0)
        response = create_response(reply,id);
      else
        // For faults expect a string response containing the error
        response = create_fault_value_response(ret, reply,id);

      if (reply)
        json_node_free(reply);
    }

  if (response)
    {
      GString *response_string = g_string_new("");
  
      // Serialize response into content_string
      JsonGenerator *gen = json_generator_new ();
      gsize len;
      json_generator_set_root (gen, response);
      json_node_free(response);
      gchar *content_string = json_generator_to_data(gen, &len);
      g_object_unref (gen);

      g_string_append_printf(response_string,
                             "HTTP/1.1 200 OK\r\n"
                             "Connection: close\r\n"
                             "Content-Length: %d\r\n"
                             "Content-Type: text/xml\r\n"
                             "Date: Fri, 1 Jan 2000 00:00:00 GMT\r\n"
                             "Server: GlibJsonRPC server\r\n"
                             "\r\n"
                             "%s",
                             (int)len,
                             content_string
                             );
      g_free(content_string);
  
      g_output_stream_write (out,
                             response_string->str,
                             response_string->len,
                             NULL,NULL);
      g_string_free(response_string, TRUE);
    }

  g_object_unref(parser);

  return TRUE;
}
Ejemplo n.º 21
0
static void
identd_read_ready (GDataInputStream *in_stream, GAsyncResult *res, ident_info *info)
{
	GSocketAddress *sok_addr;
	GOutputStream *out_stream;
	guint64 local, remote;
	gchar *read_buf, buf[512], *p;

	if ((read_buf = g_data_input_stream_read_line_finish (in_stream, res, NULL, NULL)))
	{
		local = g_ascii_strtoull (read_buf, NULL, 0);
		p = strchr (read_buf, ',');
		if (!p)
		{
			g_free (read_buf);
			goto cleanup;
		}

		remote = g_ascii_strtoull (p + 1, NULL, 0);
		g_free (read_buf);

		g_snprintf (buf, sizeof (buf), "%"G_GUINT16_FORMAT", %"G_GUINT16_FORMAT" : ",
					(guint16)MIN(local, G_MAXUINT16), (guint16)MIN(remote, G_MAXUINT16));

		if (!local || !remote || local > G_MAXUINT16 || remote > G_MAXUINT16)
		{
			g_strlcat (buf, "ERROR : INVALID-PORT\r\n", sizeof (buf));
			g_debug ("Identd: Received invalid port");
		}
		else
		{
			info->username = g_hash_table_lookup (responses, GINT_TO_POINTER (local));
			if (!info->username)
			{
				g_strlcat (buf, "ERROR : NO-USER\r\n", sizeof (buf));
				g_debug ("Identd: Received invalid local port");
			}
			else
			{
				const gsize len = strlen (buf);

				g_hash_table_steal (responses, GINT_TO_POINTER (local));

				g_snprintf (buf + len, sizeof (buf) - len, "USERID : UNIX : %s\r\n", info->username);

				if ((sok_addr = g_socket_connection_get_remote_address (info->conn, NULL)))
				{
					GInetAddress *inet_addr;
					gchar *addr;

					inet_addr = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (sok_addr));
					addr = g_inet_address_to_string (inet_addr);

					hexchat_printf (ph, _("*\tServicing ident request from %s as %s"), addr, info->username);

					g_object_unref (sok_addr);
					g_object_unref (inet_addr);
					g_free (addr);
				}
			}
		}

		out_stream = g_io_stream_get_output_stream (G_IO_STREAM (info->conn));
		g_output_stream_write_async (out_stream, buf, strlen (buf), G_PRIORITY_DEFAULT,
									NULL, (GAsyncReadyCallback)identd_write_ready, info);
	}

	return;

cleanup:
	ident_info_free (info);
}
Ejemplo n.º 22
0
int
main (int argc, char *argv[])
{
  GOptionContext *context;
  GSocketClient *client;
  GSocketConnection *connection;
  GSocketAddress *address;
  GCancellable *cancellable;
  GOutputStream *out;
  GError *error = NULL;
  char buffer[1000];

  g_type_init ();

  context = g_option_context_new (" <hostname>[:port] - send data to tcp host");
  g_option_context_add_main_entries (context, cmd_entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (argc != 2)
    {
      g_printerr ("%s: %s\n", argv[0], "Need to specify hostname");
      return 1;
    }

  if (async)
    loop = g_main_loop_new (NULL, FALSE);

  if (cancel_timeout)
    {
      GThread *thread;
      cancellable = g_cancellable_new ();
      thread = g_thread_new ("cancel", cancel_thread, cancellable);
      g_thread_unref (thread);
    }
  else
    {
      cancellable = NULL;
    }

  client = g_socket_client_new ();
  if (io_timeout)
    g_socket_client_set_timeout (client, io_timeout);
  if (verbose)
    g_signal_connect (client, "event", G_CALLBACK (socket_client_event), NULL);

  if (async)
    {
      GAsyncResult *res;
      g_socket_client_connect_to_host_async (client, argv[1], 7777,
					     cancellable, async_cb, &res);
      g_main_loop_run (loop);
      connection = g_socket_client_connect_to_host_finish (client, res, &error);
      g_object_unref (res);
    }
  else
    {
      connection = g_socket_client_connect_to_host (client,
						    argv[1],
						    7777,
						    cancellable, &error);
    }
  if (connection == NULL)
    {
      g_printerr ("%s can't connect: %s\n", argv[0], error->message);
      return 1;
    }
  g_object_unref (client);

  address = g_socket_connection_get_remote_address (connection, &error);
  if (!address)
    {
      g_printerr ("Error getting remote address: %s\n",
		  error->message);
      return 1;
    }
  g_print ("Connected to address: %s\n",
	   socket_address_to_string (address));
  g_object_unref (address);

  if (graceful)
    g_tcp_connection_set_graceful_disconnect (G_TCP_CONNECTION (connection), TRUE);

  out = g_io_stream_get_output_stream (G_IO_STREAM (connection));

  while (fgets(buffer, sizeof (buffer), stdin) != NULL)
    {
      /* FIXME if (async) */
      if (!g_output_stream_write_all (out, buffer, strlen (buffer),
				      NULL, cancellable, &error))
	{
	  g_warning ("send error: %s\n",  error->message);
	  g_error_free (error);
	  error = NULL;
	}
    }

  g_print ("closing stream\n");
  if (async)
    {
      GAsyncResult *res;
      g_io_stream_close_async (G_IO_STREAM (connection),
			       0, cancellable, async_cb, &res);
      g_main_loop_run (loop);
      if (!g_io_stream_close_finish (G_IO_STREAM (connection),
				     res, &error))
	{
	  g_object_unref (res);
	  g_warning ("close error: %s\n",  error->message);
	  return 1;
	}
      g_object_unref (res);
    }
  else
    {
      if (!g_io_stream_close (G_IO_STREAM (connection), cancellable, &error))
	{
	  g_warning ("close error: %s\n",  error->message);
	  return 1;
	}
    }

  g_object_unref (connection);

  return 0;
}
Ejemplo n.º 23
0
static void
synce_device_set_property (GObject      *obj,
                           guint         property_id,
                           const GValue *value,
                           GParamSpec   *pspec)
{
  SynceDevice *self = SYNCE_DEVICE (obj);
  SynceDevicePrivate *priv = SYNCE_DEVICE_GET_PRIVATE (self);

  switch (property_id) {
  case PROP_CONNECTION:
    if (priv->conn != NULL)
      {
	g_object_unref (priv->conn);
      }

    priv->conn = g_value_get_pointer (value);
    g_object_ref (priv->conn);

    GInputStream *in_stream = g_io_stream_get_input_stream(G_IO_STREAM(priv->conn));
    priv->iobuf = g_malloc(sizeof (guint32));
    g_input_stream_read_async(in_stream, priv->iobuf, sizeof (guint32), G_PRIORITY_DEFAULT, NULL, synce_device_conn_event_cb, g_object_ref(self));

    GInetSocketAddress *address = NULL;
    GInetAddress *inet_address = NULL;
    address = G_INET_SOCKET_ADDRESS(g_socket_connection_get_remote_address(priv->conn, NULL));
    inet_address = g_inet_socket_address_get_address(address);
    priv->ip_address =  g_inet_address_to_string(inet_address);
    g_object_unref(address);

    address = G_INET_SOCKET_ADDRESS(g_socket_connection_get_local_address(priv->conn, NULL));
    inet_address = g_inet_socket_address_get_address(address);
    priv->iface_address = g_inet_address_to_string(inet_address);
    g_object_unref(address);

    break;
  case PROP_DEVICE_PATH:
    g_free (priv->device_path);
    priv->device_path = g_value_dup_string (value);
    g_debug("%s: running for device %s", G_STRFUNC, priv->device_path);

    break;
  case PROP_OBJ_PATH:
    g_free (priv->obj_path);
    priv->obj_path = g_value_dup_string (value);
    break;
  case PROP_GUID:
    g_free (priv->guid);
    priv->guid = g_value_dup_string (value);
    break;
  case PROP_OS_MAJOR:
    priv->os_major = g_value_get_uint (value);
    break;
  case PROP_OS_MINOR:
    priv->os_minor = g_value_get_uint (value);
    break;
  case PROP_NAME:
    g_free (priv->name);
    priv->name = g_value_dup_string (value);
    break;
  case PROP_VERSION:
    priv->version = g_value_get_uint (value);
    break;
  case PROP_CPU_TYPE:
    priv->cpu_type = g_value_get_uint (value);
    break;
  case PROP_CURRENT_PARTNER_ID:
    priv->cur_partner_id = g_value_get_uint (value);
    break;
  case PROP_ID:
    priv->id = g_value_get_uint (value);
    break;
  case PROP_PLATFORM_NAME:
    g_free (priv->platform_name);
    priv->platform_name = g_value_dup_string (value);
    break;
  case PROP_MODEL_NAME:
    g_free (priv->model_name);
    priv->model_name = g_value_dup_string (value);
    break;
  case PROP_PASSWORD_FLAGS:
    priv->pw_flags = g_value_get_uint (value);
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, property_id, pspec);
    break;
  }
}
Ejemplo n.º 24
0
void lllp_next_song_cb(GObject *listener, GAsyncResult *res, gpointer pstore_library) {
	GtkListStore *store_library = GTK_LIST_STORE(pstore_library);
	gboolean valid = FALSE;
	GSocketConnection *connection;
	GSocketClient *player_client;
	GSocketAddress *address;
	GSocket *socket;
	GInputStream *stream;
	GOutputStream *output_stream;
	GInetAddress *inet_address;
	GInetAddress *player_with_the_song;
	GtkTreeIter iter;
	gchar *player_with_the_song_char;
	struct force_vector_s force_vector;
	gchar *remote_file;
	gint random_number;
	gsize count = 0;
	int i;
	struct force_vector_s rand_force_vector;

	connection = g_socket_listener_accept_finish(G_SOCKET_LISTENER(listener), res, NULL, NULL);
	address = g_socket_connection_get_remote_address(connection, NULL);
	inet_address = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(address));

	socket = g_socket_connection_get_socket(connection);
	stream = g_io_stream_get_input_stream(G_IO_STREAM(connection));

	g_input_stream_read_all(stream, &force_vector, sizeof(force_vector), NULL, NULL, NULL);
	
	valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store_library), &iter);
	while(valid == TRUE) {
		valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store_library), &iter);
		count++;
	}

	gint rand;
	float distance = 100, old_distance = 100;
	float treshold = 0.95;
	float treshold_distance = 4.0;

	do {
		/* TO FUNCTIONALIZE */
		rand = g_random_int_range(0, count);

		if(gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store_library), &iter)) {
			for(i = 0; i < rand - 1; ++i) {
				gtk_tree_model_iter_next(GTK_TREE_MODEL(store_library), &iter);
			}
			gtk_tree_model_get(GTK_TREE_MODEL(store_library), &iter, FORCE_AMP, &rand_force_vector.amplitude,
				FORCE_ATK, &rand_force_vector.attack, FORCE_FREQ, &rand_force_vector.frequency,
				FORCE_TEMPO, &rand_force_vector.tempo, -1);
		}
		treshold -= 0.01;
		treshold_distance += 0.01;
	}  while((bl_cosine_similarity(rand_force_vector, force_vector) < treshold) ||
		((distance = bl_distance(rand_force_vector, force_vector)) > treshold_distance));
	
	gtk_tree_model_get(GTK_TREE_MODEL(store_library), &iter, AFILE, &remote_file, INET_ADDRESS, &player_with_the_song_char, -1);
	player_with_the_song = g_inet_address_new_from_string(player_with_the_song_char);

	if(g_inet_address_equal(player_with_the_song, inet_address) == TRUE) {
		rand_force_vector.attack = rand_force_vector.frequency = rand_force_vector.tempo = rand_force_vector.amplitude = 0;
		player_client = g_socket_client_new();
		connection = g_socket_client_connect_to_host(player_client, g_inet_address_to_string(inet_address), 5353, NULL, NULL);
		output_stream = g_io_stream_get_output_stream(G_IO_STREAM(connection));
		g_output_stream_write_all(output_stream, &rand_force_vector, sizeof(rand_force_vector), &count, NULL, NULL);
		g_io_stream_close(G_IO_STREAM(connection), NULL, NULL);

		g_socket_listener_accept_async(G_SOCKET_LISTENER(listener), NULL, lllp_next_song_cb, store_library);
	
		return;
	}
	player_client = g_socket_client_new();
	connection = g_socket_client_connect_to_host(player_client, g_inet_address_to_string(inet_address), 5353, NULL, NULL);
	output_stream = g_io_stream_get_output_stream(G_IO_STREAM(connection));
	g_output_stream_write_all(output_stream, &rand_force_vector, sizeof(rand_force_vector), &count, NULL, NULL);
	g_io_stream_close(G_IO_STREAM(connection), NULL, NULL);

	player_with_the_song_char = g_inet_address_to_string(player_with_the_song);
	connection = g_socket_client_connect_to_host(player_client, player_with_the_song_char, 19144, NULL, NULL);
	printf("%p\n", connection);
	output_stream = g_io_stream_get_output_stream(G_IO_STREAM(connection));
	count = strlen(g_inet_address_to_string(inet_address)) + 1;
	g_output_stream_write_all(output_stream, &count, sizeof(gsize), NULL, NULL, NULL);
	g_output_stream_write_all(output_stream, g_inet_address_to_string(inet_address), count, NULL, NULL, NULL);
	count = strlen(remote_file) + 1;
	g_output_stream_write_all(output_stream, &count, sizeof(gsize), NULL, NULL, NULL);
	g_output_stream_write_all(output_stream, remote_file, count, NULL, NULL, NULL);
	g_output_stream_close(output_stream, NULL, NULL);

	g_socket_listener_accept_async(G_SOCKET_LISTENER(listener), NULL, lllp_next_song_cb, store_library);
}