Exemplo n.º 1
0
bool
ExtractAll (unzFile zip, const char *dir, CanonMode mode)
{
	char *filename, *dirname, *path, *altpath;
	char *canonicalized_filename;
	unz_file_info info;
	int fd;
	
	if (unzGoToFirstFile (zip) != UNZ_OK)
		return false;
	
	do {
		unzGetCurrentFileInfo (zip, &info, NULL, 0, NULL, 0, NULL, 0);
		if (info.external_fa & (1 << 4))
			continue;
		
		if (!(filename = (char *) g_malloc (info.size_filename + 1)))
			return false;
		
		unzGetCurrentFileInfo (zip, NULL, filename, info.size_filename + 1, NULL, 0, NULL, 0);
		
		canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, mode == CanonModeXap);
		
		path = g_build_filename (dir, canonicalized_filename, NULL);
		
		dirname = g_path_get_dirname (path);
		if (g_mkdir_with_parents (dirname, 0700) == -1 && errno != EEXIST) {
			g_free (filename);
			g_free (dirname);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		g_free (dirname);
		
		if ((fd = g_open (path, O_CREAT | O_WRONLY | O_TRUNC, 0600)) == -1) {
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		if (unzOpenCurrentFile (zip) != UNZ_OK) {
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			close (fd);
			return false;
		}
		
		if (!ExtractFile (zip, fd)) {
			unzCloseCurrentFile (zip);
			g_free (filename);
			g_free (canonicalized_filename);
			g_free (path);
			return false;
		}
		
		unzCloseCurrentFile (zip);
		close (fd);

		if (mode == CanonModeXap && is_dll_exe_or_mdb (filename, info.size_filename)) {
			g_free (canonicalized_filename);
			canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, false);
			altpath = g_build_filename (dir, canonicalized_filename, NULL);
			if (strcmp (path, altpath) != 0)
				symlink (path, altpath);
			g_free (altpath);
		}
		
		g_free (filename);
		g_free (canonicalized_filename);
		g_free (path);
	} while (unzGoToNextFile (zip) == UNZ_OK);
	
	return true;
}
Exemplo n.º 2
0
static void
import_mbox_exec (struct _import_mbox_msg *m)
{
	CamelFolder *folder;
	CamelMimeParser *mp = NULL;
	struct stat st;
	int fd;
	CamelMessageInfo *info;

	if (g_stat(m->path, &st) == -1) {
		g_warning("cannot find source file to import '%s': %s", m->path, g_strerror(errno));
		return;
	}

	if (m->uri == NULL || m->uri[0] == 0)
		folder = mail_component_get_folder(NULL, MAIL_COMPONENT_FOLDER_INBOX);
	else
		folder = mail_tool_uri_to_folder(m->uri, CAMEL_STORE_FOLDER_CREATE, &m->base.ex);

	if (folder == NULL)
		return;

	if (S_ISREG(st.st_mode)) {
		CamelOperation *oldcancel = NULL;

		fd = g_open(m->path, O_RDONLY|O_BINARY, 0);
		if (fd == -1) {
			g_warning("cannot find source file to import '%s': %s", m->path, g_strerror(errno));
			goto fail1;
		}

		mp = camel_mime_parser_new();
		camel_mime_parser_scan_from(mp, TRUE);
		if (camel_mime_parser_init_with_fd(mp, fd) == -1) { /* will never happen - 0 is unconditionally returned */
			goto fail2;
		}

		if (m->cancel)
			oldcancel = camel_operation_register(m->cancel);

		camel_operation_start(NULL, _("Importing `%s'"), folder->full_name);
		camel_folder_freeze(folder);
		while (camel_mime_parser_step(mp, NULL, NULL) == CAMEL_MIME_PARSER_STATE_FROM) {
			CamelMimeMessage *msg;
			const char *tmp;
			int pc = 0;
			guint32 flags = 0;

			if (st.st_size > 0)
				pc = (int)(100.0 * ((double)camel_mime_parser_tell(mp) / (double)st.st_size));
			camel_operation_progress(NULL, pc);

			msg = camel_mime_message_new();
			if (camel_mime_part_construct_from_parser((CamelMimePart *)msg, mp) == -1) {
				/* set exception? */
				camel_object_unref(msg);
				break;
			}

			info = camel_message_info_new(NULL);

			tmp = camel_medium_get_header((CamelMedium *)msg, "X-Mozilla-Status");
			if (tmp)
				flags |= decode_mozilla_status(tmp);
			tmp = camel_medium_get_header((CamelMedium *)msg, "Status");
			if (tmp)
				flags |= decode_status(tmp);
			tmp = camel_medium_get_header((CamelMedium *)msg, "X-Status");
			if (tmp)
				flags |= decode_status(tmp);

			camel_message_info_set_flags(info, flags, ~0);
			camel_folder_append_message(folder, msg, info, NULL, &m->base.ex);
			camel_message_info_free(info);
			camel_object_unref(msg);

			if (camel_exception_is_set(&m->base.ex))
				break;

			camel_mime_parser_step(mp, NULL, NULL);
		}
		camel_folder_sync(folder, FALSE, NULL);
		camel_folder_thaw(folder);
		camel_operation_end(NULL);
		/* TODO: these api's are a bit weird, registering the old is the same as deregistering */
		if (m->cancel)
			camel_operation_register(oldcancel);
	fail2:
		camel_object_unref(mp);
	}
fail1:
	camel_folder_sync(folder, FALSE, NULL);
	camel_object_unref(folder);
}
Exemplo n.º 3
0
/*! @brief Locks a group
 * 
 * Tries to acquire a lock for the given group.
 * 
 * If the lock was successfully acquired, OSYNC_LOCK_OK will
 * be returned.
 * 
 * If the lock was acquired, but a old lock file was detected,
 * OSYNC_LOCK_STALE will be returned. Use this to detect if the
 * last sync of this group was successful, or if this something crashed.
 * If you get this answer you should perform a slow-sync
 * 
 * If the group is locked, OSYNC_LOCKED is returned
 * 
 * @param group The group
 * @returns if the lockfile was acquired
 * 
 */
OSyncLockState osync_group_lock(OSyncGroup *group)
{
  char *lockfile = NULL;
  osync_bool exists = FALSE;
  osync_bool locked = FALSE;
	
  osync_trace(TRACE_ENTRY, "%s(%p)", __func__, group);
  osync_assert(group);
	
  if (!group->configdir) {
    osync_trace(TRACE_EXIT, "%s: OSYNC_LOCK_OK: No configdir", __func__);
    return OSYNC_LOCK_OK;
  }
	
  if (group->lock_fd) {
    osync_trace(TRACE_EXIT, "%s: OSYNC_LOCKED, lock_fd existed", __func__);
    return OSYNC_LOCKED;
  }
	
  lockfile = g_strdup_printf("%s%clock", group->configdir, G_DIR_SEPARATOR);

  if (g_file_test(lockfile, G_FILE_TEST_EXISTS)) {
    osync_trace(TRACE_INTERNAL, "locking group: file exists");
    exists = TRUE;
  }

  if ((group->lock_fd = g_open(lockfile, O_CREAT | O_WRONLY, 00700)) == -1) {
    group->lock_fd = 0;
    g_free(lockfile);
    osync_trace(TRACE_EXIT, "%s: Unable to open: %s", __func__, g_strerror(errno));
    return OSYNC_LOCK_STALE;
  } else {
#ifndef _WIN32
    /* Set FD_CLOEXEC flags for the lock file descriptor. We don't want the
     * subprocesses created by plugins or the engine to keep holding the lock
     */
    int oldflags = fcntl(group->lock_fd, F_GETFD);
    if (oldflags == -1) {
      osync_trace(TRACE_EXIT_ERROR, "%s: %s", __func__, "Unable to get fd flags");
      return OSYNC_LOCK_STALE;
    }

    if (fcntl(group->lock_fd, F_SETFD, oldflags|FD_CLOEXEC) == -1) {
      osync_trace(TRACE_EXIT_ERROR, "%s: %s", __func__, "Unable to set fd flags");
      return OSYNC_LOCK_STALE;
    }

    if (flock(group->lock_fd, LOCK_EX | LOCK_NB) == -1) {
      if (errno == EWOULDBLOCK) {
        osync_trace(TRACE_INTERNAL, "locking group: is locked2");
        locked = TRUE;
        close(group->lock_fd);
        group->lock_fd = 0;
      } else
        osync_trace(TRACE_INTERNAL, "error setting lock: %s", g_strerror(errno));
    } else
#else /* _WIN32 */
      /* Windows cannot delete files which are open. When doing the backup, the lock file */
      /* would be open */
      close(group->lock_fd); 
#endif
    osync_trace(TRACE_INTERNAL, "Successfully locked");
  } /* g_open */
	
  g_free(lockfile);
	
  if (exists) {
    if (locked) {
      osync_trace(TRACE_EXIT, "%s: OSYNC_LOCKED", __func__);
      return OSYNC_LOCKED;
    } else {
      osync_trace(TRACE_EXIT, "%s: OSYNC_LOCK_STALE", __func__);
      return OSYNC_LOCK_STALE;
    }
  }
	
  osync_trace(TRACE_EXIT, "%s: OSYNC_LOCK_OK", __func__);
  return OSYNC_LOCK_OK;
}
Exemplo n.º 4
0
static GConfSource*  
resolve_address (const gchar* address, GError** err)
{
  struct stat statbuf;
  gchar* root_dir;
  XMLSource* xsource;
  GConfSource* source;
  gint flags = 0;
  GConfLock* lock = NULL;
  guint dir_mode = 0700;
  guint file_mode = 0600;
  gchar** address_flags;
  gchar** iter;
  gboolean force_readonly;
  
  root_dir = get_dir_from_address (address, err);
  if (root_dir == NULL)
    return NULL;

  if (g_stat (root_dir, &statbuf) == 0)
    {
      /* Already exists, base our dir_mode on it */
      dir_mode = _gconf_mode_t_to_mode (statbuf.st_mode);

      /* dir_mode without search bits */
      file_mode = dir_mode & (~0111); 
    }
  else if (g_mkdir (root_dir, dir_mode) < 0)
    {
      /* Error out even on EEXIST - shouldn't happen anyway */
      gconf_set_error (err, GCONF_ERROR_FAILED,
		       _("Could not make directory `%s': %s"),
		      (gchar *)root_dir, g_strerror (errno));
      g_free (root_dir);
      return NULL;
    }

  force_readonly = FALSE;
  
  address_flags = gconf_address_flags (address);  
  if (address_flags)
    {
      iter = address_flags;
      while (*iter)
        {
          if (strcmp (*iter, "readonly") == 0)
            {
              force_readonly = TRUE;
              break;
            }

          ++iter;
        }
    }

  g_strfreev (address_flags);

  {
    /* See if we're writable */
    gboolean writable;
    int fd;
    gchar* testfile;

    writable = FALSE;
    
    if (!force_readonly)
      {
        testfile = g_strconcat(root_dir, "/.testing.writeability", NULL);    
        
        fd = g_open(testfile, O_CREAT|O_WRONLY, S_IRWXU);
        
        if (fd >= 0)
          {
            writable = TRUE;
            close(fd);
          }
        
        g_unlink(testfile);
        
        g_free(testfile);
      }
    
    if (writable)
      flags |= GCONF_SOURCE_ALL_WRITEABLE;

    /* We only do locking if it's writable,
     * and if not using local locks,
     * which is sort of broken but close enough
     */
    if (writable && !gconf_use_local_locks ())
      {
        gchar* lockdir;

        lockdir = get_lock_dir_from_root_dir (root_dir);
        
        lock = gconf_get_lock(lockdir, err);

        if (lock != NULL)
          gconf_log(GCL_DEBUG, "Acquired lock directory `%s'", lockdir);
        
        g_free(lockdir);
        
        if (lock == NULL)
          {
            g_free(root_dir);
            return NULL;
          }
      }
  }

  {
    /* see if we're readable */
    gboolean readable = FALSE;
    GDir* d;

    d = g_dir_open(root_dir, 0, NULL);

    if (d != NULL)
      {
        readable = TRUE;
        g_dir_close(d);
      }
    
    if (readable)
      flags |= GCONF_SOURCE_ALL_READABLE;
  }

  if (!(flags & GCONF_SOURCE_ALL_READABLE) &&
      !(flags & GCONF_SOURCE_ALL_WRITEABLE))
    {
      gconf_set_error(err, GCONF_ERROR_BAD_ADDRESS, _("Can't read from or write to the XML root directory in the address \"%s\""), address);
      g_free(root_dir);
      return NULL;
    }  
  
  /* Create the new source */

  xsource = xs_new(root_dir, dir_mode, file_mode, lock);

  gconf_log(GCL_DEBUG,
            _("Directory/file permissions for XML source at root %s are: %o/%o"),
            root_dir, dir_mode, file_mode);
  
  source = (GConfSource*)xsource;

  source->flags = flags;
  
  g_free(root_dir);
  
  return source;
}
Exemplo n.º 5
0
Arquivo: text.c Projeto: TheX/hexchat
static void
scrollback_shrink (session *sess)
{
	char *file;
	char *buf;
	int fh;
	int lines;
	int line;
	gsize len;
	char *p;

	scrollback_close (sess);
	sess->scrollwritten = 0;
	lines = 0;

	if ((file = scrollback_get_filename (sess)) == NULL)
	{
		g_free (file);
		return;
	}

	if (!g_file_get_contents (file, &buf, &len, NULL))
	{
		g_free (file);
		return;
	}

	/* count all lines */
	p = buf;
	while (p != buf + len)
	{
		if (*p == '\n')
			lines++;
		p++;
	}

	fh = g_open (file, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0644);
	g_free (file);
	if (fh == -1)
	{
		free (buf);
		return;
	}

	line = 0;
	p = buf;
	while (p != buf + len)
	{
		if (*p == '\n')
		{
			line++;
			if (line >= lines - prefs.hex_text_max_lines &&
				 p + 1 != buf + len)
			{
				p++;
				write (fh, p, len - (p - buf));
				break;
			}
		}
		p++;
	}

	close (fh);
	free (buf);
}
Exemplo n.º 6
0
/*!
 \brief main() is the typical main function in a C program, it performs
 all core initialization, loading of all main parameters, initializing handlers
 and entering gtk_main to process events until program close
 \param argc (gint) count of command line arguments
 \param argv (char **) array of command line args
 \returns TRUE
 */
gint main(gint argc, gchar ** argv)
{
	gint port_fd = 0;
	gint file_fd = 0;
	
	verify_args(argc, argv);

	output(g_strdup_printf("MegaTunix msloader %s\n",VERSION),TRUE);

	/* If we got this far, all is good argument wise */
	if (!lock_port(argv[2]))
	{
		output((gchar *)"Could NOT LOCK Serial Port\nCheck for already running serial apps using the port\n",FALSE);
		exit(-1);
	}

	port_fd = open_port(argv[2]);
	if (port_fd > 0)
		output((gchar *)"Port successfully opened\n",FALSE);
	else
	{
		output((gchar *)"Could NOT open Port check permissions\n",FALSE);
		unlock_port();
		exit(-1);
	}
#ifdef __WIN32__
	file_fd = open(argv[3], O_RDWR | O_BINARY );
#else
	file_fd = g_open(argv[3],O_RDONLY,S_IRUSR);
#endif
	if (file_fd > 0 )
		output((gchar *)"Firmware file successfully opened\n",FALSE);
	else
	{
		output((gchar *)"Could NOT open firmware file, check permissions/paths\n",FALSE);
		close_port(port_fd);
		unlock_port();
		exit(-1);
	}
	if (type == MS1)
	{
		setup_port(port_fd, 9600);
		do_ms1_load(port_fd,file_fd);
	}
	else if (type == MS2)
	{
		setup_port(port_fd,115200);
		do_ms2_load(port_fd,file_fd);
	}

	else if (type == FREEEMS)
	{
		setup_port(port_fd,115200);
		do_freeems_load(port_fd,file_fd);
	}

	flush_serial(port_fd,BOTH);
	close_port(port_fd);
	unlock_port();
	return (0) ;
}
Exemplo n.º 7
0
/**
 * link_init:
 * @thread_safe: if we want thread safety enabled.
 * 
 * Initialize linc.
 **/
void
link_init (gboolean thread_safe)
{
#if defined (CONNECTION_DEBUG) && defined (CONNECTION_DEBUG_FLAG)
	if (getenv ("LINK_CONNECTION_DEBUG"))
		link_connection_debug_flag = TRUE;
	if (link_connection_debug_flag &&
	    getenv ("LINK_PER_PROCESS_STDERR") &&
	    fileno (stderr) >= 0) {
		char *stderr_file = g_build_filename (g_get_tmp_dir (),
						      g_strdup_printf ("link_debug.%d", getpid ()),
						      NULL);
		int fd;
		fd = g_open (stderr_file, O_WRONLY|O_CREAT, 0666);
		if (fd >= 0) {
			char *prgname = g_get_prgname ();
			d_printf ("Redirecting stderr of %s to %s\n",
				  (prgname ? prgname : "this process"), stderr_file);
			dup2 (fd, fileno (stderr));
			close (fd);
		}
	        d_printf ("stderr redirected here\n");
	}
#endif

	if (thread_safe && !g_thread_supported ())
		g_thread_init (NULL);

	link_is_thread_safe = (thread_safe && g_thread_supported());

	g_type_init ();

#ifdef SIGPIPE
	/*
	 * Link's raison d'etre is for ORBit2 and Bonobo
	 *
	 * In Bonobo, components and containers must not crash if the
	 * remote end crashes.  If a remote server crashes and then we
	 * try to make a CORBA call on it, we may get a SIGPIPE.  So,
	 * for lack of a better solution, we ignore SIGPIPE here.  This
	 * is open for reconsideration in the future.
	 *
	 * When SIGPIPE is ignored, write() calls which would
	 * ordinarily trigger a signal will instead return -1 and set
	 * errno to EPIPE.  So linc will be able to catch these
	 * errors instead of letting them kill the component.
	 *
	 * Possibilities are the MSG_PEEK trick, where you test if the
	 * connection is dead right before doing the writev().  That
	 * approach has two problems:
	 *
	 *   1. There is the possibility of a race condition, where
	 *      the remote end calls right after the test, and right
	 *      before the writev().
	 * 
	 *   2. An extra system call per write might be regarded by
	 *      some as a performance hit.
	 *
	 * Another possibility is to surround the call to writev() in
	 * link_connection_writev (linc-connection.c) with something like
	 * this:
	 *
	 *		link_ignore_sigpipe = 1;
	 *
	 *		result = writev ( ... );
	 *
	 *		link_ignore_sigpipe = 0;
	 *
	 * The SIGPIPE signal handler will check the global
	 * link_ignore_sigpipe variable and ignore the signal if it
	 * is 1.  If it is 0, it can proxy to the user's original
	 * signal handler.  This is a real possibility.
	 */
	signal (SIGPIPE, SIG_IGN);
#endif
	
	link_context = g_main_context_new ();
	link_loop    = g_main_loop_new (link_context, TRUE);
	
#ifdef LINK_SSL_SUPPORT
	SSLeay_add_ssl_algorithms ();
	link_ssl_method = SSLv23_method ();
	link_ssl_ctx = SSL_CTX_new (link_ssl_method);
#endif

	link_main_lock = link_mutex_new ();
	link_cmd_queue_lock = link_mutex_new ();
	if (link_is_thread_safe) {
		link_main_cond = g_cond_new ();
		link_cmd_queue_cond = g_cond_new ();
	}

#ifdef HAVE_WINSOCK2_H
	{
		WSADATA wsadata;
		if (WSAStartup (MAKEWORD (2, 0), &wsadata) != 0)
			g_error ("Windows Sockets could not be initialized");
	}
#endif
}
Exemplo n.º 8
0
int nand_read(struct cmd_param *params)
{
	struct chip_param_io chip_params;
	int fd = -1, out_fd = -1, done = 0, ret = 0;
	char *dev, *out;
	int pos, count, mult, block_size;
	uint8_t *buf = NULL;

	if (!(dev = param_get_string(params, "dev"))) {
		fprintf(stderr, "You must specify 'dev' parameter\n");
		return (1);
	}

	if ((out = param_get_string(params, "out"))) {
		out_fd = open(out, O_WRONLY|O_CREAT);
		if (out_fd == -1) {
			perrorf("Cannot open %s for writing", out);
			return (1);
		}
	}

	if ((fd = g_open(dev, 1)) == -1) {
		perrorf("Cannot open %s", dev);
		ret = 1;
		goto out;
	}

	if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) == -1) {
		perrorf("Cannot ioctl(NAND_IO_GET_CHIP_PARAM)");
		ret = 1;
		goto out;
	}

	block_size = chip_params.page_size * chip_params.pages_per_block;

	if (param_has_value(params, "page")) {
		pos = chip_params.page_size * param_get_int(params, "page");
		mult = chip_params.page_size;
	} else if (param_has_value(params, "block")) {
		pos = block_size * param_get_int(params, "block");
		mult = block_size;
	} else if (param_has_value(params, "pos")) {
		pos = param_get_int(params, "pos");
		mult = 1;
		if (pos % chip_params.page_size) {
			fprintf(stderr, "Position must be page-size aligned!\n");
			ret = 1;
			goto out;
		}
	} else {
		fprintf(stderr, "You must specify one of: 'block', 'page',"
		    "'pos' arguments\n");
		ret = 1;
		goto out;
	}

	if (!(param_has_value(params, "count")))
		count = mult;
	else
		count = param_get_int(params, "count") * mult;

	if (!(buf = malloc(chip_params.page_size))) {
		perrorf("Cannot allocate buffer [size %x]",
		    chip_params.page_size);
		ret = 1;
		goto out;
	}

	lseek(fd, pos, SEEK_SET);

	while (done < count) {
		if ((ret = read(fd, buf, chip_params.page_size)) !=
		    (int32_t)chip_params.page_size) {
			perrorf("read error (read %d bytes)", ret);
			goto out;
		}

		if (out_fd != -1) {
			done += ret;
			if ((ret = write(out_fd, buf, chip_params.page_size)) !=
			    (int32_t)chip_params.page_size) {
				perrorf("write error (written %d bytes)", ret);
				ret = 1;
				goto out;
			}
		} else {
			hexdumpoffset(buf, chip_params.page_size, done);
			done += ret;
		}
	}

out:
	g_close(fd);
	if (out_fd != -1)
		close(out_fd);
	if (buf)
		free(buf);

	return (ret);
}
Exemplo n.º 9
0
//FIXME: nuke this!
char *
Application::GetResourceAsPath (const Uri *resourceBase, const Uri *uri)
{
	const char *filename;
	char *dirname, *path;
	char *canonicalized_filename;
	ManagedStreamCallbacks stream;
	unzFile zipfile;
	struct stat st;
	char buf[4096];
	int nread;
	int fd;
	
	if (!get_resource_cb || !uri || uri->IsAbsolute ())
		return NULL;
	
	// construct the path name for this resource
	filename = uri->ToString ();
	canonicalized_filename = Deployment::GetCurrent ()->CanonicalizeFileName (filename, false);
	
	path = g_build_filename (GetResourceRoot(), canonicalized_filename, NULL);
	g_free (canonicalized_filename);
	
	if (g_stat (path, &st) != -1) {
		// path exists, we're done
		return path;
	}
	
	// create the directory for our resource (keeping the relative path intact)
	dirname = g_path_get_dirname (path);
	if (g_mkdir_with_parents (dirname, 0700) == -1 && errno != EEXIST) {
		g_free (dirname);
		g_free (path);
		return NULL;
	}
	
	g_free (dirname);
	
	stream = get_resource_cb (resourceBase, uri);
	
	if (!stream.handle) {
		g_free (path);
		return NULL;
	}
	
	// reset the stream to 0
	if (stream.CanSeek (stream.handle))
		stream.Seek (stream.handle, 0, SEEK_SET);
	
	// create and save the buffer to disk
	if ((fd = g_open (path, O_WRONLY | O_CREAT | O_EXCL, 0600)) == -1) {
		stream.Close (stream.handle);
		g_free (path);
		return NULL;
	}
	
	// write the stream to disk
	do {
		if ((nread = stream.Read (stream.handle, buf, 0, sizeof (buf))) <= 0)
			break;
		
		if (write_all (fd, buf, (size_t) nread) == -1) {
			stream.Close (stream.handle);
			g_unlink (path);
			g_free (path);
			close (fd);
			
			return NULL;
		}
	} while (true);
	
	stream.Close (stream.handle);
	close (fd);
	
	// check to see if the resource is zipped
	if (!(zipfile = unzOpen (path))) {
		// nope, not zipped...
		return path;
	}
	
	// create a directory to contain our unzipped content
	if (!(dirname = CreateTempDir (path))) {
		unzClose (zipfile);
		g_free (dirname);
		g_unlink (path);
		g_free (path);
		return NULL;
	}
	
	// unzip the contents
	if (!ExtractAll (zipfile, dirname, CanonModeResource)) {
		RemoveDir (dirname);
		unzClose (zipfile);
		g_free (dirname);
		g_unlink (path);
		g_free (path);
		return NULL;
	}
	
	unzClose (zipfile);
	g_unlink (path);
	
	if (g_rename (dirname, path) == -1) {
		RemoveDir (dirname);
		g_free (dirname);
		g_free (path);
		return NULL;
	}
	
	g_free (dirname);
	
	return path;
}
Exemplo n.º 10
0
GFileOutputStream *
_g_local_file_output_stream_replace (const char        *filename,
				     gboolean          readable,
				     const char        *etag,
				     gboolean           create_backup,
				     GFileCreateFlags   flags,
                                     GFileInfo         *reference_info,
				     GCancellable      *cancellable,
				     GError           **error)
{
  GLocalFileOutputStream *stream;
  int mode;
  int fd;
  char *temp_file;
  gboolean sync_on_close;
  int open_flags;

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

  temp_file = NULL;

  mode = mode_from_flags_or_info (flags, reference_info);
  sync_on_close = FALSE;

  /* If the file doesn't exist, create it */
  open_flags = O_CREAT | O_EXCL | O_BINARY;
  if (readable)
    open_flags |= O_RDWR;
  else
    open_flags |= O_WRONLY;
  fd = g_open (filename, open_flags, mode);

  if (fd == -1 && errno == EEXIST)
    {
      /* The file already exists */
      fd = handle_overwrite_open (filename, readable, etag,
                                  create_backup, &temp_file,
                                  flags, reference_info,
                                  cancellable, error);
      if (fd == -1)
	return NULL;

      /* If the final destination exists, we want to sync the newly written
       * file to ensure the data is on disk when we rename over the destination.
       * otherwise if we get a system crash we can lose both the new and the
       * old file on some filesystems. (I.E. those that don't guarantee the
       * data is written to the disk before the metadata.)
       */
      sync_on_close = TRUE;
    }
  else if (fd == -1)
    {
      set_error_from_open_errno (filename, error);
      return NULL;
    }
  
 
  stream = g_object_new (G_TYPE_LOCAL_FILE_OUTPUT_STREAM, NULL);
  stream->priv->fd = fd;
  stream->priv->sync_on_close = sync_on_close;
  stream->priv->tmp_filename = temp_file;
  if (create_backup)
    stream->priv->backup_filename = create_backup_filename (filename);
  stream->priv->original_filename =  g_strdup (filename);
  
  return G_FILE_OUTPUT_STREAM (stream);
}
Exemplo n.º 11
0
static int
handle_overwrite_open (const char    *filename,
		       gboolean       readable,
		       const char    *etag,
		       gboolean       create_backup,
		       char         **temp_filename,
		       GFileCreateFlags flags,
                       GFileInfo       *reference_info,
		       GCancellable  *cancellable,
		       GError       **error)
{
  int fd = -1;
  GLocalFileStat original_stat;
  char *current_etag;
  gboolean is_symlink;
  int open_flags;
  int res;
  int mode;

  mode = mode_from_flags_or_info (flags, reference_info);

  /* We only need read access to the original file if we are creating a backup.
   * We also add O_CREATE to avoid a race if the file was just removed */
  if (create_backup || readable)
    open_flags = O_RDWR | O_CREAT | O_BINARY;
  else
    open_flags = O_WRONLY | O_CREAT | O_BINARY;
  
  /* Some systems have O_NOFOLLOW, which lets us avoid some races
   * when finding out if the file we opened was a symlink */
#ifdef O_NOFOLLOW
  is_symlink = FALSE;
  fd = g_open (filename, open_flags | O_NOFOLLOW, mode);
  if (fd == -1 && errno == ELOOP)
    {
      /* Could be a symlink, or it could be a regular ELOOP error,
       * but then the next open will fail too. */
      is_symlink = TRUE;
      fd = g_open (filename, open_flags, mode);
    }
#else
  fd = g_open (filename, open_flags, mode);
  /* This is racy, but we do it as soon as possible to minimize the race */
  is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
#endif
    
  if (fd == -1)
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error opening file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      return -1;
    }
  
#ifdef G_OS_WIN32
  res = _fstati64 (fd, &original_stat);
#else
  res = fstat (fd, &original_stat);
#endif

  if (res != 0) 
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error when getting information for file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      goto err_out;
    }
  
  /* not a regular file */
  if (!S_ISREG (original_stat.st_mode))
    {
      if (S_ISDIR (original_stat.st_mode))
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_IS_DIRECTORY,
                             _("Target file is a directory"));
      else
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_NOT_REGULAR_FILE,
                             _("Target file is not a regular file"));
      goto err_out;
    }
  
  if (etag != NULL)
    {
      current_etag = _g_local_file_info_create_etag (&original_stat);
      if (strcmp (etag, current_etag) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_WRONG_ETAG,
                               _("The file was externally modified"));
	  g_free (current_etag);
	  goto err_out;
	}
      g_free (current_etag);
    }

  /* We use two backup strategies.
   * The first one (which is faster) consist in saving to a
   * tmp file then rename the original file to the backup and the
   * tmp file to the original name. This is fast but doesn't work
   * when the file is a link (hard or symbolic) or when we can't
   * write to the current dir or can't set the permissions on the
   * new file. 
   * The second strategy consist simply in copying the old file
   * to a backup file and rewrite the contents of the file.
   */
  
  if ((flags & G_FILE_CREATE_REPLACE_DESTINATION) ||
      (!(original_stat.st_nlink > 1) && !is_symlink))
    {
      char *dirname, *tmp_filename;
      int tmpfd;
      
      dirname = g_path_get_dirname (filename);
      tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
      g_free (dirname);

      tmpfd = g_mkstemp_full (tmp_filename, (readable ? O_RDWR : O_WRONLY) | O_BINARY, mode);
      if (tmpfd == -1)
	{
	  g_free (tmp_filename);
	  goto fallback_strategy;
	}
      
      /* try to keep permissions (unless replacing) */

      if ( ! (flags & G_FILE_CREATE_REPLACE_DESTINATION) &&
	   (
#ifdef HAVE_FCHOWN
	    fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
#endif
#ifdef HAVE_FCHMOD
	    fchmod (tmpfd, original_stat.st_mode) == -1 ||
#endif
	    0
	    )
	  )
	{
          GLocalFileStat tmp_statbuf;
          int tres;

#ifdef G_OS_WIN32
          tres = _fstati64 (tmpfd, &tmp_statbuf);
#else
          tres = fstat (tmpfd, &tmp_statbuf);
#endif
	  /* Check that we really needed to change something */
	  if (tres != 0 ||
	      original_stat.st_uid != tmp_statbuf.st_uid ||
	      original_stat.st_gid != tmp_statbuf.st_gid ||
	      original_stat.st_mode != tmp_statbuf.st_mode)
	    {
	      g_close (tmpfd, NULL);
	      g_unlink (tmp_filename);
	      g_free (tmp_filename);
	      goto fallback_strategy;
	    }
	}

      g_close (fd, NULL);
      *temp_filename = tmp_filename;
      return tmpfd;
    }

 fallback_strategy:

  if (create_backup)
    {
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      struct stat tmp_statbuf;      
#endif
      char *backup_filename;
      int bfd;
      
      backup_filename = create_backup_filename (filename);

      if (g_unlink (backup_filename) == -1 && errno != ENOENT)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      bfd = g_open (backup_filename,
		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
		    original_stat.st_mode & 0777);

      if (bfd == -1)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      /* If needed, Try to set the group of the backup same as the
       * original file. If this fails, set the protection
       * bits for the group same as the protection bits for
       * others. */
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      if (fstat (bfd, &tmp_statbuf) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
	  g_close (bfd, NULL);
	  g_free (backup_filename);
	  goto err_out;
	}
      
      if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
	  fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
	{
	  if (fchmod (bfd,
		      (original_stat.st_mode & 0707) |
		      ((original_stat.st_mode & 07) << 3)) != 0)
	    {
	      g_set_error_literal (error,
                                   G_IO_ERROR,
                                   G_IO_ERROR_CANT_CREATE_BACKUP,
                                   _("Backup file creation failed"));
	      g_unlink (backup_filename);
	      g_close (bfd, NULL);
	      g_free (backup_filename);
	      goto err_out;
	    }
	}
#endif

      if (!copy_file_data (fd, bfd, NULL))
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
          g_close (bfd, NULL);
	  g_free (backup_filename);
	  
	  goto err_out;
	}
      
      g_close (bfd, NULL);
      g_free (backup_filename);

      /* Seek back to the start of the file after the backup copy */
      if (lseek (fd, 0, SEEK_SET) == -1)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error seeking in file: %s"),
		       g_strerror (errsv));
	  goto err_out;
	}
    }

  if (flags & G_FILE_CREATE_REPLACE_DESTINATION)
    {
      g_close (fd, NULL);
      
      if (g_unlink (filename) != 0)
	{
	  int errsv = errno;
	  
	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error removing old file: %s"),
		       g_strerror (errsv));
	  goto err_out2;
	}

      if (readable)
	open_flags = O_RDWR | O_CREAT | O_BINARY;
      else
	open_flags = O_WRONLY | O_CREAT | O_BINARY;
      fd = g_open (filename, open_flags, mode);
      if (fd == -1)
	{
	  int errsv = errno;
	  char *display_name = g_filename_display_name (filename);
	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error opening file '%s': %s"),
		       display_name, g_strerror (errsv));
	  g_free (display_name);
	  goto err_out2;
	}
    }
  else
    {
      /* Truncate the file at the start */
#ifdef G_OS_WIN32
      if (g_win32_ftruncate (fd, 0) == -1)
#else
	if (ftruncate (fd, 0) == -1)
#endif
	  {
	    int errsv = errno;
	    
	    g_set_error (error, G_IO_ERROR,
			 g_io_error_from_errno (errsv),
			 _("Error truncating file: %s"),
			 g_strerror (errsv));
	    goto err_out;
	  }
    }
    
  return fd;

 err_out:
  g_close (fd, NULL);
 err_out2:
  return -1;
}
Exemplo n.º 12
0
void filesystem::g_open_tempmem(service_ptr_t<file> & p_out,abort_callback & p_abort) {
	g_open(p_out,"tempmem://",open_mode_write_new,p_abort);
}
Exemplo n.º 13
0
void filesystem::g_open_write_new(service_ptr_t<file> & p_out,const char * p_path,abort_callback & p_abort) {
	g_open(p_out,p_path,open_mode_write_new,p_abort);
}
Exemplo n.º 14
0
void filesystem::g_open_timeout(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort) {
	FB2K_RETRY_ON_SHARING_VIOLATION( g_open(p_out, p_path, p_mode, p_abort), p_abort, p_timeout);
}
Exemplo n.º 15
0
Arquivo: dia_xml.c Projeto: UIKit0/dia
/*!
 * \brief Fallback implementation for not well-formed diagram files
 *
 * If all files produced by dia were good XML files, we wouldn't have to do 
 *  this little gymnastic. Alas, during the libxml1 days, we were outputting 
 *  files with no encoding specification (which means UTF-8 if we're in an
 *  asciish encoding) and strings encoded in local charset (so, we wrote
 *  broken files). 
 *
 *  The following logic finds if we have a broken file, and attempts to fix 
 *  it if it's possible. If the file is correct or is unrecognisable, we pass
 *  it untouched to libxml2.
 * @param filename The name of the file to check.
 * @param default_enc The default encoding to use if none is given.
 * @param ctx The context in which this function is called
 * @return The filename given if it seems ok, or the name of a new file
 *          with fixed contents, or NULL if we couldn't read the file.  The
 *          caller should free this string and unlink the file if it is not
 *          the same as `filename'.
 * @bug The many gzclose-g_free-return sequences should be refactored into
 *       an "exception handle" (goto+label). At least for people who think goto is
 *       better than this. I dont. --hb
 * \ingroup DiagramXmlIo
 */
static const gchar *
xml_file_check_encoding(const gchar *filename, const gchar *default_enc, DiaContext *ctx)
{
  int fd = g_open (filename, O_RDONLY, 0);
  /* If the next call exits the program (without any message) check if
   * you are loading an incompatible version of zlib*.dll, e.g. one
   * built against a newer version of msvcrt*.dll
   */
  gzFile zf = gzdopen(fd,"rb");  
  gchar *buf;
  gchar *p,*pmax;
  int len;
  gchar *tmp,*res;
  int uf;
  gboolean well_formed_utf8;
  int write_ok;

  static char magic_xml[] = 
  {0x3c,0x3f,0x78,0x6d,0x6c,0x00}; /* "<?xml" in ASCII */

  if (!zf) {
    dia_log_message("%s can not be opened for encoding check (%s)", filename, fd > 0 ? "gzdopen" : "g_open");
    /* XXX perhaps we can just chicken out to libxml ? -- CC */
    return filename;
  }
  p = buf = g_malloc0(BUFLEN);  
  len = gzread(zf,buf,BUFLEN);
  pmax = p + len;

  /* first, we expect the magic <?xml string */
  if ((0 != strncmp(p,magic_xml,5)) || (len < 5)) {
    gzclose(zf);
    g_free(buf);
    return filename; /* let libxml figure out what this is. */
  }
  /* now, we're sure we have some asciish XML file. */
  p += 5;
  while (((*p == 0x20)||(*p == 0x09)||(*p == 0x0d)||(*p == 0x0a))
         && (p<pmax)) p++;
  if (p>=pmax) { /* whoops ? */
    gzclose(zf);
    g_free(buf);
    return filename;
  }
  if (0 != strncmp(p,"version=\"",9)) {
    gzclose(zf); /* chicken out. */
    g_free(buf);
    return filename;
  }
  p += 9;
  /* The header is rather well formed. */
  if (p>=pmax) { /* whoops ? */
    gzclose(zf);
    g_free(buf);
    return filename;
  }
  while ((*p != '"') && (p < pmax)) p++;
  p++;
  while (((*p == 0x20)||(*p == 0x09)||(*p == 0x0d)||(*p == 0x0a))
         && (p<pmax)) p++;
  if (p>=pmax) { /* whoops ? */
    gzclose(zf);
    g_free(buf);
    return filename;
  }
  if (0 == strncmp(p,"encoding=\"",10)) {
    gzclose(zf); /* this file has an encoding string. Good. */
    g_free(buf);
    return filename;
  }
  /* now let's read the whole file, to see if there are offending bits.
   * We can call it well formed UTF-8 if the highest isn't used
   */
  well_formed_utf8 = TRUE;
  do {
    int i;
    for (i = 0; i < len; i++)
      if (buf[i] & 0x80 || buf[i] == '&')
        well_formed_utf8 = FALSE;
    len = gzread(zf,buf,BUFLEN);
  } while (len > 0 && well_formed_utf8);
  if (well_formed_utf8) {
    gzclose(zf); /* this file is utf-8 compatible  */
    g_free(buf);
    return filename;
  } else {
    gzclose(zf); /* poor man's fseek */
    fd = g_open (filename, O_RDONLY, 0);
    zf = gzdopen(fd,"rb"); 
    len = gzread(zf,buf,BUFLEN);
  }

  if (0 != strcmp(default_enc,"UTF-8")) {
    dia_context_add_message (ctx, 
                             _("The file %s has no encoding specification;\n"
			     "assuming it is encoded in %s"),
			     dia_context_get_filename(ctx), default_enc);
  } else {
    gzclose(zf); /* we apply the standard here. */
    g_free(buf);
    return filename;
  }

  tmp = getenv("TMP"); 
  if (!tmp) tmp = getenv("TEMP");
  if (!tmp) tmp = "/tmp";

  res = g_strconcat(tmp,G_DIR_SEPARATOR_S,"dia-xml-fix-encodingXXXXXX",NULL);
  uf = g_mkstemp(res);
  write_ok = (uf > 0);
  write_ok = write_ok && (write(uf,buf,p-buf) > 0);
  write_ok = write_ok && (write(uf," encoding=\"",11) > 0);
  write_ok = write_ok && (write(uf,default_enc,strlen(default_enc)) > 0);
  write_ok = write_ok && (write(uf,"\" ",2) > 0);
  write_ok = write_ok && (write(uf,p,pmax - p) > 0);

  while (write_ok) {
    len = gzread(zf,buf,BUFLEN);
    if (len <= 0) break;
    write_ok = write_ok && (write(uf,buf,len) > 0);
  }
  gzclose(zf);
  if (uf > 0)
    close(uf);
  g_free(buf);
  if (!write_ok) {
    g_free(res);
    res = NULL;
  }
  return res; /* caller frees the name and unlinks the file. */
}
Exemplo n.º 16
0
static void
run (const gchar      *name,
     gint              nparams,
     const GimpParam  *param,
     gint             *nreturn_vals,
     GimpParam       **return_vals)
{
  static GimpParam   values[2];
  GimpPDBStatusType  status = GIMP_PDB_SUCCESS;
  GError            *error  = NULL;
  gint32             image;
  TiffSelectedPages  pages;

  run_mode = param[0].data.d_int32;

  INIT_I18N ();

  *nreturn_vals = 1;
  *return_vals  = values;

  gegl_init (NULL, NULL);

  values[0].type          = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;

  TIFFSetWarningHandler (tiff_warning);
  TIFFSetErrorHandler (tiff_error);

  if (strcmp (name, LOAD_PROC) == 0)
    {
      const gchar *filename = param[1].data.d_string;
      TIFF        *tif      = NULL;
      gint         fd;

      fd = g_open (filename, O_RDONLY | _O_BINARY, 0);

      if (fd == -1)
        {
          g_set_error (&error, G_FILE_ERROR, g_file_error_from_errno (errno),
                       _("Could not open '%s' for reading: %s"),
                       gimp_filename_to_utf8 (filename), g_strerror (errno));

          status = GIMP_PDB_EXECUTION_ERROR;
        }
      else
        {
          tif = TIFFFdOpen (fd, filename, "r");
        }

      if (tif)
        {
          gimp_get_data (LOAD_PROC, &target);

          pages.n_pages = pages.o_pages = TIFFNumberOfDirectories (tif);

          if (pages.n_pages == 0)
            {
              g_set_error (&error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
                           _("TIFF '%s' does not contain any directories"),
                           gimp_filename_to_utf8 (filename));

              status = GIMP_PDB_EXECUTION_ERROR;
            }
          else
            {
              gboolean run_it = FALSE;
              gint     i;

              if (run_mode != GIMP_RUN_INTERACTIVE)
                {
                  pages.pages = g_new (gint, pages.n_pages);

                  for (i = 0; i < pages.n_pages; i++)
                    pages.pages[i] = i;

                  run_it = TRUE;
                }

              if (pages.n_pages == 1)
                {
                  target = GIMP_PAGE_SELECTOR_TARGET_LAYERS;
                  pages.pages = g_new0 (gint, pages.n_pages);

                  run_it = TRUE;
                }

              if ((! run_it) && (run_mode == GIMP_RUN_INTERACTIVE))
                run_it = load_dialog (tif, &pages);

              if (run_it)
                {
                  gimp_set_data (LOAD_PROC, &target, sizeof (target));

                  image = load_image (param[1].data.d_string, tif, &pages,
                                      &error);

                  g_free (pages.pages);

                  if (image != -1)
                    {
                      *nreturn_vals = 2;
                      values[1].type         = GIMP_PDB_IMAGE;
                      values[1].data.d_image = image;
                    }
                  else
                    {
                      status = GIMP_PDB_EXECUTION_ERROR;
                    }
                }
              else
                {
                  status = GIMP_PDB_CANCEL;
                }
            }

          TIFFClose (tif);
          close (fd);
        }
      else
        {
          close (fd);
          status = GIMP_PDB_EXECUTION_ERROR;
        }
    }
  else
    {
      status = GIMP_PDB_CALLING_ERROR;
    }

  if (status != GIMP_PDB_SUCCESS && error)
    {
      *nreturn_vals = 2;
      values[1].type          = GIMP_PDB_STRING;
      values[1].data.d_string = error->message;
    }

  values[0].data.d_status = status;
}
Exemplo n.º 17
0
GeglBuffer *
gegl_buffer_load (const gchar *path)
{
  GeglBuffer *ret;

  LoadInfo *info = g_slice_new0 (LoadInfo);

  info->path = g_strdup (path);
  info->i = g_open (info->path, O_RDONLY, 0770);
  GEGL_NOTE (GEGL_DEBUG_BUFFER_LOAD, "starting to load buffer %s", path);
  if (info->i == -1)
    {
      GEGL_NOTE (GEGL_DEBUG_BUFFER_LOAD, "failed top open %s for reading", path);
      return NULL;
    }

  {
    GeglBufferItem *header = gegl_buffer_read_header (info->i, &info->offset, NULL);
    g_assert (header);
    /*memcpy (&(info->header), header, sizeof (GeglBufferHeader));*/
    info->header = *(&header->header);
    info->offset = info->header.next;
    /*g_free (header);*/  /* is there a pointer to a string or something we're missing? */
  }



  info->tile_size    = info->header.tile_width *
                       info->header.tile_height *
                       info->header.bytes_per_pixel;
  info->format       = babl_format (info->header.description);

  ret = g_object_new (GEGL_TYPE_BUFFER,
                      "format", info->format,
                      "tile-width", info->header.tile_width,
                      "tile-height", info->header.tile_height,
                      "height", info->header.height,
                      "width", info->header.width,
                      "path", path,
                      NULL);

  /* sanity check, should probably report error condition and return safely instead
  */
  g_assert (babl_format_get_bytes_per_pixel (info->format) == info->header.bytes_per_pixel);

  info->tiles = gegl_buffer_read_index (info->i, &info->offset, NULL);

  /* load each tile */
  {
    GList *iter;
    gint   i = 0;
    for (iter = info->tiles; iter; iter = iter->next)
      {
        GeglBufferTile *entry = iter->data;
        guchar         *data;
        GeglTile       *tile;


        tile = gegl_tile_source_get_tile (GEGL_TILE_SOURCE (ret),
                                          entry->x,
                                          entry->y,
                                          entry->z);

        if (info->offset != entry->offset)
          {
            seekto (info, entry->offset);
          }
        /*g_assert (info->offset == entry->offset);*/


        g_assert (tile);
        gegl_tile_lock (tile);

        data = gegl_tile_get_data (tile);
        g_assert (data);

        {
          ssize_t sz_read = read (info->i, data, info->tile_size);
          if(sz_read != -1)
            info->offset += sz_read;
        }
        /*g_assert (info->offset == entry->offset + info->tile_size);*/

        gegl_tile_unlock (tile);
        gegl_tile_unref (tile);
        i++;
      }
    GEGL_NOTE (GEGL_DEBUG_BUFFER_LOAD, "%i tiles loaded",i);
  }
  GEGL_NOTE (GEGL_DEBUG_BUFFER_LOAD, "buffer loaded %s", info->path);

  load_info_destroy (info);
  return ret;
}
Exemplo n.º 18
0
Arquivo: gmodule.c Projeto: zsx/glib
static gchar*
parse_libtool_archive (const gchar* libtool_name)
{
  const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
  const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
  const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
  gchar *lt_dlname = NULL;
  gboolean lt_installed = TRUE;
  gchar *lt_libdir = NULL;
  gchar *name;
  GTokenType token;
  GScanner *scanner;
  
  int fd = g_open (libtool_name, O_RDONLY, 0);
  if (fd < 0)
    {
      gchar *display_libtool_name = g_filename_display_name (libtool_name);
      g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
      g_free (display_libtool_name);
      return NULL;
    }
  /* search libtool's dlname specification  */
  scanner = g_scanner_new (NULL);
  g_scanner_input_file (scanner, fd);
  scanner->config->symbol_2_token = TRUE;
  g_scanner_scope_add_symbol (scanner, 0, "dlname", 
			      GUINT_TO_POINTER (TOKEN_DLNAME));
  g_scanner_scope_add_symbol (scanner, 0, "installed", 
			      GUINT_TO_POINTER (TOKEN_INSTALLED));
  g_scanner_scope_add_symbol (scanner, 0, "libdir", 
			      GUINT_TO_POINTER (TOKEN_LIBDIR));
  while (!g_scanner_eof (scanner))
    {
      token = g_scanner_get_next_token (scanner);
      if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED || 
	  token == TOKEN_LIBDIR)
	{
	  if (g_scanner_get_next_token (scanner) != '=' ||
	      g_scanner_get_next_token (scanner) != 
	      (token == TOKEN_INSTALLED ? 
	       G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
	    {
	      gchar *display_libtool_name = g_filename_display_name (libtool_name);
	      g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
	      g_free (display_libtool_name);

	      g_free (lt_dlname);
	      g_free (lt_libdir);
	      g_scanner_destroy (scanner);
	      close (fd);

	      return NULL;
	    }
	  else
	    {
	      if (token == TOKEN_DLNAME)
		{
		  g_free (lt_dlname);
		  lt_dlname = g_strdup (scanner->value.v_string);
		}
	      else if (token == TOKEN_INSTALLED)
		lt_installed = 
		  strcmp (scanner->value.v_identifier, "yes") == 0;
	      else /* token == TOKEN_LIBDIR */
		{
		  g_free (lt_libdir);
		  lt_libdir = g_strdup (scanner->value.v_string);
		}
	    }
	}      
    }

  if (!lt_installed)
    {
      gchar *dir = g_path_get_dirname (libtool_name);
      g_free (lt_libdir);
      lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
      g_free (dir);
    }

  name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
  
  g_free (lt_dlname);
  g_free (lt_libdir);
  g_scanner_destroy (scanner);
  close (fd);

  return name;
}
Exemplo n.º 19
0
void input_entry::g_open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) {
	TRACK_CALL_TEXT("input_entry::g_open_for_info_write");
	p_instance ^= g_open(input_info_writer::class_guid, p_filehint, p_path, p_abort, p_from_redirect);
}
Exemplo n.º 20
0
void backup_document_save_cb(GObject *obj, GeanyDocument *doc, gpointer user_data)
{
	FILE *src, *dst;
	gchar *locale_filename_src;
	gchar *locale_filename_dst;
	gchar *basename_src;
	gchar *dir_parts_src;
	gchar *stamp;
	gchar buf[512];
	gint fd_dst = -1;
	gchar backupcopy_time_fmt[] = "%Y-%m-%d-%H-%M-%S";

	locale_filename_src = utils_get_locale_from_utf8(doc->file_name);

	if ((src = g_fopen(locale_filename_src, "r")) == NULL)
	{
		/* it's unlikely that this happens */
		ui_set_statusbar ( FALSE, _("Backup Copy: File could not be read.") );
		g_free(locale_filename_src);
		return;
	}

	stamp = utils_get_date_time(backupcopy_time_fmt, NULL);
	basename_src = g_path_get_basename(locale_filename_src);
	dir_parts_src = backup_create_dir_parts(locale_filename_src);
	locale_filename_dst = g_strconcat(
		backupcopy_backup_dir, G_DIR_SEPARATOR_S,
		dir_parts_src, G_DIR_SEPARATOR_S,
		basename_src, ".", stamp, NULL);
	g_free(basename_src);
	g_free(dir_parts_src);

	msgwin_status_add ( "Backup into %s", locale_filename_dst );

	/* Use g_open() on non-Windows to set file permissions to 600 atomically.
	 * On Windows, seting file permissions would require specific Windows API. */
	fd_dst = g_open(locale_filename_dst, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
	if (fd_dst == -1 || (dst = fdopen(fd_dst, "w")) == NULL)
	{
		ui_set_statusbar(FALSE, _("Backup Copy: File could not be saved.") );
		g_free(locale_filename_src);
		g_free(locale_filename_dst);
		g_free(stamp);
		fclose(src);
		if (fd_dst != -1)
			close(fd_dst);
		return;
	}

	while (fgets(buf, sizeof(buf), src) != NULL)
	{
		fputs(buf, dst);
	}

	//ui_set_statusbar ( FALSE, _("Backup Copy Saved into %s."), local_filename_dst );
	msgwin_status_add ( "Backup created in %s", locale_filename_dst );

	fclose(src);
	fclose(dst);
	if (fd_dst != -1)
		close(fd_dst);
	g_free(locale_filename_src);
	g_free(locale_filename_dst);
	g_free(stamp);
}
Exemplo n.º 21
0
/* Adapted from auditd auditd-event.c */
static gboolean
open_log_file (const char *filename,
               int        *fdp,
               FILE      **filep)
{
        int      flags;
        int      fd;
        int      res;
        char    *dirname;
        FILE    *file;
        gboolean ret;

        ret = FALSE;

        /*
         * Likely errors on rotate: ENFILE, ENOMEM, ENOSPC
         */
        flags = O_WRONLY | O_APPEND;
#ifdef O_NOFOLLOW
        flags |= O_NOFOLLOW;
#endif

        dirname = g_path_get_dirname (filename);
        /* always make sure we have a directory */
        errno = 0;
        res = g_mkdir_with_parents (dirname,
                                    S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
        if (res < 0) {
                g_warning ("Unable to create directory %s (%s)",
                           dirname,
                           g_strerror (errno));
                g_free (dirname);
                return FALSE;
        }
        g_free (dirname);

retry:
        fd = g_open (filename, flags, 0600);
        if (fd < 0) {
                if (errno == ENOENT) {
                        /* FIXME: should we just skip if file doesn't exist? */
                        fd = g_open (filename,
                                     O_CREAT | O_EXCL | O_APPEND,
                                     S_IRUSR | S_IWUSR | S_IRGRP);
                        if (fd < 0) {
                                g_warning ("Couldn't create log file %s (%s)",
                                           filename,
                                           g_strerror (errno));
                                goto out;
                        }

                        close (fd);
                        fd = g_open (filename, flags, 0600);
                } else if (errno == ENFILE) {
                        /* All system descriptors used, try again... */
                        goto retry;
                }
                if (fd < 0) {
                        g_warning ("Couldn't open log file %s (%s)",
                                   filename,
                                   g_strerror (errno));
                        goto out;
                }
        }

        if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1) {
                close (fd);
                g_warning ("Error setting log file CLOEXEC flag (%s)",
                           g_strerror (errno));
                goto out;
        }

        if (fchown (fd, 0, 0) == -1) {
                g_warning ("Error changing owner of log file (%s)",
                           g_strerror (errno));
        }

        file = fdopen (fd, "a");
        if (file == NULL) {
                g_warning ("Error setting up log descriptor (%s)",
                           g_strerror (errno));
                close (fd);
                goto out;
        }

        /* Set it to line buffering */
        setlinebuf (file);

        ret = TRUE;

        if (fdp != NULL) {
                *fdp = fd;
        }
        if (filep != NULL) {
                *filep = file;
        }

 out:

        return ret;
}
Exemplo n.º 22
0
int
main (int argc, char **argv)
{
#ifdef G_OS_WIN32
	extern void link_shutdown (void);
#endif

	GConfClient *client;
#if DEVELOPMENT
	gboolean skip_warning_dialog;
#endif
	GnomeProgram *program;
	GnomeClient *master_client;
	GOptionContext *context;
	char *filename;

	/* Make ElectricFence work.  */
	free (malloc (10));

	bindtextdomain (GETTEXT_PACKAGE, EVOLUTION_LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

	context = g_option_context_new (_("- The Evolution PIM and Email Client"));

	g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);

	g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);

#ifdef G_OS_WIN32
	set_paths ();
#endif

	program = gnome_program_init (PACKAGE, VERSION, LIBGNOMEUI_MODULE, argc, argv,
				      GNOME_PROGRAM_STANDARD_PROPERTIES,
				      GNOME_PARAM_GOPTION_CONTEXT, context,
				      GNOME_PARAM_HUMAN_READABLE_NAME, _("Evolution"),
				      NULL);

#ifdef G_OS_WIN32
	if (strcmp (_(""), "") == 0) {
		/* No message catalog installed for the current locale language,
		 * so don't bother with the localisations provided by other things then
		 * either. Reset thread locale to "en-US" and C library locale to "C".
		 */
		SetThreadLocale (MAKELCID (MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
					   SORT_DEFAULT));
		setlocale (LC_ALL, "C");
	}
#endif
	if (start_online && start_offline) {
		fprintf (stderr, _("%s: --online and --offline cannot be used together.\n  Use %s --help for more information.\n"),
			 argv[0], argv[0]);
		exit (1);
	}

	if (killev) {
		filename = g_build_filename (EVOLUTION_TOOLSDIR,
					     "killev",
					     NULL);
		execl (filename, "killev", NULL);
		/* Not reached */
		exit (0);
	}

	client = gconf_client_get_default ();

#if DEVELOPMENT
	
	if (force_migrate) {
		destroy_config (client);
	}
#endif
	if (disable_preview) {
		gconf_client_set_bool (client, "/apps/evolution/mail/display/show_preview", FALSE, NULL);
		gconf_client_set_bool (client, "/apps/evolution/mail/display/safe_list", TRUE, NULL);
		gconf_client_set_bool (client, "/apps/evolution/addressbook/display/show_preview", FALSE, NULL);
		gconf_client_set_bool (client, "/apps/evolution/calendar/display/show_task_preview", FALSE, NULL);
	}

	setup_segv_redirect ();

	if (evolution_debug_log) {
		int fd;

		fd = g_open (evolution_debug_log, O_WRONLY | O_CREAT | O_TRUNC, 0600);
		if (fd != -1) {
			dup2 (fd, STDOUT_FILENO);
			dup2 (fd, STDERR_FILENO);
			close (fd);
		} else
			g_warning ("Could not set up debugging output file.");
	}

	master_client = gnome_master_client ();

	g_signal_connect (G_OBJECT (master_client), "save_yourself", G_CALLBACK (gnome_master_client_save_yourself_cb), NULL);
	g_signal_connect (G_OBJECT (master_client), "die", G_CALLBACK (gnome_master_client_die_cb), NULL);

	glade_init ();
	e_cursors_init ();
	e_icon_factory_init ();
	e_passwords_init();

	gtk_window_set_default_icon_name ("evolution");

	if (setup_only)
		exit (0);

	gnome_sound_init ("localhost");

	if (!disable_eplugin) {
		e_plugin_register_type(e_plugin_lib_get_type());
		e_plugin_hook_register_type(es_menu_hook_get_type());
		e_plugin_hook_register_type(es_event_hook_get_type());
#ifdef ENABLE_PROFILING
		e_plugin_hook_register_type(e_profile_event_hook_get_type());
#endif
		e_plugin_hook_register_type(e_plugin_type_hook_get_type());
		e_plugin_hook_register_type(e_import_hook_get_type());
		e_plugin_hook_register_type(E_TYPE_PLUGIN_UI_HOOK);
		e_plugin_load_plugins();
	}

#if DEVELOPMENT
	skip_warning_dialog = gconf_client_get_bool (
		client, SKIP_WARNING_DIALOG_KEY, NULL);

	if (!skip_warning_dialog && !getenv ("EVOLVE_ME_HARDER"))
		gconf_client_set_bool (
			client, SKIP_WARNING_DIALOG_KEY,
			show_development_warning (), NULL);
	else
		g_idle_add ((GSourceFunc) idle_cb, remaining_args);

#else
	g_idle_add ((GSourceFunc) idle_cb, remaining_args);
#endif
	g_object_unref (client);

	bonobo_main ();

	e_icon_factory_shutdown ();
	g_object_unref (program);
	gnome_sound_shutdown ();
	e_cursors_shutdown ();
#ifdef G_OS_WIN32
	link_shutdown ();
#endif
	return 0;
}
Exemplo n.º 23
0
/**
 * g_mapped_file_new:
 * @filename: The path of the file to load, in the GLib filename encoding
 * @writable: whether the mapping should be writable
 * @error: return location for a #GError, or %NULL
 *
 * Maps a file into memory. On UNIX, this is using the mmap() function.
 *
 * If @writable is %TRUE, the mapped buffer may be modified, otherwise
 * it is an error to modify the mapped buffer. Modifications to the buffer 
 * are not visible to other processes mapping the same file, and are not 
 * written back to the file.
 *
 * Note that modifications of the underlying file might affect the contents
 * of the #GMappedFile. Therefore, mapping should only be used if the file 
 * will not be modified, or if all modifications of the file are done
 * atomically (e.g. using g_file_set_contents()). 
 *
 * Return value: a newly allocated #GMappedFile which must be unref'd
 *    with g_mapped_file_unref(), or %NULL if the mapping failed.
 *
 * Since: 2.8
 */
GMappedFile *
g_mapped_file_new (const gchar  *filename,
		   gboolean      writable,
		   GError      **error)
{
  GMappedFile *file;
  int fd;
  struct stat st;

  g_return_val_if_fail (filename != NULL, NULL);
  g_return_val_if_fail (!error || *error == NULL, NULL);

  fd = g_open (filename, (writable ? O_RDWR : O_RDONLY) | _O_BINARY, 0);
  if (fd == -1)
    {
      int save_errno = errno;
      gchar *display_filename = g_filename_display_name (filename);
      
      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (save_errno),
                   _("Failed to open file '%s': open() failed: %s"),
                   display_filename, 
		   g_strerror (save_errno));
      g_free (display_filename);
      return NULL;
    }

  file = g_slice_new0 (GMappedFile);
  file->ref_count = 1;
  file->free_func = g_mapped_file_destroy;

  if (fstat (fd, &st) == -1)
    {
      int save_errno = errno;
      gchar *display_filename = g_filename_display_name (filename);

      g_set_error (error,
                   G_FILE_ERROR,
                   g_file_error_from_errno (save_errno),
                   _("Failed to get attributes of file '%s': fstat() failed: %s"),
                   display_filename, 
		   g_strerror (save_errno));
      g_free (display_filename);
      goto out;
    }

  if (st.st_size == 0)
    {
      file->length = 0;
      file->contents = NULL;
      close (fd);
      return file;
    }

  file->contents = MAP_FAILED;

#ifdef HAVE_MMAP
  if (st.st_size > G_MAXSIZE)
    {
      errno = EINVAL;
    }
  else
    {      
      file->length = (gsize) st.st_size;
      file->contents = (gchar *) mmap (NULL,  file->length,
				       writable ? PROT_READ|PROT_WRITE : PROT_READ,
				       MAP_PRIVATE, fd, 0);
    }
#endif
#ifdef G_OS_WIN32
  file->length = st.st_size;
  file->mapping = CreateFileMapping ((HANDLE) _get_osfhandle (fd), NULL,
				     writable ? PAGE_WRITECOPY : PAGE_READONLY,
				     0, 0,
				     NULL);
  if (file->mapping != NULL)
    {
      file->contents = MapViewOfFile (file->mapping,
				      writable ? FILE_MAP_COPY : FILE_MAP_READ,
				      0, 0,
				      0);
      if (file->contents == NULL)
	{
	  file->contents = MAP_FAILED;
	  CloseHandle (file->mapping);
	  file->mapping = NULL;
	}
    }
#endif

  
  if (file->contents == MAP_FAILED)
    {
      int save_errno = errno;
      gchar *display_filename = g_filename_display_name (filename);
      
      g_set_error (error,
		   G_FILE_ERROR,
		   g_file_error_from_errno (save_errno),
		   _("Failed to map file '%s': mmap() failed: %s"),
		   display_filename,
		   g_strerror (save_errno));
      g_free (display_filename);
      goto out;
    }

  close (fd);
  return file;

 out:
  close (fd);
  g_slice_free (GMappedFile, file);

  return NULL;
}
Exemplo n.º 24
0
static void
mp_label(struct gctl_req *req)
{
	struct g_multipath_metadata md;
	off_t disksize = 0, msize;
	uint8_t *sector, *rsector;
	char *ptr;
	uuid_t uuid;
	ssize_t secsize = 0, ssize;
	uint32_t status;
	const char *name, *name2, *mpname;
	int error, i, nargs, fd;

	nargs = gctl_get_int(req, "nargs");
	if (nargs < 2) {
		gctl_error(req, "wrong number of arguments.");
		return;
	}

	/*
	 * First, check each provider to make sure it's the same size.
	 * This also gets us our size and sectorsize for the metadata.
	 */
	for (i = 1; i < nargs; i++) {
		name = gctl_get_ascii(req, "arg%d", i);
		msize = g_get_mediasize(name);
		ssize = g_get_sectorsize(name);
		if (msize == 0 || ssize == 0) {
			gctl_error(req, "cannot get information about %s: %s.",
			    name, strerror(errno));
			return;
		}
		if (i == 1) {
			secsize = ssize;
			disksize = msize;
		} else {
			if (secsize != ssize) {
				gctl_error(req, "%s sector size %ju different.",
				    name, (intmax_t)ssize);
				return;
			}
			if (disksize != msize) {
				gctl_error(req, "%s media size %ju different.",
				    name, (intmax_t)msize);
				return;
			}
		}
		
	}

	/*
	 * Generate metadata.
	 */
	strlcpy(md.md_magic, G_MULTIPATH_MAGIC, sizeof(md.md_magic));
	md.md_version = G_MULTIPATH_VERSION;
	mpname = gctl_get_ascii(req, "arg0");
	strlcpy(md.md_name, mpname, sizeof(md.md_name));
	md.md_size = disksize;
	md.md_sectorsize = secsize;
	uuid_create(&uuid, &status);
	if (status != uuid_s_ok) {
		gctl_error(req, "cannot create a UUID.");
		return;
	}
	uuid_to_string(&uuid, &ptr, &status);
	if (status != uuid_s_ok) {
		gctl_error(req, "cannot stringify a UUID.");
		return;
	}
	strlcpy(md.md_uuid, ptr, sizeof (md.md_uuid));
	md.md_active_active = gctl_get_int(req, "active_active");
	free(ptr);

	/*
	 * Allocate a sector to write as metadata.
	 */
	sector = malloc(secsize);
	if (sector == NULL) {
		gctl_error(req, "unable to allocate metadata buffer");
		return;
	}
	memset(sector, 0, secsize);
	rsector = malloc(secsize);
	if (rsector == NULL) {
		free(sector);
		gctl_error(req, "unable to allocate metadata buffer");
		return;
	}

	/*
	 * encode the metadata
	 */
	multipath_metadata_encode(&md, sector);

	/*
	 * Store metadata on the initial provider.
	 */
	name = gctl_get_ascii(req, "arg1");
	error = g_metadata_store(name, sector, secsize);
	if (error != 0) {
		gctl_error(req, "cannot store metadata on %s: %s.", name, strerror(error));
		return;
	}

	/*
	 * Now touch the rest of the providers to hint retaste.
	 */
	for (i = 2; i < nargs; i++) {
		name2 = gctl_get_ascii(req, "arg%d", i);
		fd = g_open(name2, 1);
		if (fd < 0) {
			fprintf(stderr, "Unable to open %s: %s.\n",
			    name2, strerror(errno));
			continue;
		}
		if (pread(fd, rsector, secsize, disksize - secsize) !=
		    (ssize_t)secsize) {
			fprintf(stderr, "Unable to read metadata from %s: %s.\n",
			    name2, strerror(errno));
			g_close(fd);
			continue;
		}
		g_close(fd);
		if (memcmp(sector, rsector, secsize)) {
			fprintf(stderr, "No metadata found on %s."
			    " It is not a path of %s.\n",
			    name2, name);
		}
	}
}
Exemplo n.º 25
0
GtkIconCache *
_gtk_icon_cache_new_for_path (const gchar *path)
{
  GtkIconCache *cache = NULL;
  GMappedFile *map;

  gchar *cache_filename;
  gint fd = -1;
  struct stat st;
  struct stat path_st;
  CacheInfo info;

   /* Check if we have a cache file */
  cache_filename = g_build_filename (path, "icon-theme.cache", NULL);

  GTK_NOTE (ICONTHEME, 
	    g_print ("look for cache in %s\n", path));

  if (g_stat (path, &path_st) < 0)
    goto done;

  /* Open the file and map it into memory */
  fd = g_open (cache_filename, O_RDONLY|_O_BINARY, 0);

  if (fd < 0)
    goto done;
  
  if (fstat (fd, &st) < 0 || st.st_size < 4)
    goto done;

  /* Verify cache is uptodate */
  if (st.st_mtime < path_st.st_mtime)
    {
      GTK_NOTE (ICONTHEME, 
		g_print ("cache outdated\n"));
      goto done; 
    }

  map = g_mapped_file_new (cache_filename, FALSE, NULL);

  if (!map)
    goto done;

  info.cache = g_mapped_file_get_contents (map);
  info.cache_size = g_mapped_file_get_length (map);
  info.n_directories = 0;
  info.flags = CHECK_OFFSETS|CHECK_STRINGS;

#ifdef G_ENABLE_DEBUG
  if (gtk_debug_flags & GTK_DEBUG_ICONTHEME)
    {
      if (!_gtk_icon_cache_validate (&info))
        {
          g_mapped_file_free (map);
          g_warning ("Icon cache '%s' is invalid\n", cache_filename);

          goto done;
        }
    }
#endif 

  GTK_NOTE (ICONTHEME, g_print ("found cache for %s\n", path));

  cache = g_new0 (GtkIconCache, 1);
  cache->ref_count = 1;
  cache->map = map;
  cache->buffer = g_mapped_file_get_contents (map);

 done:
  g_free (cache_filename);  
  if (fd >= 0)
    close (fd);

  return cache;
}
Exemplo n.º 26
0
static gboolean
create_fs_dir(const gchar* dir, const gchar* xml_filename,
              guint root_dir_len, guint dir_mode, guint file_mode,
              GError** err)
{
  g_return_val_if_fail(xml_filename != NULL, FALSE);
  
  gconf_log(GCL_DEBUG, "Enter create_fs_dir: %s", dir);

  if (g_file_test(xml_filename, G_FILE_TEST_IS_REGULAR))
    {
      gconf_log(GCL_DEBUG, "XML backend file %s already exists", xml_filename);
      return TRUE;
    }
      
  /* Don't create anything above the root directory */
  if (strlen(dir) > root_dir_len)
    {
      gchar* parent;
      
      parent = _gconf_parent_dir (dir);

      gconf_log (GCL_DEBUG, "Parent dir is %s", parent);
      
      if (parent != NULL)
        {
          gchar* parent_xml = NULL;
          gboolean success = FALSE;
          
          if (xml_filename)
            parent_xml = g_strconcat(parent, "/%gconf.xml", NULL);
          
          success = create_fs_dir(parent, parent_xml, root_dir_len,
                                  dir_mode, file_mode, err);

          if (success)
            gconf_log(GCL_DEBUG, "created parent: %s", parent);
          else
            gconf_log(GCL_DEBUG, "failed parent: %s", parent);
          
          g_free(parent);
          g_free(parent_xml);
          
          if (!success)
            return FALSE;
        }
      else
        {
          gconf_log(GCL_DEBUG, "%s has no parent", dir);
        }
    }

  gconf_log(GCL_DEBUG, "Making directory %s", dir);
  
  if (g_mkdir(dir, dir_mode) < 0)
    {
      if (errno != EEXIST)
        {
          gconf_set_error(err, GCONF_ERROR_FAILED,
                          _("Could not make directory \"%s\": %s"),
                          (gchar*)dir, g_strerror(errno));
          return FALSE;
        }
    }

  if (xml_filename != NULL)
    {
      int fd;
      /* don't truncate the file, it may well already exist */
      fd = g_open(xml_filename, O_CREAT | O_WRONLY, file_mode);

      gconf_log(GCL_DEBUG, "Creating XML file %s", xml_filename);
      
      if (fd < 0)
        {
          gconf_set_error(err, GCONF_ERROR_FAILED, _("Failed to create file `%s': %s"),
                          xml_filename, g_strerror(errno));
          
          return FALSE;
        }
      
      if (close(fd) < 0)
        {
          gconf_set_error(err, GCONF_ERROR_FAILED, _("Failed to close file `%s': %s"),
                          xml_filename, g_strerror(errno));
          
          return FALSE;
        }
    }
  else
    {
      gconf_log(GCL_DEBUG, "No XML filename passed to create_fs_dir() for %s", dir);
    }
  
  return TRUE;
}
Exemplo n.º 27
0
static CamelMimeMessage *
mbox_folder_get_message_sync (CamelFolder *folder,
                              const gchar *uid,
                              GCancellable *cancellable,
                              GError **error)
{
	CamelLocalFolder *lf = (CamelLocalFolder *) folder;
	CamelMimeMessage *message = NULL;
	CamelMboxMessageInfo *info;
	CamelMimeParser *parser = NULL;
	gint fd, retval;
	gint retried = FALSE;
	goffset frompos;

	d (printf ("Getting message %s\n", uid));

	/* lock the folder first, burn if we can't, need write lock for summary check */
	if (camel_local_folder_lock (lf, CAMEL_LOCK_WRITE, error) == -1)
		return NULL;

	/* check for new messages always */
	if (camel_local_summary_check ((CamelLocalSummary *) camel_folder_get_folder_summary (folder), lf->changes, cancellable, error) == -1) {
		camel_local_folder_unlock (lf);
		return NULL;
	}

retry:
	/* get the message summary info */
	info = (CamelMboxMessageInfo *) camel_folder_summary_get (camel_folder_get_folder_summary (folder), uid);

	if (info == NULL) {
		set_cannot_get_message_ex (
			error, CAMEL_FOLDER_ERROR_INVALID_UID,
			uid, lf->folder_path, _("No such message"));
		goto fail;
	}

	frompos = camel_mbox_message_info_get_offset (CAMEL_MBOX_MESSAGE_INFO (info));
	g_clear_object (&info);

	if (frompos == -1)
		goto fail;

	/* we use an fd instead of a normal stream here - the reason is subtle, camel_mime_part will cache
	 * the whole message in memory if the stream is non-seekable (which it is when built from a parser
	 * with no stream).  This means we dont have to lock the mbox for the life of the message, but only
	 * while it is being created. */

	fd = g_open (lf->folder_path, O_LARGEFILE | O_RDONLY | O_BINARY, 0);
	if (fd == -1) {
		set_cannot_get_message_ex (
			error, CAMEL_ERROR_GENERIC,
			uid, lf->folder_path, g_strerror (errno));
		goto fail;
	}

	/* we use a parser to verify the message is correct, and in the correct position */
	parser = camel_mime_parser_new ();
	camel_mime_parser_init_with_fd (parser, fd);
	camel_mime_parser_scan_from (parser, TRUE);

	camel_mime_parser_seek (parser, frompos, SEEK_SET);
	if (camel_mime_parser_step (parser, NULL, NULL) != CAMEL_MIME_PARSER_STATE_FROM
	    || camel_mime_parser_tell_start_from (parser) != frompos) {

		g_warning ("Summary doesn't match the folder contents!  eek!\n"
			"  expecting offset %ld got %ld, state = %d", (glong) frompos,
			(glong) camel_mime_parser_tell_start_from (parser),
			camel_mime_parser_state (parser));

		g_object_unref (parser);
		parser = NULL;

		if (!retried) {
			retried = TRUE;
			camel_local_summary_check_force ((CamelLocalSummary *) camel_folder_get_folder_summary (folder));
			retval = camel_local_summary_check ((CamelLocalSummary *) camel_folder_get_folder_summary (folder), lf->changes, cancellable, error);
			if (retval != -1)
				goto retry;
		}

		set_cannot_get_message_ex (
			error, CAMEL_FOLDER_ERROR_INVALID,
			uid, lf->folder_path,
			_("The folder appears to be irrecoverably corrupted."));
		goto fail;
	}

	message = camel_mime_message_new ();
	if (!camel_mime_part_construct_from_parser_sync (
		(CamelMimePart *) message, parser, cancellable, error)) {
		g_prefix_error (
			error, _("Cannot get message %s from folder %s: "),
			uid, lf->folder_path);
		g_object_unref (message);
		message = NULL;
		goto fail;
	}

	camel_medium_remove_header ((CamelMedium *) message, "X-Evolution");

fail:
	/* and unlock now we're finished with it */
	camel_local_folder_unlock (lf);

	if (parser)
		g_object_unref (parser);

	/* use the opportunity to notify of changes (particularly if we had a rebuild) */
	if (camel_folder_change_info_changed (lf->changes)) {
		camel_folder_changed (folder, lf->changes);
		camel_folder_change_info_clear (lf->changes);
	}

	return message;
}
Exemplo n.º 28
0
static void
dir_load_doc(Dir* d, GError** err)
{
  gboolean xml_already_exists = TRUE;
  gboolean need_backup = FALSE;
  struct stat statbuf;
  
  g_return_if_fail(d->doc == NULL);

  if (stat(d->xml_filename, &statbuf) < 0)
    {
      switch (errno)
        {
        case ENOENT:
          xml_already_exists = FALSE;
          break;
        case ENOTDIR:
#ifdef ELOOP
        case ELOOP:
#endif
        case EFAULT:
        case EACCES:
        case ENOMEM:
        case ENAMETOOLONG:
        default:
          /* These are all fatal errors */
          gconf_set_error(err, GCONF_ERROR_FAILED, _("Failed to stat `%s': %s"),
                          d->xml_filename, g_strerror(errno));
          return;
          break;
        }
    }

  if (statbuf.st_size == 0)
    {
      xml_already_exists = FALSE;
    }

  if (xml_already_exists)
    {
      GError *tmp_err;
      gboolean error_was_fatal;

      error_was_fatal = FALSE;
      tmp_err = NULL;
      d->doc = my_xml_parse_file (d->xml_filename, &tmp_err);

      if (tmp_err != NULL)
        {
          gconf_log (GCL_WARNING,
                     "%s", tmp_err->message);

          /* file errors are assumed to be some kind of
           * blowup, like out of file descriptors, so
           * we play it safe and don't touch anything
           */
          if (tmp_err->domain == G_FILE_ERROR)
            error_was_fatal = TRUE;
          
          g_error_free (tmp_err);
        }

      if (error_was_fatal)
        return;
    }
  
  /* We recover from parse errors instead of passing them up */

  /* This has the potential to just blow away an entire corrupted
   * config file; but I think that is better than the alternatives
   * (disabling config for a directory because the document is mangled).
   *
   * Parse errors really should not happen from an XML file we created
   * ourselves anyway...
   */  

  /* Also we create empty %gconf.xml files when we create a new dir,
   * and those return a parse error, though they should be trapped
   * by the statbuf.st_size == 0 check above.
   */
  
  if (d->doc == NULL)
    {
      if (xml_already_exists)
        need_backup = TRUE; /* rather uselessly save whatever broken stuff was in the file */
          
      /* Create a new doc */
      
      d->doc = xmlNewDoc((xmlChar *)"1.0");
    }
  
  if (d->doc->xmlRootNode == NULL)
    {
      /* fill it in */
      d->doc->xmlRootNode = xmlNewDocNode(d->doc, NULL, "gconf", NULL);
    }
  else if (strcmp((char*)d->doc->xmlRootNode->name, "gconf") != 0)
    {
      xmlFreeDoc(d->doc);
      d->doc = xmlNewDoc((xmlChar*)"1.0");
      d->doc->xmlRootNode = xmlNewDocNode(d->doc, NULL, (xmlChar *)"gconf", NULL);
      need_backup = TRUE; /* save broken stuff */
    }
  else
    {
      /* We had an initial doc with a valid root */
      /* Fill child_cache from entries */
      dir_fill_cache_from_doc(d);
    }

  if (need_backup)
    {
      /* Back up the file we failed to parse, if it exists,
         we aren't going to be able to do anything if this call
         fails
      */
      
      gchar* backup = g_strconcat(d->xml_filename, ".bak", NULL);
      int fd;
      
      g_rename(d->xml_filename, backup);
      
      /* Recreate %gconf.xml to maintain our integrity and be sure
         all_subdirs works */
      /* If we failed to rename, we just give up and truncate the file */
      fd = g_open(d->xml_filename, O_CREAT | O_WRONLY | O_TRUNC, d->file_mode);
      if (fd >= 0)
        close(fd);
      
      g_free(backup);
    }
  
  g_assert(d->doc != NULL);
  g_assert(d->doc->xmlRootNode != NULL);
}
Exemplo n.º 29
0
int
save_config (void)
{
	int fh, i;
	char *config, *new_config;

	if (check_config_dir () != 0)
		make_config_dirs ();

	config = default_file ();
	new_config = g_strconcat (config, ".new", NULL);
	
	fh = g_open (new_config, OFLAGS | O_TRUNC | O_WRONLY | O_CREAT, 0600);
	if (fh == -1)
	{
		g_free (new_config);
		return 0;
	}

	if (!cfg_put_str (fh, "version", PACKAGE_VERSION))
	{
		close (fh);
		g_free (new_config);
		return 0;
	}
		
	i = 0;
	do
	{
		switch (vars[i].type)
		{
		case TYPE_STR:
			if (!cfg_put_str (fh, vars[i].name, (char *) &prefs + vars[i].offset))
			{
				close (fh);
				g_free (new_config);
				return 0;
			}
			break;
		case TYPE_INT:
		case TYPE_BOOL:
			if (!cfg_put_int (fh, *((int *) &prefs + vars[i].offset), vars[i].name))
			{
				close (fh);
				g_free (new_config);
				return 0;
			}
		}
		i++;
	}
	while (vars[i].name);

	if (close (fh) == -1)
	{
		g_free (new_config);
		return 0;
	}

#ifdef WIN32
	g_unlink (config);	/* win32 can't rename to an existing file */
#endif
	if (g_rename (new_config, config) == -1)
	{
		g_free (new_config);
		return 0;
	}
	g_free (new_config);

	return 1;
}
Exemplo n.º 30
0
void
gnc_file_aqbanking_import(const gchar *aqbanking_importername,
                          const gchar *aqbanking_profilename,
                          gboolean execute_transactions)
{
    gchar *default_dir;
    gchar *selected_filename = NULL;
    gint dtaus_fd = -1;
    AB_BANKING *api = NULL;
    gboolean online = FALSE;
    GncGWENGui *gui = NULL;
    AB_IMEXPORTER *importer;
    GWEN_DB_NODE *db_profiles = NULL;
    GWEN_DB_NODE *db_profile;
    AB_IMEXPORTER_CONTEXT *context = NULL;
    GWEN_IO_LAYER *io;
    GncABImExContextImport *ieci = NULL;
    AB_JOB_LIST2 *job_list = NULL;

    /* Select a file */
    default_dir = gnc_get_default_directory(GCONF_SECTION_AQBANKING);
    selected_filename = gnc_file_dialog(_("Select a file to import"),
                                        NULL, default_dir,
                                        GNC_FILE_DIALOG_IMPORT);
    g_free(default_dir);

    if (!selected_filename)
        goto cleanup;
    DEBUG("filename: %s", selected_filename);

    /* Remember the directory as the default */
    default_dir = g_path_get_dirname(selected_filename);
    gnc_set_default_directory(GCONF_SECTION_AQBANKING, default_dir);
    g_free(default_dir);

    dtaus_fd = g_open(selected_filename, O_RDONLY, 0);
    if (dtaus_fd == -1)
    {
        DEBUG("Could not open file %s", selected_filename);
        goto cleanup;
    }

    /* Get the API */
    api = gnc_AB_BANKING_new();
    if (!api)
    {
        g_warning("gnc_file_aqbanking_import: Couldn't get AqBanking API");
        goto cleanup;
    }
    if (AB_Banking_OnlineInit(api
#ifdef AQBANKING_VERSION_4_PLUS
                              , 0
#endif
                             ) != 0)
    {
        g_warning("gnc_file_aqbanking_import: "
                  "Couldn't initialize AqBanking API");
        goto cleanup;
    }
    online = TRUE;

    /* Get a GUI object */
    gui = gnc_GWEN_Gui_get(NULL);
    if (!gui)
    {
        g_warning("gnc_ab_getbalance: Couldn't initialize Gwenhywfar GUI");
        goto cleanup;
    }

    /* Get import module */
    importer = AB_Banking_GetImExporter(api, aqbanking_importername);
    if (!importer)
    {
        g_warning("Import module %s not found", aqbanking_importername);
        gnc_error_dialog(NULL, "%s",
                         _("Import module for DTAUS import not found."));
        goto cleanup;
    }

    /* Load the import profile */
    db_profiles = AB_Banking_GetImExporterProfiles(api, aqbanking_importername);

    /* Select profile */
    db_profile = GWEN_DB_GetFirstGroup(db_profiles);
    while (db_profile)
    {
        const gchar *name;

        name = GWEN_DB_GetCharValue(db_profile, "name", 0, 0);
        g_return_if_fail(name);
        if (g_ascii_strcasecmp(name, aqbanking_profilename) == 0)
            break;
        db_profile = GWEN_DB_GetNextGroup(db_profile);
    }
    if (!db_profile)
    {
        g_warning("Profile \"%s\" for importer \"%s\" not found",
                  aqbanking_profilename, aqbanking_importername);
        /* For debugging: Print those available names that have been found */
        db_profile = GWEN_DB_GetFirstGroup(db_profiles);
        while (db_profile)
        {
            const char *name = GWEN_DB_GetCharValue(db_profile, "name", 0, 0);
            g_warning("Only found profile \"%s\"\n", name ? name : "(null)");
            db_profile = GWEN_DB_GetNextGroup(db_profile);
        }
        goto cleanup;
    }

    /* Create a context to store the results */
    context = AB_ImExporterContext_new();

    /* Wrap file in buffered gwen io */
    io = GWEN_Io_LayerFile_new(dtaus_fd, -1);
    dtaus_fd = -1;
    if (GWEN_Io_Manager_RegisterLayer(io))
    {
        g_warning("gnc_file_aqbanking_import: Failed to wrap file");
        goto cleanup;
    }

    /* Run the import */
    if (AB_ImExporter_Import(importer, context, io, db_profile, 0))
    {
        g_warning("gnc_file_aqbanking_import: Error on import");
        goto cleanup;
    }

    /* Close the file */
    GWEN_Io_Layer_free(io);

    /* Import the results */
    ieci = gnc_ab_import_context(context, AWAIT_TRANSACTIONS,
                                 execute_transactions,
                                 execute_transactions ? api : NULL,
                                 NULL);

    /* Extract the list of jobs */
    job_list = gnc_ab_ieci_get_job_list(ieci);

    if (execute_transactions)
    {
        if (gnc_ab_ieci_run_matcher(ieci))
        {
            /* FIXME */
            /* gnc_hbci_multijob_execute(NULL, api, job_list, gui); */
        }
    }

cleanup:
    if (job_list)
        AB_Job_List2_FreeAll(job_list);
    if (ieci)
        g_free(ieci);
    if (context)
        AB_ImExporterContext_free(context);
    if (db_profiles)
        GWEN_DB_Group_free(db_profiles);
    if (gui)
        gnc_GWEN_Gui_release(gui);
    if (online)
#ifdef AQBANKING_VERSION_4_PLUS
        AB_Banking_OnlineFini(api, 0);
#else
        AB_Banking_OnlineFini(api);
#endif
    if (api)
        gnc_AB_BANKING_fini(api);
    if (dtaus_fd != -1)
        close(dtaus_fd);
    if (selected_filename)
        g_free(selected_filename);
}