gboolean
rb_uri_mkstemp (const char *prefix, char **uri_ret, GOutputStream **stream, GError **error)
{
	GFile *file;
	char *uri = NULL;
	GFileOutputStream *fstream;
	GError *e = NULL;

	do {
		g_free (uri);
		uri = g_strdup_printf ("%s%06X", prefix, g_random_int_range (0, 0xFFFFFF));

		file = g_file_new_for_uri (uri);
		fstream = g_file_create (file, G_FILE_CREATE_PRIVATE, NULL, &e);
		if (e != NULL) {
			if (g_error_matches (e, G_IO_ERROR, G_IO_ERROR_EXISTS)) {
				g_error_free (e);
				e = NULL;
			}
		}
	} while (e == NULL && fstream == NULL);

	if (fstream != NULL) {
		*uri_ret = uri;
		*stream = G_OUTPUT_STREAM (fstream);
		return TRUE;
	} else {
		g_free (uri);
		return FALSE;
	}
}
IOChannel::IOChannel(const String& filePath, Type type)
    : m_path(filePath)
    , m_type(type)
{
    auto path = WebCore::fileSystemRepresentation(filePath);
    GRefPtr<GFile> file = adoptGRef(g_file_new_for_path(path.data()));
    switch (m_type) {
    case Type::Create: {
        g_file_delete(file.get(), nullptr, nullptr);
        m_outputStream = adoptGRef(G_OUTPUT_STREAM(g_file_create(file.get(), static_cast<GFileCreateFlags>(G_FILE_CREATE_PRIVATE), nullptr, nullptr)));
        ASSERT(m_outputStream);
        GUniquePtr<char> birthtimeString(g_strdup_printf("%" G_GUINT64_FORMAT, std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())));
        g_file_set_attribute_string(file.get(), "xattr::birthtime", birthtimeString.get(), G_FILE_QUERY_INFO_NONE, nullptr, nullptr);
        break;
    }
    case Type::Write: {
        m_ioStream = adoptGRef(g_file_open_readwrite(file.get(), nullptr, nullptr));
        ASSERT(m_ioStream);
        break;
    }
    case Type::Read:
        m_inputStream = adoptGRef(G_INPUT_STREAM(g_file_read(file.get(), nullptr, nullptr)));
        ASSERT(m_inputStream);
        break;
    }
}
Exemple #3
0
gboolean initLockFile(void)
{
	gboolean ret = TRUE;
	GError *error = NULL;
	GFileOutputStream *stream = NULL;
	gchar *tmpfile = NULL;

	myLockFile = NULL;

	tmpfile = g_build_filename(g_get_tmp_dir(), "obshutdown.lock", NULL);

	if(g_file_test(tmpfile, G_FILE_TEST_EXISTS)) {
		printMessage(MSG_ERR, "Obshutdown alredy running! Lockfile \"%s\" exist.\n", tmpfile);
		ret = FALSE;
	}
	else {
		myLockFile = g_file_new_for_path(tmpfile);
		stream = g_file_create(myLockFile, G_FILE_CREATE_NONE, NULL, &error);
		if (!stream) {
			printMessage(MSG_ERR, "Lockfile creating failed: %s\n", error->message);
			ret = FALSE;
		}
		else
			g_object_unref(stream);
	}

	g_free(tmpfile);

	return ret;
}
Exemple #4
0
static void
do_create (GVfsBackend *backend,
	   GVfsJobOpenForWrite *job,
	   const char *filename,
	   GFileCreateFlags flags)
{
  GFile *file;
  GFileOutputStream *out;
  GError *error;
  
  file = g_vfs_get_file_for_path (g_vfs_get_local (),
				  filename);

  error = NULL;
  out = g_file_create (file, flags, G_VFS_JOB (job)->cancellable, &error);
  g_object_unref (file);
  if (out)
    {
      g_vfs_job_open_for_write_set_can_seek (job, FALSE);
      g_vfs_job_open_for_write_set_handle (job, out);
      g_vfs_job_succeeded (G_VFS_JOB (job));
    }
  else
    {
      g_vfs_job_failed_from_error (G_VFS_JOB (job), error);
      g_error_free (error);
    }
}
ScLocalStorageManager* sc_local_storage_manager_new(const gchar *url) {
  ScLocalStorageManager *manager = g_new0(ScLocalStorageManager, 1);
  SoupURI *uri = soup_uri_new(url);
  GString *filename = g_string_new(NULL);
  const gchar *host = soup_uri_get_host(uri);
  const gchar *path = soup_uri_get_path(uri);
  const gchar *query = soup_uri_get_query(uri);
  const gchar *fragment = soup_uri_get_fragment(uri);
  GFile *parent = NULL;
  GError *error = NULL;

  g_string_append_printf(filename, "%s/%s", host, path);
			 
  if(url[strlen(url) - 1] == '/' || g_strcmp0("/", path) == 0)
    g_string_append(filename, "/index.html");
  
  if(query) g_string_append_printf(filename, "/%s\n", query);
  if(fragment) g_string_append_printf(filename, "#%s\n", fragment);
  manager->file = g_file_new_for_commandline_arg(filename->str);
  g_string_free(filename, TRUE);

  if(g_file_query_exists(manager->file, NULL)) {
    g_file_delete(manager->file, NULL, &error);
    if(error && !g_error_matches(error, G_IO_ERROR,G_IO_ERROR_EXISTS)) {
      g_critical(G_STRLOC ": %d : %s", error->code, error->message);
      g_error_free(error);
      g_object_unref(parent);
      g_object_unref(manager->file);
      g_free(manager);
      return NULL;
    }
  }

  parent = g_file_get_parent(manager->file);
  g_file_make_directory_with_parents(parent, NULL, &error);
  if(error && !g_error_matches(error, G_IO_ERROR,G_IO_ERROR_EXISTS)) {
    g_critical(G_STRLOC ": %d : %s", error->code, error->message);
    g_error_free(error);
    g_object_unref(parent);
    g_object_unref(manager->file);
    g_free(manager);
    return NULL;
  }

  error = NULL;
  manager->ostream = g_file_create(manager->file, G_FILE_CREATE_NONE, NULL, &error);
  if(error) {
    g_critical(G_STRLOC ": %d : %s", error->code, error->message);
    g_error_free(error);
    g_object_unref(parent);
    g_object_unref(manager->file);
    g_free(manager);
    return NULL;
  }
  return manager;
}
Exemple #6
0
JS_EXPORT_API
GFile* desktop_new_file(const char* name_add_before)
{
    GFile* file = _get_useable_file_templates(_("New file"),name_add_before);
    GFileOutputStream* stream =
        g_file_create(file, G_FILE_CREATE_NONE, NULL, NULL);
    if (stream)
        g_object_unref(stream);
    return file;
}
static void
create_one_file (GFile *file)
{
        GFileOutputStream* stream;

        stream = g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL);
        if (stream != NULL) {
                g_output_stream_close (G_OUTPUT_STREAM (stream), NULL, NULL);
                g_object_unref (stream);
        }
}
/* Tests the function for a simple file */
static void
test_simple_file (void)
{
    g_autoptr (GFile) root = NULL;
    g_autoptr (GFile) file = NULL;

    root = g_file_new_for_path (g_get_tmp_dir ());
    file = g_file_get_child (root, "simple_file");
    g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL);
    g_assert_false (dir_has_files (file));
    g_assert_true (g_file_delete (file, NULL, NULL));
}
static gboolean
gst_gio_sink_start (GstBaseSink * base_sink)
{
  GstGioSink *sink = GST_GIO_SINK (base_sink);
  GOutputStream *stream;
  GCancellable *cancel = GST_GIO_BASE_SINK (sink)->cancel;
  gboolean success;
  GError *err = NULL;
  gchar *uri;

  if (sink->file == NULL) {
    GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_WRITE, (NULL),
        ("No location or GFile given"));
    return FALSE;
  }

  uri = g_file_get_uri (sink->file);
  if (!uri)
    uri = g_strdup ("(null)");

  stream =
      G_OUTPUT_STREAM (g_file_create (sink->file, G_FILE_CREATE_NONE, cancel,
          &err));

  success = (stream != NULL);

  if (!success && !gst_gio_error (sink, "g_file_create", &err, NULL)) {

    /*if (GST_GIO_ERROR_MATCHES (err, EXISTS)) */
    /* FIXME: Retry with replace if overwrite == TRUE! */

    if (GST_GIO_ERROR_MATCHES (err, NOT_FOUND))
      GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, (NULL),
          ("Could not open location %s for writing: %s", uri, err->message));
    else
      GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_READ, (NULL),
          ("Could not open location %s for writing: %s", uri, err->message));

    g_free (uri);
    g_clear_error (&err);
  }

  if (!success)
    return FALSE;

  GST_DEBUG_OBJECT (sink, "opened location %s", uri);

  g_free (uri);

  gst_gio_base_sink_set_stream (GST_GIO_BASE_SINK (sink), stream);

  return GST_BASE_SINK_CLASS (parent_class)->start (base_sink);
}
    void didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
    {
        m_response = response;
        m_download->didReceiveResponse(response);

        if (response.httpStatusCode() >= 400) {
            downloadFailed(platformDownloadNetworkError(response.httpStatusCode(), response.url(), response.httpStatusText()));
            return;
        }

        String suggestedFilename = response.suggestedFilename();
        if (suggestedFilename.isEmpty()) {
            URL url = response.url();
            url.setQuery(String());
            url.removeFragmentIdentifier();
            suggestedFilename = decodeURLEscapeSequences(url.lastPathComponent());
        }

        String destinationURI = m_download->decideDestinationWithSuggestedFilename(suggestedFilename, m_allowOverwrite);
        if (destinationURI.isEmpty()) {
#if PLATFORM(GTK)
            GUniquePtr<char> buffer(g_strdup_printf(_("Cannot determine destination URI for download with suggested filename %s"), suggestedFilename.utf8().data()));
            String errorMessage = String::fromUTF8(buffer.get());
#else
            String errorMessage = makeString("Cannot determine destination URI for download with suggested filename ", suggestedFilename);
#endif
            downloadFailed(platformDownloadDestinationError(response, errorMessage));
            return;
        }

        m_destinationFile = adoptGRef(g_file_new_for_uri(destinationURI.utf8().data()));
        GRefPtr<GFileOutputStream> outputStream;
        GUniqueOutPtr<GError> error;
        if (m_allowOverwrite)
            outputStream = adoptGRef(g_file_replace(m_destinationFile.get(), nullptr, FALSE, G_FILE_CREATE_NONE, nullptr, &error.outPtr()));
        else
            outputStream = adoptGRef(g_file_create(m_destinationFile.get(), G_FILE_CREATE_NONE, nullptr, &error.outPtr()));
        if (!outputStream) {
            m_destinationFile.clear();
            downloadFailed(platformDownloadDestinationError(response, error->message));
            return;
        }

        String intermediateURI = destinationURI + ".wkdownload";
        m_intermediateFile = adoptGRef(g_file_new_for_uri(intermediateURI.utf8().data()));
        m_outputStream = adoptGRef(g_file_replace(m_intermediateFile.get(), 0, TRUE, G_FILE_CREATE_NONE, 0, &error.outPtr()));
        if (!m_outputStream) {
            downloadFailed(platformDownloadDestinationError(response, error->message));
            return;
        }

        m_download->didCreateDestination(destinationURI);
    }
Exemple #11
0
/* Touch. */
gboolean
misc_create_file (const gchar *filepath)
{
    GFileOutputStream *noused;
    GFile *file;

    file = g_file_new_for_path (filepath);
    noused = g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL);

    g_object_unref(file);

    return noused != NULL;
}
Exemple #12
0
void
lsm_dom_document_save_to_url (LsmDomDocument *document, const char *path, GError **error)
{
	GFile *file;
	GFileOutputStream *stream;

	g_return_if_fail (path != NULL);

	file = g_file_new_for_uri (path);
	stream = g_file_create (file, G_FILE_CREATE_REPLACE_DESTINATION, NULL, error);
	if (stream != NULL) {
		lsm_dom_document_save_to_stream (document, G_OUTPUT_STREAM (stream), error);
		g_object_unref (stream);
	}
	g_object_unref (file);
}
Exemple #13
0
static gboolean
ori_save (gchar * fn, gboolean replace)
{
  gchar *text;
  GFile *fp;
  GFileOutputStream *file_out;
  GError *error = NULL;
  char *nullstr = "NULLSTRING";
  gssize bytes;

  if (!fn)
	fn = nullstr;

  fp = g_file_new_for_uri (fn);

  file_out = g_file_create (fp, G_FILE_CREATE_NONE, NULL, &error);
  if ((file_out == NULL) && (error->code == G_IO_ERROR_EXISTS))
	{
	  if (replace)
		{
		  g_error_free (error);
		/* replace file */
		  file_out = g_file_replace (fp, NULL, TRUE, G_FILE_CREATE_NONE, NULL, &error);
		}
	}
  text = gui_editor_get_text (app->editor);
  if (file_out == NULL)
	{
	  gchar errmsg[MAX_ERR_MSG_SIZE + 1];
	  g_snprintf (errmsg, MAX_ERR_MSG_SIZE, _("Failed to save <%s>"),
				  fn);
	  gui_app_show_msg (GTK_MESSAGE_ERROR, errmsg);
	  return TRUE;
	}
  bytes = g_output_stream_write (G_OUTPUT_STREAM (file_out), text, strlen (text), NULL, NULL);
  gtk_text_buffer_set_modified ((GtkTextBuffer *)app->editor->buffer, FALSE);
  
  /* debug */
  g_output_stream_close (G_OUTPUT_STREAM (file_out), NULL, NULL);

  g_free (text);
  if (replace)
	_set_file_name (fn);

  /*g_error_free (error);*/
  return TRUE;
}
/* called in an I/O thread */
static GOutputStream *
get_stream_for_unique_path (const gchar *path,
                            const gchar *filename,
                            gchar **filename_used)
{
  GOutputStream *stream;
  GFile *file;
  gchar *real_path, *real_filename, *name, *ptr;
  gint idx;

  ptr = g_strrstr (filename, ".png");

  if (ptr != NULL)
    real_filename = g_strndup (filename, ptr - filename);
  else
    real_filename = g_strdup (filename);

  idx = 0;
  real_path = NULL;

  do
    {
      if (idx == 0)
        name = g_strdup_printf ("%s.png", real_filename);
      else
        name = g_strdup_printf ("%s - %d.png", real_filename, idx);

      real_path = g_build_filename (path, name, NULL);
      g_free (name);

      file = g_file_new_for_path (real_path);
      stream = G_OUTPUT_STREAM (g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL));
      g_object_unref (file);

      if (stream != NULL)
        *filename_used = real_path;
      else
        g_free (real_path);

      idx++;
    }
  while (stream == NULL);

  g_free (real_filename);

  return stream;
}
Exemple #15
0
static void
_completion_create_initial_file(GFile *file, const gchar *text)
{
	gchar *path;
	gint len;
	GFileOutputStream *stream;
	gchar buffer[block_size];

	g_assert(file != NULL);
	g_assert(text != NULL);

	len = strlen(text);

	g_return_if_fail(len <= COMPLETION_STRING_SIZE);

	path = g_file_get_path(file);

	g_debug("Creating file: \"%s\"", path);

	if((stream = g_file_create(file, G_FILE_CREATE_PRIVATE, NULL, NULL)))
	{
		memset(buffer, 0, block_size);
		memcpy(buffer + COMPLETION_COUNTER_SIZE, text, len);

		g_debug("Appending new text: \"%s\"", text);
		g_output_stream_write(G_OUTPUT_STREAM(stream), buffer, block_size, NULL, NULL);
		g_output_stream_flush(G_OUTPUT_STREAM(stream), NULL, NULL);

		g_output_stream_close(G_OUTPUT_STREAM(stream), NULL, NULL);
		g_object_unref(stream);
	}
	else
	{
		g_warning("Couldn't create file: \"%s\"", path);
	}

	g_free(path);
}
static void
export_png (GtkButton     *button,
    ChamplainView *view)
{
  cairo_surface_t *surface;
  GdkPixbuf *pixbuf;
  GFileOutputStream *os;
  GFile *file;
  gint width, height;

  if (champlain_view_get_state (view) != CHAMPLAIN_STATE_DONE)
    return;

  surface = champlain_view_to_surface (view, TRUE);
  if (!surface)
    return;

  width = cairo_image_surface_get_width (surface);
  height = cairo_image_surface_get_height (surface);
  pixbuf = gdk_pixbuf_get_from_surface (surface, 0, 0, width, height);
  if (!pixbuf)
    return;

  file = g_file_new_for_path ("champlain-map.png");
  os = g_file_create (file, G_FILE_CREATE_NONE, NULL, NULL);
  if (!os)
    {
      g_object_unref (pixbuf);
      return;
    }

  gdk_pixbuf_save_to_stream_async (pixbuf,
                                   G_OUTPUT_STREAM (os), "png",
                                   NULL,
                                   (GAsyncReadyCallback) export_to_png_cb,
                                   NULL);
}
Exemple #17
0
gboolean
ostree_create_file_from_input (GFile            *dest_file,
                               GFileInfo        *finfo,
                               GVariant         *xattrs,
                               GInputStream     *input,
                               GCancellable     *cancellable,
                               GError          **error)
{
  gboolean ret = FALSE;
  const char *dest_path;
  guint32 uid, gid, mode;
  ot_lobj GFileOutputStream *out = NULL;

  if (g_cancellable_set_error_if_cancelled (cancellable, error))
    return FALSE;

  if (finfo != NULL)
    {
      mode = g_file_info_get_attribute_uint32 (finfo, "unix::mode");
    }
  else
    {
      mode = S_IFREG | 0664;
    }
  dest_path = ot_gfile_get_path_cached (dest_file);

  if (S_ISDIR (mode))
    {
      if (mkdir (ot_gfile_get_path_cached (dest_file), mode) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          goto out;
        }
    }
  else if (S_ISREG (mode))
    {
      out = g_file_create (dest_file, 0, cancellable, error);
      if (!out)
        goto out;

      if (input)
        {
          if (g_output_stream_splice ((GOutputStream*)out, input, 0,
                                      cancellable, error) < 0)
            goto out;
        }

      if (!g_output_stream_close ((GOutputStream*)out, NULL, error))
        goto out;
    }
  else if (S_ISLNK (mode))
    {
      const char *target = g_file_info_get_attribute_byte_string (finfo, "standard::symlink-target");
      if (symlink (target, dest_path) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          goto out;
        }
    }
  else if (S_ISCHR (mode) || S_ISBLK (mode))
    {
      guint32 dev = g_file_info_get_attribute_uint32 (finfo, "unix::rdev");
      if (mknod (dest_path, mode, dev) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          goto out;
        }
    }
  else if (S_ISFIFO (mode))
    {
      if (mkfifo (dest_path, mode) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          goto out;
        }
    }
  else
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Invalid mode %u", mode);
      goto out;
    }

  if (finfo != NULL)
    {
      uid = g_file_info_get_attribute_uint32 (finfo, "unix::uid");
      gid = g_file_info_get_attribute_uint32 (finfo, "unix::gid");
      
      if (lchown (dest_path, uid, gid) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          g_prefix_error (error, "lchown(%u, %u) failed: ", uid, gid);
          goto out;
        }
    }

  if (!S_ISLNK (mode))
    {
      if (chmod (dest_path, mode) < 0)
        {
          ot_util_set_error_from_errno (error, errno);
          g_prefix_error (error, "chmod(%u) failed: ", mode);
          goto out;
        }
    }

  if (xattrs != NULL)
    {
      if (!ostree_set_xattrs (dest_file, xattrs, cancellable, error))
        goto out;
    }

  ret = TRUE;
 out:
  if (!ret && !S_ISDIR(mode))
    {
      (void) unlink (dest_path);
    }
  return ret;
}
Exemple #18
0
static void
catalog_new_dialog_response_cb (GtkWidget *dialog,
				int        response_id,
				gpointer   user_data)
{
	GthBrowser    *browser = user_data;
	char          *name;
	GthFileData   *selected_parent;
	GFile         *parent;
	GthFileSource *file_source;
	GFile         *gio_parent;
	char          *display_name;
	GError        *error = NULL;
	GFile         *gio_file;

	if (response_id != GTK_RESPONSE_OK) {
		gtk_widget_destroy (dialog);
		return;
	}

	name = gth_request_dialog_get_normalized_text (GTH_REQUEST_DIALOG (dialog));
	if (_g_utf8_all_spaces (name)) {
		g_free (name);
		gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, _("No name specified"));
		return;
	}

	if (g_regex_match_simple ("/", name, 0, 0)) {
		char *message;

		message = g_strdup_printf (_("Invalid name. The following characters are not allowed: %s"), "/");
		gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, message);

		g_free (message);
		g_free (name);

		return;
	}

	selected_parent = gth_browser_get_folder_popup_file_data (browser);
	if (selected_parent != NULL) {
		GthFileSource *file_source;
		GFileInfo     *info;

		file_source = gth_main_get_file_source (selected_parent->file);
		info = gth_file_source_get_file_info (file_source, selected_parent->file, GFILE_BASIC_ATTRIBUTES);
		if (g_file_info_get_attribute_boolean (info, "gthumb::no-child"))
			parent = g_file_get_parent (selected_parent->file);
		else
			parent = g_file_dup (selected_parent->file);

		g_object_unref (info);
		g_object_unref (file_source);
	}
	else
		parent = g_file_new_for_uri ("catalog:///");

	file_source = gth_main_get_file_source (parent);
	gio_parent = gth_file_source_to_gio_file (file_source, parent);
	display_name = g_strconcat (name, ".catalog", NULL);
	gio_file = g_file_get_child_for_display_name (gio_parent, display_name, &error);
	if (gio_file != NULL) {
		GFileOutputStream *stream;

		stream = g_file_create (gio_file, G_FILE_CREATE_NONE, NULL, &error);
		if (stream != NULL) {
			GFile *file;
			GList *list;

			file = gth_catalog_file_from_gio_file (gio_file, NULL);
			list = g_list_prepend (NULL, file);
			gth_monitor_folder_changed (gth_main_get_default_monitor (),
						    parent,
						    list,
						    GTH_MONITOR_EVENT_CREATED);

			g_list_free (list);
			g_object_unref (file);
			g_object_unref (stream);
		}

		g_object_unref (gio_file);
	}

	if (error != NULL) {
		if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS))
			gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, _("Name already used"));
		else
			gth_request_dialog_set_info_text (GTH_REQUEST_DIALOG (dialog), GTK_MESSAGE_ERROR, error->message);
		g_clear_error (&error);
	}
	else
		gtk_widget_destroy (dialog);

	g_free (display_name);
	g_object_unref (gio_parent);
	g_object_unref (file_source);
	g_free (name);
}
Exemple #19
0
void on_create_new(GtkAction* action, FmMainWin* win)
{
    FmFolderView* fv = FM_FOLDER_VIEW(win->folder_view);
    const char* name = gtk_action_get_name(action);
    GError* err = NULL;
    FmPath* cwd = fm_folder_view_get_cwd(fv);
    FmPath* dest;
    char* basename;
_retry:
    basename = fm_get_user_input(GTK_WINDOW(win), _("Create New..."), _("Enter a name for the newly created file:"), _("New"));
    if(!basename)
        return;

    dest = fm_path_new_child(cwd, basename);
    g_free(basename);

    if( strcmp(name, "NewFolder") == 0 )
    {
        GFile* gf = fm_path_to_gfile(dest);
        if(!g_file_make_directory(gf, NULL, &err))
        {
            if(err->domain = G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
            {
                fm_path_unref(dest);
                g_error_free(err);
                g_object_unref(gf);
                err = NULL;
                goto _retry;
            }
            fm_show_error(GTK_WINDOW(win), err->message);
            g_error_free(err);
        }

        if(!err) /* select the newly created file */
        {
            /*FIXME: this doesn't work since the newly created file will
             * only be shown after file-created event was fired on its
             * folder's monitor and after FmFolder handles it in idle
             * handler. So, we cannot select it since it's not yet in
             * the folder model now. */
            /* fm_folder_view_select_file_path(fv, dest); */
        }
        g_object_unref(gf);
    }
    else if( strcmp(name, "NewBlank") == 0 )
    {
        GFile* gf = fm_path_to_gfile(dest);
        GFileOutputStream* f = g_file_create(gf, G_FILE_CREATE_NONE, NULL, &err);
        if(f)
        {
            g_output_stream_close(G_OUTPUT_STREAM(f), NULL, NULL);
            g_object_unref(f);
        }
        else
        {
            if(err->domain = G_IO_ERROR && err->code == G_IO_ERROR_EXISTS)
            {
                fm_path_unref(dest);
                g_error_free(err);
                g_object_unref(gf);
                err = NULL;
                goto _retry;
            }
            fm_show_error(GTK_WINDOW(win), err->message);
            g_error_free(err);
        }

        if(!err) /* select the newly created file */
        {
            /*FIXME: this doesn't work since the newly created file will
             * only be shown after file-created event was fired on its
             * folder's monitor and after FmFolder handles it in idle
             * handler. So, we cannot select it since it's not yet in
             * the folder model now. */
            /* fm_folder_view_select_file_path(fv, dest); */
        }
        g_object_unref(gf);
    }
    else /* templates */
    {

    }
    fm_path_unref(dest);
}
static gboolean
run (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  g_autoptr(GOptionContext) context = NULL;
  const char *dirpath;
  OtTrivialHttpd appstruct = { 0, };
  OtTrivialHttpd *app = &appstruct;
  glnx_unref_object SoupServer *server = NULL;
  g_autoptr(GFileMonitor) dirmon = NULL;

  context = g_option_context_new ("[DIR] - Simple webserver");
  g_option_context_add_main_entries (context, options, NULL);

  app->root_dfd = -1;

  if (!g_option_context_parse (context, &argc, &argv, error))
    goto out;

  if (argc > 1)
    dirpath = argv[1];
  else
    dirpath = ".";

  if (!glnx_opendirat (AT_FDCWD, dirpath, TRUE, &app->root_dfd, error))
    goto out;

  if (!(opt_random_500s_percentage >= 0 && opt_random_500s_percentage <= 99))
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Invalid --random-500s=%u", opt_random_500s_percentage);
      goto out;
    }

  if (opt_log)
    {
      GOutputStream *stream = NULL;

      if (g_strcmp0 (opt_log, "-") == 0)
        {
          if (opt_daemonize)
            {
              ot_util_usage_error (context, "Cannot use --log-file=- and --daemonize at the same time", error);
              goto out;
            }
          stream = G_OUTPUT_STREAM (g_unix_output_stream_new (STDOUT_FILENO, FALSE));
        }
      else
        {
          g_autoptr(GFile) log_file = NULL;
          GFileOutputStream* log_stream;

          log_file = g_file_new_for_path (opt_log);
          log_stream = g_file_create (log_file,
                                      G_FILE_CREATE_PRIVATE,
                                      cancellable,
                                      error);
          if (!log_stream)
            goto out;
          stream = G_OUTPUT_STREAM (log_stream);
        }

      app->log = stream;
    }

#if SOUP_CHECK_VERSION(2, 48, 0)
  server = soup_server_new (SOUP_SERVER_SERVER_HEADER, "ostree-httpd ", NULL);
  if (!soup_server_listen_all (server, opt_port, 0, error))
    goto out;
#else
  server = soup_server_new (SOUP_SERVER_PORT, opt_port,
                            SOUP_SERVER_SERVER_HEADER, "ostree-httpd ",
                            NULL);
#endif

  soup_server_add_handler (server, NULL, httpd_callback, app, NULL);
  if (opt_port_file)
    {
      g_autofree char *portstr = NULL;
#if SOUP_CHECK_VERSION(2, 48, 0)
      GSList *listeners = soup_server_get_listeners (server);
      g_autoptr(GSocket) listener = NULL;
      g_autoptr(GSocketAddress) addr = NULL;
      
      g_assert (listeners);
      listener = g_object_ref (listeners->data);
      g_slist_free (listeners);
      listeners = NULL;
      addr = g_socket_get_local_address (listener, error);
      if (!addr)
        goto out;

      g_assert (G_IS_INET_SOCKET_ADDRESS (addr));
      
      portstr = g_strdup_printf ("%u\n", g_inet_socket_address_get_port ((GInetSocketAddress*)addr));
#else
      portstr = g_strdup_printf ("%u\n", soup_server_get_port (server));
#endif

      if (g_strcmp0 ("-", opt_port_file) == 0)
        {
          fputs (portstr, stdout); // not g_print - this must go to stdout, not a handler
          fflush (stdout);
        }
      else if (!g_file_set_contents (opt_port_file, portstr, strlen (portstr), error))
        goto out;
    }
#if !SOUP_CHECK_VERSION(2, 48, 0)
  soup_server_run_async (server);
#endif
  
  if (opt_daemonize)
    {
      pid_t pid = fork();
      if (pid == -1)
        {
          int errsv = errno;
          g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (errsv),
                               g_strerror (errsv));
          goto out;
        }
      else if (pid > 0)
        {
          ret = TRUE;
          goto out;
        }
      /* Child, continue */
      if (setsid () < 0)
        err (1, "setsid");
      /* Daemonising: close stdout/stderr so $() et al work on us */
      if (freopen("/dev/null", "r", stdin) == NULL)
        err (1, "freopen");
      if (freopen("/dev/null", "w", stdout) == NULL)
        err (1, "freopen");
      if (freopen("/dev/null", "w", stderr) == NULL)
        err (1, "freopen");
    }
  else
    {
      /* Since we're used for testing purposes, let's just do this by
       * default.  This ensures we exit when our parent does.
       */
      if (prctl (PR_SET_PDEATHSIG, SIGTERM) != 0)
        {
          if (errno != ENOSYS)
            {
              glnx_set_error_from_errno (error);
              goto out;
            }
        }
    }

  app->running = TRUE;
  if (opt_autoexit)
    {
      gboolean is_symlink = FALSE;
      g_autoptr(GFile) root = NULL;
      g_autoptr(GFileInfo) info = NULL;

      root = g_file_new_for_path (dirpath);
      info = g_file_query_info (root,
                                G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK,
                                G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
                                cancellable, error);
      if (!info)
        goto out;

      is_symlink = g_file_info_get_is_symlink (info);

      if (is_symlink)
        dirmon = g_file_monitor_file (root, 0, cancellable, error);
      else
        dirmon = g_file_monitor_directory (root, 0, cancellable, error);

      if (!dirmon)
        goto out;
      g_signal_connect (dirmon, "changed", G_CALLBACK (on_dir_changed), app);
    }
  httpd_log (app, "serving at root %s\n", dirpath);
  while (app->running)
    g_main_context_iteration (NULL, TRUE);

  ret = TRUE;
 out:
  if (app->root_dfd != -1)
    (void) close (app->root_dfd);
  g_clear_object (&app->log);
  return ret;
}
Exemple #21
0
gboolean
ot_gpgme_ctx_tmp_home_dir (gpgme_ctx_t     gpgme_ctx,
                           const char     *tmp_dir,
                           char          **out_tmp_home_dir,
                           GOutputStream **out_pubring_stream,
                           GCancellable   *cancellable,
                           GError        **error)
{
  g_autoptr(GFile) pubring_file = NULL;
  g_autoptr(GOutputStream) target_stream = NULL;
  g_autofree char *pubring_path = NULL;
  g_autofree char *tmp_home_dir = NULL;
  gpgme_error_t gpg_error;
  gboolean ret = FALSE;

  g_return_val_if_fail (gpgme_ctx != NULL, FALSE);

  /* GPGME has no API for using multiple keyrings (aka, gpg --keyring),
   * so we create a temporary directory and tell GPGME to use it as the
   * home directory.  Then (optionally) create a pubring.gpg file there
   * and hand the caller an open output stream to concatenate necessary
   * keyring files. */

  if (tmp_dir == NULL)
    tmp_dir = g_get_tmp_dir ();

  tmp_home_dir = g_build_filename (tmp_dir, "ostree-gpg-XXXXXX", NULL);

  if (mkdtemp (tmp_home_dir) == NULL)
    {
      glnx_set_error_from_errno (error);
      goto out;
    }

  /* Not documented, but gpgme_ctx_set_engine_info() accepts NULL for
   * the executable file name, which leaves the old setting unchanged. */
  gpg_error = gpgme_ctx_set_engine_info (gpgme_ctx,
                                         GPGME_PROTOCOL_OpenPGP,
                                         NULL, tmp_home_dir);
  if (gpg_error != GPG_ERR_NO_ERROR)
    {
      ot_gpgme_error_to_gio_error (gpg_error, error);
      goto out;
    }

  if (out_pubring_stream != NULL)
    {
      GFileOutputStream *pubring_stream;
      glnx_unref_object GFile *pubring_file = NULL;
      g_autofree char *pubring_path = NULL;

      pubring_path = g_build_filename (tmp_home_dir, "pubring.gpg", NULL);
      pubring_file = g_file_new_for_path (pubring_path);

      pubring_stream = g_file_create (pubring_file,
                                      G_FILE_CREATE_NONE,
                                      cancellable, error);
      if (pubring_stream == NULL)
        goto out;

      /* Sneaky cast from GFileOutputStream to GOutputStream. */
      *out_pubring_stream = g_steal_pointer (&pubring_stream);
    }

  if (out_tmp_home_dir != NULL)
    *out_tmp_home_dir = g_steal_pointer (&tmp_home_dir);

  ret = TRUE;

out:
  if (!ret)
    {
      /* Clean up our mess on error. */
      (void) glnx_shutil_rm_rf_at (AT_FDCWD, tmp_home_dir, NULL, NULL);
    }

  return ret;
}
Exemple #22
0
static GFile *
filebox_uploader_handle_task_create_tmp (HevFileboxUploader *self,
			GObject *task, GInputStream *req_stream, GHashTable *req_htb,
			GHashTable *res_htb, const gchar *ft_path, gsize size)
{
	GFile *file = NULL;
	gboolean status = TRUE;
	gchar name[256], *path = NULL;
	const gchar *remote_addr = NULL, *remote_port = NULL;
	GFileOutputStream *file_ostream = NULL;

	g_debug ("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	remote_addr = g_hash_table_lookup (req_htb, "REMOTE_ADDR");
	remote_port = g_hash_table_lookup (req_htb, "REMOTE_PORT");

	g_snprintf (name, 256, "%s-%s.tmp", remote_addr, remote_port);
	path = g_build_filename (ft_path, name, NULL);
	file = g_file_new_for_path (path);
	g_free (path);

	file_ostream = g_file_create (file, G_FILE_CREATE_PRIVATE, NULL, NULL);
	if (!file_ostream) {
		g_hash_table_insert (res_htb, g_strdup ("Status"), g_strdup ("403 Forbidden"));
		g_object_unref (file);
		return NULL;
	}

	/* write to tmp file */
	for (; 0<size;) {
		guint8 buffer[8192];
		gssize rsize = 0;

		rsize = g_input_stream_read (req_stream,
					buffer, 8192, NULL, NULL);
		if (-1 == rsize) {
			status = FALSE;
			break;
		} else if (0 == rsize) {
			break;
		}

		if (!g_output_stream_write_all (G_OUTPUT_STREAM (file_ostream),
						buffer, rsize, NULL, NULL, NULL)) {
			status = FALSE;
			break;
		}
		size -= rsize;
	}

	g_object_unref (file_ostream);

	if (!status) {
		g_hash_table_insert (res_htb, g_strdup ("Status"),
					g_strdup ("500 Internal Server Error"));
		g_object_unref (file);
		return NULL;
	}

	return file;
}
static gboolean
_save_to_uri (GESFormatter * formatter, GESTimeline * timeline,
    const gchar * uri, gboolean overwrite, GError ** error)
{
  GFile *file;
  gboolean ret;
  GString *str;
  GOutputStream *stream;
  GError *lerror = NULL;

  g_return_val_if_fail (formatter->project, FALSE);

  file = g_file_new_for_uri (uri);
  stream = G_OUTPUT_STREAM (g_file_create (file, G_FILE_CREATE_NONE, NULL,
          &lerror));
  if (stream == NULL) {
    if (overwrite && lerror->code == G_IO_ERROR_EXISTS) {
      g_clear_error (&lerror);
      stream = G_OUTPUT_STREAM (g_file_replace (file, NULL, FALSE,
              G_FILE_CREATE_NONE, NULL, &lerror));
    }

    if (stream == NULL)
      goto failed_opening_file;
  }

  str = GES_BASE_XML_FORMATTER_GET_CLASS (formatter)->save (formatter,
      timeline, error);

  if (str == NULL)
    goto serialization_failed;

  ret = g_output_stream_write_all (stream, str->str, str->len, NULL,
      NULL, &lerror);
  ret = g_output_stream_close (stream, NULL, &lerror);

  if (ret == FALSE)
    GST_WARNING_OBJECT (formatter, "Could not save %s because: %s", uri,
        lerror->message);

  g_string_free (str, TRUE);
  gst_object_unref (file);
  gst_object_unref (stream);

  if (lerror)
    g_propagate_error (error, lerror);

  return ret;

serialization_failed:
  gst_object_unref (file);

  g_output_stream_close (stream, NULL, NULL);
  gst_object_unref (stream);
  if (lerror)
    g_propagate_error (error, lerror);

  return FALSE;

failed_opening_file:
  gst_object_unref (file);

  GST_WARNING_OBJECT (formatter, "Could not open %s because: %s", uri,
      lerror->message);

  if (lerror)
    g_propagate_error (error, lerror);

  return FALSE;
}
Exemple #24
0
static void
file_ptr_array_foreach_write_meta_handler (gpointer data, gpointer user_data)
{
	GFile *file = G_FILE (data), *meta_file = NULL;
	GObject *scgi_task = G_OBJECT (user_data);
	GObject *request = NULL;
	GHashTable *req_htb = NULL;
	gchar *duration = NULL, *one_off = NULL, *rand_pass = NULL;
	GKeyFile *meta = NULL;
	GDateTime *crt_time = NULL, *exp_time = NULL;
	GFileOutputStream *file_ostream = NULL;
	guint64 dur = 0;

	g_debug ("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	request = hev_scgi_task_get_request (HEV_SCGI_TASK (scgi_task));
	req_htb = hev_scgi_request_get_header_hash_table (HEV_SCGI_REQUEST (request));

	duration = g_object_get_data (scgi_task, "duration");
	one_off = g_object_get_data (scgi_task, "one-off");
	rand_pass = g_object_get_data (scgi_task, "rand-pass");

	meta_file = g_object_get_data (G_OBJECT (file), "meta");
	g_file_delete (meta_file, NULL, NULL);
	meta = g_key_file_new ();

	/* set meta contents */
	crt_time = g_date_time_new_now_utc ();
	g_key_file_set_int64 (meta, "Meta", "CrtDate",
				g_date_time_to_unix (crt_time));
	if (duration) {
		dur = g_ascii_strtoull (duration, NULL, 10);
		if ((0 >= dur) || (7 < dur))
		  dur = 1;
	} else {
		dur = 1;
	}
	exp_time = g_date_time_add_days (crt_time, dur);
	g_key_file_set_int64 (meta, "Meta", "ExpDate",
				g_date_time_to_unix (exp_time));
	g_date_time_unref (exp_time);
	g_date_time_unref (crt_time);
	g_key_file_set_boolean (meta, "Meta", "OneOff", one_off ? TRUE : FALSE);
	g_key_file_set_string (meta, "Meta", "IP",
				g_hash_table_lookup (req_htb, "REMOTE_ADDR"));
	g_key_file_set_string (meta, "Meta", "RandPass", rand_pass);

	/* create and write to meta file */
	file_ostream = g_file_create (meta_file, G_FILE_CREATE_PRIVATE, NULL, NULL);
	if (file_ostream) {
		gchar *data = NULL;
		gsize length = 0;
		data = g_key_file_to_data (meta, &length, NULL);
		g_output_stream_write_all (G_OUTPUT_STREAM (file_ostream),
					data, length, NULL, NULL, NULL);
		g_free (data);
		g_object_unref (file_ostream);
	}

	g_key_file_unref (meta);
}
static void
update_mimelist (NemoMimeApplicationChooser *chooser, const gchar *fn, gboolean def)
{
    gchar *list_fn = g_build_filename (g_get_user_data_dir (), "applications", "mimeapps.list", NULL);
    GKeyFile *mimeapps;
    GFile *list_file;

    list_file = g_file_new_for_path (list_fn);
    mimeapps = g_key_file_new ();

    if (g_file_query_exists (list_file, NULL)) {
        g_key_file_load_from_file (mimeapps,
                                   list_fn,
                                   G_KEY_FILE_NONE,
                                   NULL);
    }

    if (def) {
        g_key_file_set_string (mimeapps,
                               DEFAULT_APPS,
                               chooser->details->content_type,
                               fn);
    } else {
        gsize count;

        gchar **l = g_key_file_get_string_list (mimeapps,
                                                ADDED_ASS,
                                                chooser->details->content_type,
                                                &count,
                                                NULL);

        gchar *new_string_list;

        if (l) {
            gchar *temp_list;
            temp_list = g_strjoinv (";", l);
            new_string_list = g_strdup_printf ("%s;%s;", fn, temp_list);
            g_free (temp_list);
            g_strfreev (l);
        } else {
            new_string_list = g_strdup_printf ("%s;", fn);
        }


        g_key_file_set_string (mimeapps,
                               ADDED_ASS,
                               chooser->details->content_type,
                               new_string_list);
    }

    if (g_file_query_exists (list_file, NULL)) {
        g_file_delete (list_file, NULL, NULL);
    }

    gsize size;
    gchar *buffer = g_key_file_to_data (mimeapps, &size, NULL);
    GFileOutputStream *out;
    gboolean res;

    out = g_file_create (list_file,
                         G_FILE_CREATE_NONE,
                         NULL,
                         NULL);
    if (out) {
        res = g_output_stream_write_all (G_OUTPUT_STREAM (out),
                                         buffer, size,
                                         NULL,
                                         NULL,
                                         NULL);
        if (res) {
            res = g_output_stream_close (G_OUTPUT_STREAM (out),
                                         NULL,
                                         NULL);
        }
        g_object_unref (out);
    }

    g_free (buffer);

}
static GOutputStream *
get_checksum_stream (CheckcopyFileList * list, GFile * dest)
{
  CheckcopyFileListPrivate *priv = GET_PRIVATE (list);

  gchar * basename;
  gchar * checksum_name;
  GFileOutputStream * out = NULL;
  GError *error = NULL;
  GCancellable * cancel;
  GFile *checksum = NULL;
  gint i;
  gchar *ext = "CHECKSUM";

  cancel = checkcopy_get_cancellable ();

  if (priv->checksum_file) {
    /* We already have a file. Just append to it. */
    out = g_file_append_to (priv->checksum_file, 0, cancel, &error);

    if (!out || error) {
      thread_show_gerror (dest, error);
      g_error_free (error);
      error = NULL;

      return NULL;
    } else {
      return G_OUTPUT_STREAM (out);
    }
  }


  /* We do not have a file yet, search for one */

  basename = g_file_get_basename (dest);

  i = 0;
  do {
    DBG ("Try %d to generate a checksum file name", i);
    if (checksum) {
      g_object_unref (checksum);
      checksum = NULL;
    }

    if (error) {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS)) {
        /* There was an error, but it was not that the file already exists.
         * We should abort at this point. */

        thread_show_error (_("Failed to create checksum file: %s"), error->message);
        g_error_free (error);
        error = NULL;
        break;
      } else {
        /* continue with next iteration */

        g_error_free (error);
        error = NULL;

        if (i > MAX_CHECKSUM_FILE_RETRIES) {
          thread_show_error (_("Maximum number of retries reached.\nCould not create a checksum file."));
          break;
        }
      }
    }

    if (basename == NULL) {
      checksum_name = g_strdup (ext);
    } else {
      if (i==0)
        checksum_name = g_strconcat (basename, ".", ext, NULL);
      else
        checksum_name = g_strdup_printf ("%s-%d.%s", basename, i, ext);
    }

    checksum = g_file_resolve_relative_path (dest, checksum_name);
    i++;

    if (g_cancellable_set_error_if_cancelled (cancel, &error)) {
      break;
    }

  } while ((out = g_file_create (checksum, 0, cancel, &error)) == NULL);

  g_free (basename);

  if (out) {
    priv->checksum_file = checksum;

    return G_OUTPUT_STREAM (out);
  } else {
    if (checksum)
      g_object_unref (checksum);

    return NULL;
  }
}
static void
create_custom_desktop_file (NemoMimeApplicationChooser *chooser, gboolean def)
{
    GKeyFile *keyfile = g_key_file_new ();

    g_key_file_set_string (keyfile,
                           G_KEY_FILE_DESKTOP_GROUP,
                           G_KEY_FILE_DESKTOP_KEY_EXEC,
                           g_app_info_get_commandline (chooser->details->custom_info));

    g_key_file_set_string (keyfile,
                           G_KEY_FILE_DESKTOP_GROUP,
                           G_KEY_FILE_DESKTOP_KEY_NAME,
                           g_app_info_get_display_name (chooser->details->custom_info));

    g_key_file_set_string (keyfile,
                           G_KEY_FILE_DESKTOP_GROUP,
                           G_KEY_FILE_DESKTOP_KEY_MIME_TYPE,
                           chooser->details->content_type);

    g_key_file_set_string (keyfile,
                           G_KEY_FILE_DESKTOP_GROUP,
                           G_KEY_FILE_DESKTOP_KEY_TYPE,
                           G_KEY_FILE_DESKTOP_TYPE_APPLICATION);

    gsize size;
    gchar *buffer = g_key_file_to_data (keyfile, &size, NULL);

    gint32 rn = g_random_int_range (0, G_MAXINT32 - 1);
    gchar *fn = g_strdup_printf ("nemo_%s_%d.desktop",
                                 g_app_info_get_display_name (chooser->details->custom_info),
                                 rn);

    gchar *path = g_build_filename (g_get_user_data_dir (), "applications", fn, NULL);

    GFile *outfile = g_file_new_for_path (path);

    g_free (path);

    GFileOutputStream *out;
    gboolean res;

    out = g_file_create (outfile,
                         G_FILE_CREATE_NONE,
                         NULL,
                         NULL);
    if (out) {
        res = g_output_stream_write_all (G_OUTPUT_STREAM (out),
                                         buffer, size,
                                         NULL,
                                         NULL,
                                         NULL);
        if (res) {
            res = g_output_stream_close (G_OUTPUT_STREAM (out),
                                         NULL,
                                         NULL);
            update_mimelist (chooser, fn, def);
        }
        g_object_unref (out);
    }

    g_object_unref (outfile);
    g_free (fn);
    g_free (buffer);
}
Exemple #28
0
static GFile *
filebox_uploader_handle_task_create_file (HevFileboxUploader *self,
			GHashTable *res_htb, const gchar *fp_path, const gchar *fm_path,
			const gchar *filename, const gchar *contents, gsize length)
{
	GFile *file = NULL, *meta = NULL;
	GRegex *regex = NULL;
	GMatchInfo *match_info = NULL;
	gchar *file_name = NULL, *basename = NULL, *file_path = NULL, *meta_path = NULL;
	GFileOutputStream *file_ostream = NULL;

	g_debug ("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	/* fetch filename */
	regex = g_regex_new ("filename=\"(.+)\"", 0, 0, NULL);
	if (g_regex_match (regex, filename, 0, &match_info))
	  file_name = g_match_info_fetch (match_info, 1);
	g_match_info_unref (match_info);
	g_regex_unref (regex);

	/* build file path and meta path */
	basename = g_path_get_basename (file_name);
	g_free (file_name);
	file_path = g_build_filename (fp_path, basename, NULL);
	meta_path = g_build_filename (fm_path, basename, NULL);
	g_free (basename);

	/* new file */
	file = g_file_new_for_path (file_path);
	g_free (file_path);
	if (!file) {
		g_hash_table_insert (res_htb, g_strdup ("Status"),
					g_strdup ("500 Internal Server Error"));
		g_free (meta_path);
		return NULL;
	}

	/* craete file */
	file_ostream = g_file_create (file, G_FILE_CREATE_PRIVATE, NULL, NULL);
	if (!file_ostream) {
		g_hash_table_insert (res_htb, g_strdup ("Status"),
					g_strdup ("403 Forbidden"));
		g_object_unref (file);
		g_free (meta_path);
		return NULL;
	}

	/* write contents to file */
	if (!g_output_stream_write_all (G_OUTPUT_STREAM (file_ostream),
				contents, length, NULL, NULL, NULL)) {
		g_hash_table_insert (res_htb, g_strdup ("Status"),
					g_strdup ("500 Internal Server Error"));
		g_object_unref (file_ostream);
		g_file_delete (file, NULL, NULL);
		g_object_unref (file);
		g_free (meta_path);
		return NULL;
	}

	/* new meta file */
	meta = g_file_new_for_path (meta_path);
	g_free (meta_path);
	if (!meta) {
		g_hash_table_insert (res_htb, g_strdup ("Status"),
					g_strdup ("500 Internal Server Error"));
		g_object_unref (file_ostream);
		g_file_delete (file, NULL, NULL);
		g_object_unref (file);
		return NULL;
	}
	g_object_set_data_full (G_OBJECT (file), "meta", meta,
				(GDestroyNotify) g_object_unref);

	g_object_unref (file_ostream);

	return file;
}
Exemple #29
0
static char *
create_desktop_file (const char *id,
                     const char *name,
                     const char *address,
                     const char *profile_dir,
                     GdkPixbuf  *icon)
{
  GKeyFile *file = NULL;
  char *exec_string;
  char *data = NULL;
  char *filename, *apps_path, *desktop_file_path = NULL;
  char *link_path;
  char *wm_class;
  GFile *link;
  GError *error = NULL;

  g_assert (profile_dir);

  filename = get_app_desktop_filename (id);
  if (!filename)
    return NULL;

  file = g_key_file_new ();
  g_key_file_set_value (file, "Desktop Entry", "Name", name);
  exec_string = g_strdup_printf ("epiphany --application-mode --profile=\"%s\" %s",
                                 profile_dir,
                                 address);
  g_key_file_set_value (file, "Desktop Entry", "Exec", exec_string);
  g_free (exec_string);
  g_key_file_set_value (file, "Desktop Entry", "StartupNotify", "true");
  g_key_file_set_value (file, "Desktop Entry", "Terminal", "false");
  g_key_file_set_value (file, "Desktop Entry", "Type", "Application");
  g_key_file_set_value (file, "Desktop Entry", "Categories", "Network;GNOME;GTK;");

  if (icon) {
    GOutputStream *stream;
    char *path;
    GFile *image;

    path = g_build_filename (profile_dir, EPHY_WEB_APP_ICON_NAME, NULL);
    image = g_file_new_for_path (path);

    stream = (GOutputStream *)g_file_create (image, 0, NULL, NULL);
    gdk_pixbuf_save_to_stream (icon, stream, "png", NULL, NULL, NULL);
    g_key_file_set_value (file, "Desktop Entry", "Icon", path);

    g_object_unref (stream);
    g_object_unref (image);
    g_free (path);
  }

  wm_class = g_strconcat (EPHY_WEB_APP_PROGRAM_NAME_PREFIX, id, NULL);
  g_key_file_set_value (file, "Desktop Entry", "StartupWMClass", wm_class);
  g_free (wm_class);
  data = g_key_file_to_data (file, NULL, NULL);

  desktop_file_path = g_build_filename (profile_dir, filename, NULL);

  if (!g_file_set_contents (desktop_file_path, data, -1, NULL)) {
    g_free (desktop_file_path);
    desktop_file_path = NULL;
  }

  /* Create a symlink in XDG_DATA_DIR/applications for the Shell to
   * pick up this application. */
  apps_path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
  if (ephy_ensure_dir_exists (apps_path, &error)) {
    link_path = g_build_filename (apps_path, filename, NULL);
    link = g_file_new_for_path (link_path);
    g_free (link_path);
    g_file_make_symbolic_link (link, desktop_file_path, NULL, NULL);
    g_object_unref (link);
  } else {
    g_warning ("Error creating application symlink: %s", error->message);
    g_error_free (error);
  }

  g_free (apps_path);
  g_free (filename);
  g_free (data);
  g_key_file_free (file);

  return desktop_file_path;
}
/* Prepare a root filesystem, taking mainly the contents of /usr from yumroot */
static gboolean 
create_rootfs_from_yumroot_content (GFile         *targetroot,
                                    GFile         *yumroot,
                                    JsonObject    *treefile,
                                    GCancellable  *cancellable,
                                    GError       **error)
{
  gboolean ret = FALSE;
  gs_unref_object GFile *kernel_path = NULL;
  gs_unref_object GFile *initramfs_path = NULL;
  gs_unref_hashtable GHashTable *preserve_groups_set = NULL;

  g_print ("Preparing kernel\n");
  if (!do_kernel_prep (yumroot, treefile, cancellable, error))
    goto out;
  
  g_print ("Initializing rootfs\n");
  if (!init_rootfs (targetroot, cancellable, error))
    goto out;

  g_print ("Migrating /etc/passwd to /usr/lib/\n");
  if (!rpmostree_passwd_migrate_except_root (yumroot, RPM_OSTREE_PASSWD_MIGRATE_PASSWD, NULL,
                                             cancellable, error))
    goto out;

  if (json_object_has_member (treefile, "etc-group-members"))
    {
      JsonArray *etc_group_members = json_object_get_array_member (treefile, "etc-group-members");
      preserve_groups_set = _rpmostree_jsonutil_jsarray_strings_to_set (etc_group_members);
    }
      
  g_print ("Migrating /etc/group to /usr/lib/\n");
  if (!rpmostree_passwd_migrate_except_root (yumroot, RPM_OSTREE_PASSWD_MIGRATE_GROUP,
                                             preserve_groups_set,
                                             cancellable, error))
    goto out;

  /* NSS configuration to look at the new files */
  {
    gs_unref_object GFile *yumroot_etc = 
      g_file_resolve_relative_path (yumroot, "etc");

    if (!replace_nsswitch (yumroot_etc, cancellable, error))
      goto out;
  }

  /* We take /usr from the yum content */
  g_print ("Moving /usr to target\n");
  {
    gs_unref_object GFile *usr = g_file_get_child (yumroot, "usr");
    if (!move_to_dir (usr, targetroot, cancellable, error))
      goto out;
  }

  /* Except /usr/local -> ../var/usrlocal */
  g_print ("Linking /usr/local -> ../var/usrlocal\n");
  {
    gs_unref_object GFile *target_usrlocal =
      g_file_resolve_relative_path (targetroot, "usr/local");

    if (!gs_shutil_rm_rf (target_usrlocal, cancellable, error))
      goto out;

    if (!g_file_make_symbolic_link (target_usrlocal, "../var/usrlocal",
                                    cancellable, error))
      goto out;
  }

  /* And now we take the contents of /etc and put them in /usr/etc */
  g_print ("Moving /etc to /usr/etc\n");
  {
    gs_unref_object GFile *yumroot_etc =
      g_file_get_child (yumroot, "etc");
    gs_unref_object GFile *target_usretc =
      g_file_resolve_relative_path (targetroot, "usr/etc");
    
    if (!gs_file_rename (yumroot_etc, target_usretc,
                         cancellable, error))
      goto out;
  }

  if (!migrate_rpm_and_yumdb (targetroot, yumroot, cancellable, error))
    goto out;

  {
    gs_unref_object GFile *yumroot_var = g_file_get_child (yumroot, "var");
    gs_unref_object GFile *rpmostree_tmpfiles_path =
      g_file_resolve_relative_path (targetroot, "usr/lib/tmpfiles.d/rpm-ostree-autovar.conf");
    gs_unref_object GFileOutputStream *tmpfiles_out =
      g_file_create (rpmostree_tmpfiles_path,
                     G_FILE_CREATE_REPLACE_DESTINATION,
                     cancellable, error);

    if (!tmpfiles_out)
      goto out;

    
    if (!convert_var_to_tmpfiles_d ((GOutputStream*)tmpfiles_out, yumroot, yumroot_var,
                                    cancellable, error))
      goto out;

    if (!g_output_stream_close ((GOutputStream*)tmpfiles_out, cancellable, error))
      goto out;
  }

  /* Move boot, but rename the kernel/initramfs to have a checksum */
  g_print ("Moving /boot\n");
  {
    gs_unref_object GFile *yumroot_boot =
      g_file_get_child (yumroot, "boot");
    gs_unref_object GFile *target_boot =
      g_file_get_child (targetroot, "boot");
    gs_unref_object GFile *target_usrlib =
      g_file_resolve_relative_path (targetroot, "usr/lib");
    gs_unref_object GFile *target_usrlib_ostree_boot =
      g_file_resolve_relative_path (target_usrlib, "ostree-boot");
    RpmOstreePostprocessBootLocation boot_location =
      RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH;
    const char *boot_location_str = NULL;
      
    if (!_rpmostree_jsonutil_object_get_optional_string_member (treefile,
                                                                "boot_location",
                                                                &boot_location_str, error))
      goto out;

    if (boot_location_str != NULL)
      {
        if (strcmp (boot_location_str, "legacy") == 0)
          boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_LEGACY;
        else if (strcmp (boot_location_str, "both") == 0)
          boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH;
        else if (strcmp (boot_location_str, "new") == 0)
          boot_location = RPMOSTREE_POSTPROCESS_BOOT_LOCATION_NEW;
        else
          {
            g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                         "Invalid boot location '%s'", boot_location_str);
            goto out;
          }
      }
    
    if (!gs_file_ensure_directory (target_usrlib, TRUE, cancellable, error))
      goto out;

    switch (boot_location)
      {
      case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_LEGACY:
        {
          g_print ("Using boot location: legacy\n");
          if (!gs_file_rename (yumroot_boot, target_boot, cancellable, error))
            goto out;
        }
        break;
      case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_BOTH:
        {
          g_print ("Using boot location: both\n");
          if (!gs_file_rename (yumroot_boot, target_boot, cancellable, error))
            goto out;
          /* Hardlink the existing content, only a little ugly as
           * we'll end up sha256'ing it twice, but oh well. */
          if (!gs_shutil_cp_al_or_fallback (target_boot, target_usrlib_ostree_boot, cancellable, error))
            goto out;
        }
        break;
      case RPMOSTREE_POSTPROCESS_BOOT_LOCATION_NEW:
        {
          g_print ("Using boot location: new\n");
          if (!gs_file_rename (yumroot_boot, target_usrlib_ostree_boot, cancellable, error))
            goto out;
        }
        break;
      }
  }

  /* Also carry along toplevel compat links */
  g_print ("Copying toplevel compat symlinks\n");
  {
    guint i;
    const char *toplevel_links[] = { "lib", "lib64", "lib32",
                                     "bin", "sbin" };
    for (i = 0; i < G_N_ELEMENTS (toplevel_links); i++)
      {
        gs_unref_object GFile *srcpath =
          g_file_get_child (yumroot, toplevel_links[i]);

        if (g_file_query_file_type (srcpath, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL) == G_FILE_TYPE_SYMBOLIC_LINK)
          {
            if (!move_to_dir (srcpath, targetroot, cancellable, error))
              goto out;
          }
      }
  }

  g_print ("Adding tmpfiles-ostree-integration.conf\n");
  {
    gs_unref_object GFile *src_pkglibdir = g_file_new_for_path (PKGLIBDIR);
    gs_unref_object GFile *src_tmpfilesd =
      g_file_get_child (src_pkglibdir, "tmpfiles-ostree-integration.conf");
    gs_unref_object GFile *target_tmpfilesd =
      g_file_resolve_relative_path (targetroot, "usr/lib/tmpfiles.d/tmpfiles-ostree-integration.conf");
    gs_unref_object GFile *target_tmpfilesd_parent = g_file_get_parent (target_tmpfilesd);
    
    if (!gs_file_ensure_directory (target_tmpfilesd_parent, TRUE, cancellable, error))
      goto out;

    if (!g_file_copy (src_tmpfilesd, target_tmpfilesd, 0,
                      cancellable, NULL, NULL, error))
      goto out;
  }

  ret = TRUE;
 out:
  return ret;
}