示例#1
0
static void
tunnel_close (Tunnel *tunnel)
{
	if (tunnel->cancellable) {
		g_cancellable_cancel (tunnel->cancellable);
		g_object_unref (tunnel->cancellable);
	}

	if (tunnel->client.iostream) {
		g_io_stream_close (tunnel->client.iostream, NULL, NULL);
		g_object_unref (tunnel->client.iostream);
	}
	if (tunnel->server.iostream) {
		g_io_stream_close (tunnel->server.iostream, NULL, NULL);
		g_object_unref (tunnel->server.iostream);
	}

	g_free (tunnel->client.buffer);
	g_free (tunnel->server.buffer);

	g_object_unref (tunnel->self);
	g_object_unref (tunnel->msg);

	g_free (tunnel);
}
示例#2
0
gboolean
g_vfs_afp_connection_close (GVfsAfpConnection *afp_connection,
                            GCancellable      *cancellable,
                            GError            **error)
{
  GVfsAfpConnectionPrivate *priv = afp_connection->priv;
  
  guint16 req_id;
  gboolean res;
  
  /* close DSI session */
  req_id = get_request_id (afp_connection);
  res = send_request_sync (g_io_stream_get_output_stream (priv->conn),
                           DSI_CLOSE_SESSION, req_id, 0, 0, NULL,
                           cancellable, error);
  if (!res)
  {
    g_io_stream_close (priv->conn, cancellable, NULL);
    g_object_unref (priv->conn);
    return FALSE;
  }

  res = g_io_stream_close (priv->conn, cancellable, error);
  g_object_unref (priv->conn);
  
  return res;
}
void
codeslayer_utils_save_gobjects (GList       *objects,
                                const gchar *file_path, 
                                gpointer     name, ...)
{
  gchar *contents;
  GHashTable *table;
  va_list var_arg;
  GFile *file;

  file = g_file_new_for_path (file_path);
  if (!g_file_query_exists (file, NULL))
    {
      GFileIOStream *stream;           
      stream = g_file_create_readwrite (file, G_FILE_CREATE_NONE, NULL, NULL);
      if (g_io_stream_close (G_IO_STREAM (stream), NULL, NULL))
        g_object_unref (stream);
    }

  va_start (var_arg, name);
  table = codeslayer_xml_create_hashtable (var_arg);
  va_end (var_arg);
  
  contents = codeslayer_xml_serialize_gobjects (objects, name, table);

  g_file_set_contents (file_path, contents, -1, NULL);

  g_object_unref (file);
  g_free (contents);
  codeslayer_xml_free_hashtable (table);
}
示例#4
0
static int gio_fclose (VFSFile * file)
{
    FileData * data = vfs_get_handle (file);
    GError * error = 0;

    if (data->iostream)
    {
        g_io_stream_close (data->iostream, 0, & error);
        g_object_unref (data->iostream);
        CHECK_ERROR ("close", vfs_get_filename (file));
    }
    else if (data->istream)
    {
        g_input_stream_close (data->istream, 0, & error);
        g_object_unref (data->istream);
        CHECK_ERROR ("close", vfs_get_filename (file));
    }
    else if (data->ostream)
    {
        g_output_stream_close (data->ostream, 0, & error);
        g_object_unref (data->ostream);
        CHECK_ERROR ("close", vfs_get_filename (file));
    }

    if (data->file)
        g_object_unref (data->file);

    return 0;

FAILED:
    if (data->file)
        g_object_unref (data->file);

    return -1;
}
示例#5
0
static void
synce_device_dispose (GObject *obj)
{
  SynceDevice *self = SYNCE_DEVICE (obj);
  SynceDevicePrivate *priv = SYNCE_DEVICE_GET_PRIVATE (self);

  if (priv->dispose_has_run)
    return;

  priv->dispose_has_run = TRUE;

#if USE_GDBUS
  if (priv->interface) {
    g_dbus_interface_skeleton_unexport(G_DBUS_INTERFACE_SKELETON(priv->interface));
    g_object_unref(priv->interface);
  }
#endif

  g_io_stream_close(G_IO_STREAM(priv->conn), NULL, NULL);
  g_object_unref(priv->conn);

#if HAVE_GUDEV
  g_object_unref(priv->gudev_client);
#endif

  g_hash_table_destroy (priv->requests);

  if (G_OBJECT_CLASS (synce_device_parent_class)->dispose)
    G_OBJECT_CLASS (synce_device_parent_class)->dispose (obj);
}
示例#6
0
void closeFile(PlatformFileHandle& handle)
{
    if (!isHandleValid(handle))
        return;

    g_io_stream_close(G_IO_STREAM(handle), 0, 0);
    g_object_unref(handle);
    handle = invalidPlatformFileHandle;
}
示例#7
0
static void
close_immediately (CockpitStream *self,
                   const gchar *problem)
{
  GError *error = NULL;
  GIOStream *io;

  if (self->priv->closed)
    return;

  if (problem)
    {
      g_free (self->priv->problem);
      self->priv->problem = g_strdup (problem);
    }

  if (self->priv->connecting)
    {
      cockpit_connectable_unref (self->priv->connecting);
      self->priv->connecting = NULL;
    }

  self->priv->closed = TRUE;

  g_debug ("%s: closing stream%s%s", self->priv->name,
           self->priv->problem ? ": " : "",
           self->priv->problem ? self->priv->problem : "");

  if (self->priv->in_source)
    stop_input (self);
  if (self->priv->out_source)
    stop_output (self);

  if (self->priv->io)
    {
      io = self->priv->io;
      self->priv->io = NULL;

      if (self->priv->sig_accept_cert)
        {
          g_signal_handler_disconnect (io, self->priv->sig_accept_cert);
          self->priv->sig_accept_cert = 0;
        }

      g_io_stream_close (io, NULL, &error);
      if (error)
        {
          g_message ("%s: close failed: %s", self->priv->name, error->message);
          g_clear_error (&error);
        }
      g_object_unref (io);
    }

  g_debug ("%s: closed", self->priv->name);
  g_signal_emit (self, cockpit_stream_sig_close, 0, self->priv->problem);
}
示例#8
0
static VALUE
rg_close(VALUE self, VALUE cancellable)
{
        GError *error = NULL;

        if (!g_io_stream_close(_SELF(self), RVAL2GCANCELLABLE(cancellable), &error))
                rbgio_raise_error(error);

        return self;
}
示例#9
0
void
gspeechd_client_fail (GSpeechdClient *client)
{
   g_assert(client);

   client->failed = TRUE;
   g_io_stream_close(G_IO_STREAM(client->connection),
                     client->cancellable,
                     NULL);
}
示例#10
0
static void
g_io_stream_dispose (GObject *object)
{
  GIOStream *stream;

  stream = G_IO_STREAM (object);

  if (!stream->priv->closed)
    g_io_stream_close (stream, NULL, NULL);

  G_OBJECT_CLASS (g_io_stream_parent_class)->dispose (object);
}
示例#11
0
char *
ot_editor_prompt (OstreeRepo *repo,
                  const char *input,
                  GCancellable *cancellable,
                  GError **error)
{
  glnx_unref_object GSubprocess *proc = NULL;
  g_autoptr(GFile) file = NULL;
  g_autoptr(GFileIOStream) io = NULL;
  GOutputStream *output;
  const char *editor;
  char *ret = NULL;
  g_autofree char *args = NULL;

  editor = get_editor ();
  if (editor == NULL)
    {
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Terminal is dumb, but EDITOR unset");
      goto out;
    }

  file = g_file_new_tmp (NULL, &io, error);
  if (file == NULL)
    goto out;

  output = g_io_stream_get_output_stream (G_IO_STREAM (io));
  if (!g_output_stream_write_all (output, input, strlen (input), NULL, cancellable, error) ||
      !g_io_stream_close (G_IO_STREAM (io), cancellable, error))
    goto out;

  {
    g_autofree char *quoted_file = g_shell_quote (gs_file_get_path_cached (file));
    args = g_strconcat (editor, " ", quoted_file, NULL);
  }

  proc = g_subprocess_new (G_SUBPROCESS_FLAGS_STDIN_INHERIT, error, 
                           "/bin/sh", "-c", args, NULL);

  if (!g_subprocess_wait_check (proc, cancellable, error))
    {
      g_prefix_error (error, "There was a problem with the editor '%s'", editor);
      goto out;
    }

  ret = glnx_file_get_contents_utf8_at (AT_FDCWD, gs_file_get_path_cached (file), NULL,
                                        cancellable, error);

out:
  if (file)
    (void )g_file_delete (file, NULL, NULL);
  return ret;
}
示例#12
0
文件: account.c 项目: magcius/cockpit
static gboolean
handle_set_icon_data_url (CockpitAccount *object,
                          GDBusMethodInvocation *invocation,
                          const gchar *arg_data)
{
  GError *error = NULL;
  Account *acc = ACCOUNT (object);

  if (!account_auth_check (object, invocation, acc))
    return TRUE;

  if (acc->u)
    {
      const gchar *base64_data = strstr (arg_data, "base64,");
      if (base64_data == NULL)
        goto out;

      base64_data += strlen ("base64,");

      gsize raw_size;
      gs_free gchar *raw_data = (gchar *)g_base64_decode (base64_data, &raw_size);

      gs_unref_object GFileIOStream *tmp_stream = NULL;
      gs_unref_object GFile *tmp_file = g_file_new_tmp ("cockpit-user-icon-XXXXXX", &tmp_stream, &error);

      if (tmp_file == NULL)
        goto out;

      GOutputStream *out = g_io_stream_get_output_stream (G_IO_STREAM (tmp_stream));
      if (!g_output_stream_write_all (out, raw_data, raw_size, NULL, NULL, &error))
        goto out;

      if (!g_io_stream_close (G_IO_STREAM (tmp_stream), NULL, &error))
        goto out;

      gs_free gchar *tmp_path = g_file_get_path (tmp_file);
      act_user_set_icon_file (acc->u, tmp_path);
      g_file_delete (tmp_file, NULL, NULL);
    }

out:
  if (error)
    {
      g_dbus_method_invocation_return_error (invocation,
                                             COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
                                             "%s", error->message);
      g_clear_error (&error);
    }
  else
    cockpit_account_complete_set_icon_data_url (object, invocation);
  return TRUE;
}
示例#13
0
static gboolean
kixmail_io_stream_close (GIOStream *stream,
                         GCancellable *cancellable,
                         GError **error)
{
  KixmailIOStream *iostream = KIXMAIL_IO_STREAM (stream);

  if (iostream->priv->disposing &&
      !iostream->priv->close_on_dispose)
    return TRUE;

  return g_io_stream_close (iostream->priv->base_iostream, cancellable, error);
}
示例#14
0
static void
gegl_tile_backend_file_finalize (GObject *object)
{
  GeglTileBackendFile *self = (GeglTileBackendFile *) object;

  if (self->index)
    g_hash_table_unref (self->index);

  if (self->exist)
    {
      GEGL_NOTE (GEGL_DEBUG_TILE_BACKEND, "finalizing buffer %s", self->path);

#if HAVE_GIO
      if (self->io)
        {
          g_io_stream_close (self->io, NULL, NULL);
          g_object_unref (self->io);
          self->io = NULL;
        }

      if (self->file)
        g_file_delete  (self->file, NULL, NULL);
#else
      if (self->i != -1)
        {
          close (self->i);
          self->i = -1;
        }
      if (self->o != -1)
        {
          close (self->o);
          self->o = -1;
        }
#endif
    }

  if (self->path)
    g_free (self->path);

#if HAVE_GIO
  if (self->monitor)
    g_object_unref (self->monitor);

  if (self->file)
    g_object_unref (self->file);
#endif

  (*G_OBJECT_CLASS (parent_class)->finalize)(object);
}
static void connectedCallback(GSocketClient* client, GAsyncResult* result, void* id)
{
    // Always finish the connection, even if this SocketStreamHandle was deactivated earlier.
    GOwnPtr<GError> error;
    GSocketConnection* socketConnection = g_socket_client_connect_to_host_finish(client, result, &error.outPtr());

    // The SocketStreamHandle has been deactivated, so just close the connection, ignoring errors.
    SocketStreamHandle* handle = getHandleFromId(id);
    if (!handle) {
        g_io_stream_close(G_IO_STREAM(socketConnection), 0, &error.outPtr());
        return;
    }

    handle->connected(socketConnection, error.get());
}
示例#16
0
static void
jetdirect_connection_test_cb (GObject      *source_object,
                              GAsyncResult *res,
                              gpointer      user_data)
{
  GSocketConnection *connection;
  PpHostPrivate     *priv;
  PpPrintDevice     *device;
  JetDirectData     *data;
  gpointer           result;
  GError            *error = NULL;
  GTask             *task = G_TASK (user_data);

  data = g_task_get_task_data (task);

  connection = g_socket_client_connect_to_host_finish (G_SOCKET_CLIENT (source_object),
                                                       res,
                                                       &error);

  if (connection != NULL)
    {
      g_io_stream_close (G_IO_STREAM (connection), NULL, NULL);
      g_object_unref (connection);

      priv = data->host->priv;

      device = g_new0 (PpPrintDevice, 1);
      device->device_class = g_strdup ("network");
      device->device_uri = g_strdup_printf ("socket://%s:%d",
                                            priv->hostname,
                                            data->port);
      /* Translators: The found device is a JetDirect printer */
      device->device_name = g_strdup (_("JetDirect Printer"));
      device->host_name = g_strdup (priv->hostname);
      device->host_port = data->port;
      device->acquisition_method = ACQUISITION_METHOD_JETDIRECT;

      data->devices->devices = g_list_append (data->devices->devices, device);
    }

  result = data->devices;
  data->devices = NULL;
  g_task_return_pointer (task, result, (GDestroyNotify) pp_devices_list_free);
  g_object_unref (task);
}
示例#17
0
static void
disconnect_internal (SoupSocket *sock, gboolean close)
{
	SoupSocketPrivate *priv = SOUP_SOCKET_GET_PRIVATE (sock);

	g_clear_object (&priv->gsock);
	if (priv->conn && close)
		g_io_stream_close (priv->conn, NULL, NULL);

	if (priv->read_src) {
		g_source_destroy (priv->read_src);
		priv->read_src = NULL;
	}
	if (priv->write_src) {
		g_source_destroy (priv->write_src);
		priv->write_src = NULL;
	}
}
static void
zpj_download_stream_ready (GObject *source,
                       GAsyncResult *res,
                       gpointer user_data)
{
  GError *error = NULL;
  PdfLoadJob *job = (PdfLoadJob *) user_data;
  const gchar *name;
  const gchar *extension;

  job->stream = zpj_skydrive_download_file_to_stream_finish (ZPJ_SKYDRIVE (source), res, &error);
  if (error != NULL) {
    pdf_load_job_complete_error (job, error);
    return;
  }

  name = zpj_skydrive_entry_get_name (job->zpj_entry);
  extension = gd_filename_get_extension_offset (name);

  /* If it is not a PDF, we need to convert it afterwards.
   * http://msdn.microsoft.com/en-us/library/live/hh826545#fileformats
   */
  if (g_strcmp0 (extension, ".pdf") != 0)
    {
      GFileIOStream *iostream;

      job->download_file = g_file_new_tmp (NULL, &iostream, &error);
      if (error != NULL) {
        pdf_load_job_complete_error (job, error);
        return;
      }

      /* We don't need the iostream. */
      g_io_stream_close (G_IO_STREAM (iostream), NULL, NULL);
    }
  else
    job->download_file = g_file_new_for_path (job->pdf_path);

  g_file_replace_async (job->download_file, NULL, FALSE,
                        G_FILE_CREATE_PRIVATE,
                        G_PRIORITY_DEFAULT,
                        job->cancellable, file_replace_ready_cb,
                        job);
}
void SocketStreamHandle::platformClose()
{
    // We remove this handle from the active handles list first, to disable all callbacks.
    deactivateHandle(this);
    stopWaitingForSocketWritability();

    if (m_socketConnection) {
        GOwnPtr<GError> error;
        g_io_stream_close(G_IO_STREAM(m_socketConnection.get()), 0, &error.outPtr());
        if (error)
            m_client->didFail(this, SocketStreamError(error->code)); // FIXME: Provide a sensible error.
        m_socketConnection = 0;
    }

    m_outputStream = 0;
    m_inputStream = 0;
    delete m_readBuffer;

    m_client->didClose(this);
}
示例#20
0
void SocketStreamHandle::connectedCallback(GSocketClient* client, GAsyncResult* result, SocketStreamHandle* handle)
{
    RefPtr<SocketStreamHandle> protectedThis = adoptRef(handle);

    // Always finish the connection, even if this SocketStreamHandle was cancelled earlier.
    GUniqueOutPtr<GError> error;
    GRefPtr<GSocketConnection> socketConnection = adoptGRef(g_socket_client_connect_to_host_finish(client, result, &error.outPtr()));

    // The SocketStreamHandle has been cancelled, so just close the connection, ignoring errors.
    if (g_cancellable_is_cancelled(handle->m_cancellable.get())) {
        if (socketConnection)
            g_io_stream_close(G_IO_STREAM(socketConnection.get()), nullptr, nullptr);
        return;
    }

    if (error)
        handle->didFail(SocketStreamError(error->code, error->message));
    else
        handle->connected(WTFMove(socketConnection));
}
示例#21
0
gchar*
codeslayer_utils_get_file_path (const gchar *folder_path, 
                                const gchar *file_name)
{
  gchar *file_path;
  GFile *file;

  file_path = g_build_filename (folder_path, file_name, NULL);  
  file = g_file_new_for_path (file_path);
  if (!g_file_query_exists (file, NULL))
    {
      GFileIOStream *stream;
      stream = g_file_create_readwrite (file, G_FILE_CREATE_NONE, NULL, NULL);
      g_io_stream_close (G_IO_STREAM (stream), NULL, NULL);
      g_object_unref (stream);
    }

  g_object_unref (file);

  return file_path;
}
示例#22
0
void SocketStreamHandle::platformClose()
{
    LOG(Network, "SocketStreamHandle %p platformClose", this);
    // We cancel this handle first to disable all callbacks.
    g_cancellable_cancel(m_cancellable.get());
    stopWaitingForSocketWritability();

    if (m_socketConnection) {
        GUniqueOutPtr<GError> error;
        g_io_stream_close(G_IO_STREAM(m_socketConnection.get()), nullptr, &error.outPtr());
        if (error)
            didFail(SocketStreamError(error->code, error->message));
        m_socketConnection = nullptr;
    }

    m_outputStream = nullptr;
    m_inputStream = nullptr;
    m_readBuffer = nullptr;

    m_client.didCloseSocketStream(*this);
}
void SocketStreamHandle::platformClose()
{
    LOG(Network, "SocketStreamHandle %p platformClose", this);
    // We remove this handle from the active handles list first, to disable all callbacks.
    deactivateHandle(this);
    stopWaitingForSocketWritability();

    if (m_socketConnection) {
        GUniqueOutPtr<GError> error;
        g_io_stream_close(G_IO_STREAM(m_socketConnection.get()), 0, &error.outPtr());
        if (error)
            m_client->didFailSocketStream(this, SocketStreamError(error->code, error->message));
        m_socketConnection = 0;
    }

    m_outputStream = 0;
    m_inputStream = 0;
    m_readBuffer = nullptr;

    m_client->didCloseSocketStream(this);
}
static void
handshake_cb (GObject *source,
    GAsyncResult *result,
    gpointer user_data)
{
  TestConnectorServer *self = TEST_CONNECTOR_SERVER (user_data);
  TestConnectorServerPrivate *priv = self->priv;
  WockyTLSConnection *tls_conn;
  GError *error = NULL;

  DEBUG ("TLS/SSL handshake finished");

  tls_conn = wocky_tls_session_handshake_finish (
    WOCKY_TLS_SESSION (source),
    result,
    &error);

  if (server_dec_outstanding (self))
    goto out;

  if (tls_conn == NULL)
    {
      DEBUG ("SSL or TLS Server Setup failed: %s", error->message);
      g_io_stream_close (priv->stream, NULL, NULL);
      goto out;
    }

  if (priv->conn != NULL)
    g_object_unref (priv->conn);

  priv->state = SERVER_STATE_START;
  priv->conn = wocky_xmpp_connection_new (G_IO_STREAM (tls_conn));
  g_object_unref (tls_conn);
  priv->tls_started = TRUE;
  xmpp_init (NULL,NULL,self);

out:
  if (error != NULL)
    g_error_free (error);
}
示例#25
0
/**
 * g_vfs_ftp_connection_enable_tls:
 * @conn: a connection without an active data connection
 * @server_identity: address of the server used to verify the certificate
 * @cb: callback called if there's a verification error
 * @user_data: user data passed to @cb
 * @cancellable: cancellable to interrupt wait
 * @error: %NULL or location to take a potential error
 *
 * Tries to enable TLS on the given @connection. If setting up TLS fails,
 * %FALSE will be returned and @error will be set. When this function fails,
 * you need to check if the connection is still usable. It might have been
 * closed.
 *
 * Returns: %TRUE on success, %FALSE otherwise.
 **/
gboolean
g_vfs_ftp_connection_enable_tls (GVfsFtpConnection * conn,
                                 GSocketConnectable *server_identity,
                                 CertificateCallback cb,
                                 gpointer            user_data,
                                 GCancellable *      cancellable,
                                 GError **           error)
{
  GIOStream *secure;

  g_return_val_if_fail (conn != NULL, FALSE);
  g_return_val_if_fail (conn->data == NULL, FALSE);
  g_return_val_if_fail (!conn->waiting_for_reply, FALSE);
  g_return_val_if_fail (g_buffered_input_stream_get_available (G_BUFFERED_INPUT_STREAM (conn->commands_in)) == 0, FALSE);

  secure = g_tls_client_connection_new (conn->commands,
                                        server_identity,
                                        error);
  if (secure == NULL)
    return FALSE;

  g_object_unref (conn->commands);
  conn->commands = secure;
  create_input_stream (conn);

  g_signal_connect (secure, "accept-certificate", G_CALLBACK (cb), user_data);

  if (!g_tls_connection_handshake (G_TLS_CONNECTION (secure),
                                   cancellable,
                                   error))
    {
      /* Close here to be sure it won't get used anymore */
      g_io_stream_close (secure, cancellable, NULL);
      return FALSE;
    }

  return TRUE;
}
示例#26
0
/**
 * g_vfs_ftp_connection_data_connection_enable_tls:
 * @conn: a connection with an active control connection
 * @server_identity: address of the server used to verify the certificate
 * @cb: callback called if there's a verification error
 * @user_data: user data passed to @cb
 * @cancellable: cancellable to interrupt wait
 * @error: %NULL or location to take a potential error
 *
 * Tries to enable TLS on the given @connection's data connection. If setting
 * up TLS fails, %FALSE will be returned and @error will be set.
 *
 * Returns: %TRUE on success, %FALSE otherwise.
 **/
gboolean
g_vfs_ftp_connection_data_connection_enable_tls (GVfsFtpConnection  *conn,
                                                 GSocketConnectable *server_identity,
                                                 CertificateCallback cb,
                                                 gpointer            user_data,
                                                 GCancellable *      cancellable,
                                                 GError **           error)
{
  GIOStream *secure;

  g_return_val_if_fail (conn != NULL, FALSE);
  g_return_val_if_fail (conn->commands != NULL, FALSE);

  secure = g_tls_client_connection_new (conn->data,
                                        server_identity,
                                        error);
  if (secure == NULL)
    return FALSE;

  g_object_unref (conn->data);
  conn->data = secure;

  g_tls_client_connection_copy_session_state (G_TLS_CLIENT_CONNECTION (secure),
                                              G_TLS_CLIENT_CONNECTION (conn->commands));

  g_signal_connect (secure, "accept-certificate", G_CALLBACK (cb), user_data);

  if (!g_tls_connection_handshake (G_TLS_CONNECTION (secure),
                                   cancellable,
                                   error))
    {
      /* Close here to be sure it won't get used anymore */
      g_io_stream_close (secure, cancellable, NULL);
      return FALSE;
    }

  return TRUE;
}
示例#27
0
int
main (int argc,
      char *argv[])
{
  GSocket *socket, *new_socket, *recv_socket;
  GSocketAddress *src_address;
  GSocketAddress *address;
  GSocketType socket_type;
  GSocketFamily socket_family;
  GError *error = NULL;
  GOptionContext *context;
  GCancellable *cancellable;
  char *display_addr;
  GTlsCertificate *tlscert = NULL;
  GIOStream *connection;
  GInputStream *istream;
  GOutputStream *ostream;

  g_type_init ();

  context = g_option_context_new (" - Test GSocket server stuff");
  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 (unix_socket && argc != 2)
    {
      g_printerr ("%s: %s\n", argv[0], "Need to specify unix socket name");
      return 1;
    }

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

  if (tls_cert_file)
    {
      if (use_udp)
	{
	  g_printerr ("DTLS (TLS over UDP) is not supported");
	  return 1;
	}

      tlscert = g_tls_certificate_new_from_file (tls_cert_file, &error);
      if (!tlscert)
	{
	  g_printerr ("Could not read server certificate '%s': %s\n",
		      tls_cert_file, error->message);
	  return 1;
	}
    }

  loop = g_main_loop_new (NULL, FALSE);

  if (use_udp)
    socket_type = G_SOCKET_TYPE_DATAGRAM;
  else
    socket_type = G_SOCKET_TYPE_STREAM;

  if (unix_socket)
    socket_family = G_SOCKET_FAMILY_UNIX;
  else
    socket_family = G_SOCKET_FAMILY_IPV4;

  socket = g_socket_new (socket_family, socket_type, 0, &error);

  if (socket == NULL)
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (non_blocking)
    g_socket_set_blocking (socket, FALSE);

  if (unix_socket)
    {
      src_address = socket_address_from_string (argv[1]);
      if (src_address == NULL)
	{
	  g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
	  return 1;
	}
    }
  else
    {
      src_address = g_inet_socket_address_new (g_inet_address_new_any (G_SOCKET_FAMILY_IPV4), port);
    }

  if (!g_socket_bind (socket, src_address, !dont_reuse_address, &error))
    {
      g_printerr ("Can't bind socket: %s\n", error->message);
      return 1;
    }
  g_object_unref (src_address);

  if (!use_udp)
    {
      if (!g_socket_listen (socket, &error))
	{
	  g_printerr ("Can't listen on socket: %s\n", error->message);
	  return 1;
	}

      address = g_socket_get_local_address (socket, &error);
      if (!address)
	{
	  g_printerr ("Error getting local address: %s\n",
		      error->message);
	  return 1;
	}
      display_addr = socket_address_to_string (address);
      g_print ("listening on %s...\n", display_addr);
      g_free (display_addr);

      ensure_socket_condition (socket, G_IO_IN, cancellable);
      new_socket = g_socket_accept (socket, cancellable, &error);
      if (!new_socket)
	{
	  g_printerr ("Error accepting socket: %s\n",
		      error->message);
	  return 1;
	}

      if (non_blocking)
	g_socket_set_blocking (new_socket, FALSE);
      if (read_timeout)
	g_socket_set_timeout (new_socket, read_timeout);

      address = g_socket_get_remote_address (new_socket, &error);
      if (!address)
	{
	  g_printerr ("Error getting remote address: %s\n",
		      error->message);
	  return 1;
	}

      display_addr = socket_address_to_string (address);
      g_print ("got a new connection from %s\n", display_addr);
      g_free(display_addr);
      g_object_unref (address);

      recv_socket = new_socket;

      connection = G_IO_STREAM (g_socket_connection_factory_create_connection (recv_socket));
      g_object_unref (new_socket);
    }
  else
    {
      recv_socket = socket;
      connection = NULL;
    }

  if (tlscert)
    {
      GIOStream *tls_conn;

      tls_conn = g_tls_server_connection_new (connection, tlscert, &error);
      if (!tls_conn)
	{
	  g_printerr ("Could not create TLS connection: %s\n",
		      error->message);
	  return 1;
	}

      if (!g_tls_connection_handshake (G_TLS_CONNECTION (tls_conn),
				       cancellable, &error))
	{
	  g_printerr ("Error during TLS handshake: %s\n",
		      error->message);
	  return 1;
       }

      g_object_unref (connection);
      connection = tls_conn;
    }

  if (connection)
    {
      istream = g_io_stream_get_input_stream (connection);
      ostream = g_io_stream_get_output_stream (connection);
    }
  else
    {
      g_assert (use_udp);
      istream = NULL;
      ostream = NULL;
    }

  while (TRUE)
    {
      gchar buffer[4096];
      gssize size;
      gsize to_send;

      if (use_udp)
	{
	  ensure_socket_condition (recv_socket, G_IO_IN, cancellable);
	  size = g_socket_receive_from (recv_socket, &address,
					buffer, sizeof buffer,
					cancellable, &error);
	}
      else
	{
	  ensure_connection_condition (connection, G_IO_IN, cancellable);
	  size = g_input_stream_read (istream,
				      buffer, sizeof buffer,
				      cancellable, &error);
	}

      if (size < 0)
	{
	  g_printerr ("Error receiving from socket: %s\n",
		      error->message);
	  return 1;
	}

      if (size == 0)
	break;

      g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
      if (use_udp)
	g_print (" from %s", socket_address_to_string (address));
      g_print ("\n");

      if (verbose)
	g_print ("-------------------------\n"
		 "%.*s\n"
		 "-------------------------\n",
		 (int)size, buffer);

      to_send = size;

#ifdef __QNXNTO__
      if (delay_)
#else
      if (delay)
#endif
	{
#ifdef __QNXNTO__
	  if (verbose)
	    g_print ("delaying %d seconds before response\n", delay_);
	  g_usleep (1000 * 1000 * delay_);
#else
	  if (verbose)
	    g_print ("delaying %d seconds before response\n", delay);
	  g_usleep (1000 * 1000 * delay);
#endif
	}

      while (to_send > 0)
	{
	  if (use_udp)
	    {
	      ensure_socket_condition (recv_socket, G_IO_OUT, cancellable);
	      size = g_socket_send_to (recv_socket, address,
				       buffer, to_send, cancellable, &error);
	    }
	  else
	    {
	      ensure_connection_condition (connection, G_IO_OUT, cancellable);
	      size = g_output_stream_write (ostream,
					    buffer, to_send,
					    cancellable, &error);
	    }

	  if (size < 0)
	    {
	      if (g_error_matches (error,
				   G_IO_ERROR,
				   G_IO_ERROR_WOULD_BLOCK))
		{
		  g_print ("socket send would block, handling\n");
		  g_error_free (error);
		  error = NULL;
		  continue;
		}
	      else
		{
		  g_printerr ("Error sending to socket: %s\n",
			      error->message);
		  return 1;
		}
	    }

	  g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);

	  if (size == 0)
	    {
	      g_printerr ("Unexpected short write\n");
	      return 1;
	    }

	  to_send -= size;
	}
    }

  g_print ("connection closed\n");

  if (connection)
    {
      if (!g_io_stream_close (connection, NULL, &error))
	{
	  g_printerr ("Error closing connection stream: %s\n",
		      error->message);
	  return 1;
	}
      g_object_unref (connection);
    }

  if (!g_socket_close (socket, &error))
    {
      g_printerr ("Error closing master socket: %s\n",
		  error->message);
      return 1;
    }
  g_object_unref (socket);

  return 0;
}
gboolean
rpmostree_compose_builtin_sign (int            argc,
                                char         **argv,
                                GCancellable  *cancellable,
                                GError       **error)
{
  gboolean ret = FALSE;
  GOptionContext *context = g_option_context_new ("- Use rpm-sign to sign an OSTree commit");
  gs_unref_object GFile *repopath = NULL;
  gs_unref_object OstreeRepo *repo = NULL;
  gs_unref_object GFile *tmp_commitdata_file = NULL;
  gs_unref_object GFileIOStream *tmp_sig_stream = NULL;
  gs_unref_object GFile *tmp_sig_file = NULL;
  gs_unref_object GFileIOStream *tmp_commitdata_stream = NULL;
  GOutputStream *tmp_commitdata_output = NULL;
  gs_unref_object GInputStream *commit_data = NULL;
  gs_free char *checksum = NULL;
  gs_unref_variant GVariant *commit_variant = NULL;
  gs_unref_bytes GBytes *commit_bytes = NULL;
  
  if (!rpmostree_option_context_parse (context, option_entries, &argc, &argv, error))
    goto out;

  if (!(opt_repo_path && opt_key_id && opt_rev))
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Missing required argument");
      goto out;
    }

  repopath = g_file_new_for_path (opt_repo_path);
  repo = ostree_repo_new (repopath);
  if (!ostree_repo_open (repo, cancellable, error))
    goto out;

  if (!ostree_repo_resolve_rev (repo, opt_rev, FALSE, &checksum, error))
    goto out;

  if (!ostree_repo_load_variant (repo, OSTREE_OBJECT_TYPE_COMMIT,
                                 checksum, &commit_variant, error))
    goto out;

  commit_bytes = g_variant_get_data_as_bytes (commit_variant);
  commit_data = (GInputStream*)g_memory_input_stream_new_from_bytes (commit_bytes);
  
  tmp_commitdata_file = g_file_new_tmp ("tmpsigXXXXXX", &tmp_commitdata_stream,
                                       error);
  if (!tmp_commitdata_file)
    goto out;

  tmp_commitdata_output = (GOutputStream*)g_io_stream_get_output_stream ((GIOStream*)tmp_commitdata_stream);
  if (g_output_stream_splice ((GOutputStream*)tmp_commitdata_output,
                              commit_data,
                              G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE |
                              G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
                              cancellable, error) < 0)
    goto out;

  tmp_sig_file = g_file_new_tmp ("tmpsigoutXXXXXX", &tmp_sig_stream, error);
  if (!tmp_sig_file)
    goto out;

  (void) g_io_stream_close ((GIOStream*)tmp_sig_stream, NULL, NULL);
                                  
  if (!gs_subprocess_simple_run_sync (NULL, GS_SUBPROCESS_STREAM_DISPOSITION_NULL,
                                      cancellable, error,
                                      "rpm-sign",
                                      "--key", opt_key_id,
                                      "--detachsign", gs_file_get_path_cached (tmp_commitdata_file),
                                      "--output", gs_file_get_path_cached (tmp_sig_file),
                                      NULL))
    goto out;

  {
    char *sigcontent = NULL;
    gsize len;
    gs_unref_bytes GBytes *sigbytes = NULL;

    if (!g_file_load_contents (tmp_sig_file, cancellable, &sigcontent, &len, NULL,
                               error))
      goto out;

    sigbytes = g_bytes_new_take (sigcontent, len);

    if (!ostree_repo_append_gpg_signature (repo, checksum, sigbytes,
                                           cancellable, error))
      goto out;
  }

  g_print ("Successfully signed OSTree commit=%s with key=%s\n",
           checksum, opt_key_id);
  
  ret = TRUE;
 out:
  if (tmp_commitdata_file)
    (void) gs_file_unlink (tmp_commitdata_file, NULL, NULL);
  if (tmp_sig_file)
    (void) gs_file_unlink (tmp_sig_file, NULL, NULL);
  return ret;
}
示例#29
0
static void
_pp_host_get_lpd_devices_thread (GTask        *task,
                                 gpointer      source_object,
                                 gpointer      task_data,
                                 GCancellable *cancellable)
{
  GSocketConnection *connection;
  PpPrintDevice     *device;
  PpHost            *host = (PpHost *) source_object;
  PpHostPrivate     *priv = host->priv;
  GSocketClient     *client;
  PpDevicesList     *result;
  GSDData           *data = (GSDData *) task_data;
  GError            *error = NULL;
  GList             *candidates = NULL;
  GList             *iter;
  gchar             *found_queue = NULL;
  gchar             *candidate;
  gchar             *address;
  gint               port;
  gint               i;

  if (priv->port == PP_HOST_UNSET_PORT)
    port = PP_HOST_DEFAULT_LPD_PORT;
  else
    port = priv->port;

  address = g_strdup_printf ("%s:%d", priv->hostname, port);
  if (address == NULL || address[0] == '/')
    goto out;

  result = data->devices;
  data->devices = NULL;

  client = g_socket_client_new ();

  connection = g_socket_client_connect_to_host (client,
                                                address,
                                                port,
                                                cancellable,
                                                &error);

  if (connection != NULL)
    {
      g_io_stream_close (G_IO_STREAM (connection), NULL, NULL);
      g_object_unref (connection);

      /* Most of this list is taken from system-config-printer */
      candidates = g_list_append (candidates, g_strdup ("PASSTHRU"));
      candidates = g_list_append (candidates, g_strdup ("AUTO"));
      candidates = g_list_append (candidates, g_strdup ("BINPS"));
      candidates = g_list_append (candidates, g_strdup ("RAW"));
      candidates = g_list_append (candidates, g_strdup ("TEXT"));
      candidates = g_list_append (candidates, g_strdup ("ps"));
      candidates = g_list_append (candidates, g_strdup ("lp"));
      candidates = g_list_append (candidates, g_strdup ("PORT1"));

      for (i = 0; i < 8; i++)
        {
          candidates = g_list_append (candidates, g_strdup_printf ("LPT%d", i));
          candidates = g_list_append (candidates, g_strdup_printf ("LPT%d_PASSTHRU", i));
          candidates = g_list_append (candidates, g_strdup_printf ("COM%d", i));
          candidates = g_list_append (candidates, g_strdup_printf ("COM%d_PASSTHRU", i));
        }

      for (i = 0; i < 50; i++)
        candidates = g_list_append (candidates, g_strdup_printf ("pr%d", i));

      for (iter = candidates; iter != NULL; iter = iter->next)
        {
          candidate = (gchar *) iter->data;

          if (test_lpd_queue (client,
                              address,
                              port,
                              cancellable,
                              candidate))
            {
              found_queue = g_strdup (candidate);
              break;
            }
        }

      if (found_queue != NULL)
        {
          device = g_new0 (PpPrintDevice, 1);
          device->device_class = g_strdup ("network");
          device->device_uri = g_strdup_printf ("lpd://%s:%d/%s",
                                                priv->hostname,
                                                port,
                                                found_queue);
          /* Translators: The found device is a Line Printer Daemon printer */
          device->device_name = g_strdup (_("LPD Printer"));
          device->host_name = g_strdup (priv->hostname);
          device->host_port = port;
          device->acquisition_method = ACQUISITION_METHOD_LPD;

          result->devices = g_list_append (result->devices, device);
        }

      g_list_free_full (candidates, g_free);
    }

  g_object_unref (client);

out:
  g_task_return_pointer (task, result, (GDestroyNotify) pp_devices_list_free);
  g_object_unref (task);

  g_free (address);
}
示例#30
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;
}