Exemplo n.º 1
0
void create_data_dir(void **state)
{
    setenv("XDG_DATA_HOME", "./tests/files/xdg_data_home", 1);
    gchar *xdg_data = xdg_get_data_home();

    GString *profanity_dir = g_string_new(xdg_data);
    g_string_append(profanity_dir, "/profanity");

    if (!mkdir_recursive(profanity_dir->str)) {
        assert_true(FALSE);
    }

    g_free(xdg_data);
    g_string_free(profanity_dir, TRUE);
}
Exemplo n.º 2
0
static bool
create_user_directory (void)
{
  char buffer[FILENAME_MAX];

  if (!sys_get_user_path (buffer, sizeof (buffer)))
    {
      game_user_path = xstrdup ("qdata" FS_SEP_STR "savegame");
      return true;
    }

  game_user_path = xstrdup (buffer);

  return mkdir_recursive (game_user_path, 0700);
}
Exemplo n.º 3
0
int parse_copy_block(struct aos_block *block, unsigned int blocknumber, int detected_device)
{
	struct aos_block_copy *copy = (struct aos_block_copy  *)block->data;
	char *name;
	
	if(verbose)
		printf("(%u) Copy \"%s\".\n", blocknumber, copy->name);
	
	// Choose the destination name
	switch(copy->partition) {
		case AOS_PARTITION_SYSTEM: {
			name = bprintf("root/system/%s", copy->name);
			break;
		}
		case AOS_PARTITION_DATA: {
			name = bprintf( "root/data/%s", copy->name);
			break;
		}
		case AOS_PARTITION_CRAMFS: {
			name = bprintf("root/cramfs/%s", copy->name);
			break;
		}
		default: {
			name = bprintf("root/copy-%u/%s", copy->partition, copy->name);
			break;
		}
	}
	
	// Make sure the folder exist, and write the file to disk
	mkdir_recursive(name);
	file_write(name, copy->data, copy->size);
	
	// Write to digest
	if(strchr(copy->name, ' ') == NULL) // Quirks to keep digest clean
		log_write("digest", "copy %u %s %s\n", copy->partition, copy->name, name);
	else
		log_write("digest", "copy %u \"%s\" \"%s\"\n", copy->partition, copy->name, name);
	
	// Handle .cramfs.secure files
	if(!strcasecmp(&copy->name[strlen(copy->name)-strlen(".cramfs.secure")], ".cramfs.secure")) {
		parse_cramfs_archive(copy->name, copy->data, copy->size, name, detected_device);
	}
	
	free(name);
	
	return 1;
}
Exemplo n.º 4
0
bool CTar32::extract(const char *fname_extract_to)
{
	std::string fname;
	if(fname_extract_to){
		fname = fname_extract_to;
	}else{
		fname = m_currentfile_status.filename;
	}
	size64 filesize = m_currentfile_status.original_size;
	const int buf_size = 4096;
	char buf[buf_size];

	CTar32InternalFile file;
	file.open(this);

	//string dirname = get_dirname(fname.c_str());
	//mkdir_recursive(dirname.c_str());
	mkdir_recursive(get_dirname(fname.c_str()).c_str());

	//std::ofstream fs_w;
	fast_fstream fs_w;
	fs_w.open(fname.c_str(), std::ios::out|std::ios::binary);
	if(fs_w.fail()){return false;}
	//FILE *fp_w = fopen(fname.c_str(), "wb");
	//if(fp_w == NULL){
	//	return false;
	//}
	size64 readsize = 0;
	while(filesize==-1 || readsize<filesize){
		size64 nextreadsize = (filesize==-1) ? buf_size : min(filesize-readsize,buf_size);
		size64 n = file.read(buf,nextreadsize);
		fs_w.write(buf,nextreadsize);
		if(fs_w.fail()){
			if(filesize==-1){
				return true;
			}else{
				return false;
			}
		}
		//fwrite(buf,1,ret,fp_w);
		readsize += n;
		if(n != nextreadsize){/*fclose(fp_w);*/return false;}
	}
	//fclose(fp_w);
	return true;
}
Exemplo n.º 5
0
static
DWORD
prepare_domain_socket(PCSTR pszPath)
{
    DWORD dwError = 0;
    PSTR pszPathCopy = NULL;
    PSTR pszDirname = NULL;
    PSTR pszBasename = NULL;

    pszPathCopy = strdup(pszPath);
    if (!pszPathCopy)
    {
        dwError = ENOMEM;
        BAIL_ON_SRVSVC_ERROR(dwError);
    }

    pszBasename = strrchr(pszPathCopy, '/');

    if (!pszBasename)
    {
        dwError = EINVAL;
        BAIL_ON_SRVSVC_ERROR(dwError);
    }

    *(pszBasename++) = '\0';

    pszDirname = pszPathCopy;

    dwError = mkdir_recursive(pszDirname, 0655);
    BAIL_ON_SRVSVC_ERROR(dwError);

    /* Ensure directory is only accessible by root */
    if (chmod(pszDirname, 0600))
    {
        dwError = errno;
        BAIL_ON_SRVSVC_ERROR(dwError);
    }

error:

    if (pszPathCopy)
        free(pszPathCopy);

    return dwError;
}
Exemplo n.º 6
0
int parse_mtd_block(struct aos_block *block, unsigned int blocknumber, int detected_device)
{
	struct aos_block_mtd *mtd = (struct aos_block_mtd  *)block->data;
	char *name;
	
	if(verbose)
		printf("(%u) MTD \"%s\" at offset 0x%08x.\n", blocknumber, mtd->name, mtd->offset);
	
	name = bprintf("flash/%s-0x%08x", mtd->name, mtd->offset);
	mkdir_recursive(name);
	file_write(name, mtd->data, mtd->size);
	
	log_write("digest", "mtd %s 0x%08x %s\n", mtd->name, mtd->offset, name);
	
	parse_flash_partition(mtd->data, mtd->size, mtd->name, mtd->offset, name, detected_device);
	free(name);
	
	return 1;
}
Exemplo n.º 7
0
void init_file_path()
{
	char tmp[64];
	time_t t = time( NULL );
	struct tm* tm1 = localtime(&t);
	if( !tm1 ){
		perror("log.c init_file_path: ERROR GETTING SYSTEM TIME.");
	}
	log_day = tm1->tm_mday;
	strftime( tmp, 64, "/%Y-%m-%d.txt", tm1 );
	if( access( dir, 0 )!=0 ){
		mkdir_recursive( dir );
	}
	strcpy( filename, dir );
	strcat( filename, tmp );
	if( fp_log )
		fclose( fp_log );
	fp_log = fopen( filename, "aw" );
}
Exemplo n.º 8
0
/*
 * Make the given directory and its parents as necessary, using the
 * given mode. Return TRUE on success, FALSE otherwise. Partial
 * results are not cleaned up on errors.
 */
static notmuch_bool_t
mkdir_recursive (const void *ctx, const char *path, int mode)
{
    struct stat st;
    int r;
    char *parent = NULL, *slash;

    /* First check the common case: directory already exists. */
    r = stat (path, &st);
    if (r == 0) {
        if (! S_ISDIR (st.st_mode)) {
	    fprintf (stderr, "Error: '%s' is not a directory: %s\n",
		     path, strerror (EEXIST));
	    return FALSE;
	}

	return TRUE;
    } else if (errno != ENOENT) {
	fprintf (stderr, "Error: stat '%s': %s\n", path, strerror (errno));
	return FALSE;
    }

    /* mkdir parents, if any */
    slash = strrchr (path, '/');
    if (slash && slash != path) {
	parent = talloc_strndup (ctx, path, slash - path);
	if (! parent) {
	    fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
	    return FALSE;
	}

	if (! mkdir_recursive (ctx, parent, mode))
	    return FALSE;
    }

    if (mkdir (path, mode)) {
	fprintf (stderr, "Error: mkdir '%s': %s\n", path, strerror (errno));
	return FALSE;
    }

    return parent ? sync_dir (parent) : TRUE;
}
Exemplo n.º 9
0
int main(int argc, const char *argv[])
{
	const char *filename = "/etc/fstab";
	FILE *f;
	struct mntent *ent;
	if (argc == 2)
		filename = argv[1];

	f = setmntent(filename, "r");
	if (f == NULL)
		err(1, "%s", filename);

	while ((ent = getmntent(f)) != NULL) {
		if (strcmp(ent->mnt_dir, "none") != 0)
			mkdir_recursive(ent->mnt_dir);
	}
	
	endmntent(f);
	return 0;
}
Exemplo n.º 10
0
static int
handle_or_update(const char *path, ZipArchive *zip)
{
	//first, extract everything
	ui_print("Extracting archive...\n");
	
	char cmd[512];
	
	//ensure the target directory on the sdcard exists and is clean
	sprintf(cmd, "rm -rf %s", OR_UPDATE_EXTRACT_DIR_NAME); 
  run_shell_script(cmd, 0, NULL);
	
	if (mkdir_recursive(OR_UPDATE_EXTRACT_DIR_NAME))
	{
		LOGE("Failed creating: "OR_UPDATE_EXTRACT_DIR_NAME"\n");
		return INSTALL_ERROR;
	}
	
	bool ok = mzExtractRecursive(zip, "", OR_UPDATE_EXTRACT_DIR_NAME, 0, NULL, NULL, NULL);

	if (!ok) 
	{
    LOGE("Failed extracting the archive.\n");
    
    //clear it
    sprintf(cmd, "rm -rf %s", OR_UPDATE_EXTRACT_DIR_NAME); 
    run_shell_script(cmd, 0, NULL);
    return 1;
	}
		
	
	sprintf(cmd, "%s \"%s/%s\" \"%s\"", OR_SCRIPT_UPDATER_NAME, 
			OR_UPDATE_EXTRACT_DIR_NAME, ASSUMED_OR_UPDATE_SCRIPT_NAME, OR_UPDATE_EXTRACT_DIR_NAME);

	run_shell_script(cmd, 1, NULL);
	
	//clear it
	sprintf(cmd, "rm -rf %s", OR_UPDATE_EXTRACT_DIR_NAME); 
  run_shell_script(cmd, 0, NULL);
	return INSTALL_SUCCESS;
}
Exemplo n.º 11
0
int Populate_ByName_using_emmc(void)
{
	#define EMMC "/proc/emmc"
	#define DEV_BLOCKS "/dev/block"
	#define DEV_BYNAME MR_POPULATE_BY_NAME_PATH

    INFO("nkk71: check by-name support");

    if (mkdir_recursive(DEV_BYNAME, 0755) == 0)
	{
		FILE * fp;
		char strDev[20], strSize[20], strErasesize[20], strName[20];
		char strHardlink[80], strSoftlink[80];

        INFO("nkk71: begin populate");

		fp = fopen (EMMC, "r");
		
		if (fp == NULL)
			ERROR("nkk71: Error opening EMMC %s", EMMC);
		else
		{
			while (!feof(fp)) {
				fscanf(fp, "%[^:]: %s %s \"%[^\"]\" ", strDev, strSize, strErasesize, strName);

                if (strncmp("mmcblk0p", strDev, 8) == 0)
                {
    				sprintf (strHardlink, "%s/%s", DEV_BLOCKS, strDev);
	    			sprintf (strSoftlink, "%s/%s", DEV_BYNAME, strName);

                    INFO("nkk71: link %s to %s - result=%i\n", strSoftlink, strHardlink, symlink(strHardlink, strSoftlink));
                }
			}
			fclose(fp);
		}
        INFO("nkk71: populate done");
	}
    else
        INFO("nkk71: by-name already found, aborting populate");
	return(0);
}
Exemplo n.º 12
0
int parse_flash_block(struct aos_block *block, unsigned int blocknumber, int detected_device)
{
	struct aos_block_flash *flash = (struct aos_block_flash *)block->data;
	char *name;
	
	if(verbose)
		printf("(%u) Flash segment \"%s\" at offset 0x%08x.\n", blocknumber, flash_name(flash->offset), flash->offset);
	
	switch(flash->offset) {
		case 0x00000000: break;
		case 0x003f8000: break;
		case 0x00060000: break;
		
		case 0x00010000:
			printf("WARNING: keys are changed in this update!\n");
			break;
		case 0x00030000:
			if(*(uint32_t *)flash->data != AOS_ZMfX_MAGIC)
				printf("WARNING: Wrong ZMfX header flashed at 0x030000 (this is bad!)\n");
			break;
		case 0x00080000:
			if(*(uint32_t *)flash->data != AOS_KERNEL_MAGIC)
				printf("WARNING: Wrong kernel header flashed at 0x080000 (this is bad!)\n");
			break;
		case 0x00210000:
			if(*(uint32_t *)flash->data != AOS_KERNEL_MAGIC)
				printf("WARNING: Wrong kernel header flashed at 0x210000 (this is bad!)\n");
			break;
	}
	
	name = bprintf("flash/%s_0x%08x", flash_name(flash->offset), flash->offset);
	mkdir_recursive(name);
	file_write(name, flash->data, flash->size);
	
	log_write("digest", "flash 0x%08x %s\n", flash->offset, name);
	
	parse_flash_partition(flash->data, flash->size, flash_name(flash->offset), flash->offset, name, detected_device);
	free(name);
	
	return 1;
}
Exemplo n.º 13
0
int parse_shell_block(struct aos_block *block, unsigned int blocknumber)
{
	struct aos_block_shell *shell= (struct aos_block_shell  *)block->data;
	char *name;
	
	if(verbose)
		printf("(%u) Shell script.\n", blocknumber);
	
	name = bprintf("shell/script_%u.sh", blocknumber);
	
	// Make sure the folder exist, and write the file to disk
	mkdir_recursive(name);
	file_write(name, shell->data, shell->length);
	
	// Write to digest
	log_write("digest", "shell %s\n", name);
	
	free(name);
	
	return 1;
}
Exemplo n.º 14
0
void make_link_init(const char *oldpath, const char *newpath)
{
    int ret;
    char buf[256];
    const char *slash;
    int width;

    slash = strrchr(newpath, '/');
    if (!slash)
        return;
    width = slash - newpath;
    if (width <= 0 || width > (int)sizeof(buf) - 1)
        return;
    memcpy(buf, newpath, width);
    buf[width] = 0;
    ret = mkdir_recursive(buf, 0755);
    if (ret) PLOG(ERROR) << "Failed to create directory " << buf;

    ret = symlink(oldpath, newpath);
    if (ret && errno != EEXIST) PLOG(ERROR) << "Failed to symlink " << oldpath << " to " << newpath;
}
Exemplo n.º 15
0
int logfile_open()
{
    char logpath[PATH_MAX];
    char timestamp[1024];
    char *logdir="/var/log";  
    
    format_time(timestamp, sizeof(timestamp), time(NULL));
    snprintf(logpath, sizeof(logpath), "%s/fsarchiver_%s_%ld.log", logdir, timestamp, (long)getpid());
    mkdir_recursive(logdir);
    
    g_logfile=open64(logpath, O_RDWR|O_CREAT|O_TRUNC|O_LARGEFILE, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    if (g_logfile>=0)
    {   msgprintf(MSG_VERB1, "Creating logfile in %s\n", logpath);
        msgprintf(MSG_VERB1, "Running fsarchiver version=[%s], fileformat=[%s]\n", FSA_VERSION, FSA_FILEFORMAT);
        return FSAERR_SUCCESS;
    }
    else
    {   sysprintf("Cannot create logfile in %s\n", logpath);
        return FSAERR_UNKNOWN;
    }
}
Exemplo n.º 16
0
/*
 * Create the given maildir folder, i.e. maildir and its
 * subdirectories cur/new/tmp. Return true on success, false
 * otherwise. Partial results are not cleaned up on errors.
 */
static bool
maildir_create_folder (const void *ctx, const char *maildir, bool world_readable)
{
    const char *subdirs[] = { "cur", "new", "tmp" };
    const int mode = (world_readable ? 0755 : 0700);
    char *subdir;
    unsigned int i;

    for (i = 0; i < ARRAY_SIZE (subdirs); i++) {
	subdir = talloc_asprintf (ctx, "%s/%s", maildir, subdirs[i]);
	if (! subdir) {
	    fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
	    return false;
	}

	if (! mkdir_recursive (ctx, subdir, mode))
	    return false;
    }

    return true;
}
Exemplo n.º 17
0
/*
 * Create the given maildir folder, i.e. maildir and its
 * subdirectories cur/new/tmp. Return TRUE on success, FALSE
 * otherwise. Partial results are not cleaned up on errors.
 */
static notmuch_bool_t
maildir_create_folder (const void *ctx, const char *maildir)
{
    const char *subdirs[] = { "cur", "new", "tmp" };
    const int mode = 0700;
    char *subdir;
    unsigned int i;

    for (i = 0; i < ARRAY_SIZE (subdirs); i++) {
	subdir = talloc_asprintf (ctx, "%s/%s", maildir, subdirs[i]);
	if (! subdir) {
	    fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
	    return FALSE;
	}

	if (! mkdir_recursive (ctx, subdir, mode))
	    return FALSE;
    }

    return TRUE;
}
Exemplo n.º 18
0
static int log_open_file(char *name)
{
    int fd = 0;
    if (access(name, W_OK) == 0) //file exist
    {
        fd = open(name, O_WRONLY | O_APPEND, 0);
    }
    else
    {
        fd = open(name, O_WRONLY | O_APPEND | O_CREAT, 0644);
        if (fd > 0)
        {
            return fd;
        }

        char tmp;
        char *dir = strrchr(name, '/');
        if (NULL == dir)
        {
            printf("the file must be a dir\n");
            return -1;
        }
        tmp = *dir;
        *dir = '\0';
        if (false == mkdir_recursive(name, (mode_t)0644))
        {
            printf("the mkdir recursive failed, the dir is %s\n", name);
            return -1;
        }
        *dir = tmp;
        fd = open(name, O_WRONLY | O_APPEND | O_CREAT, 0644);
    }
    if (fd < 0)
    {
        printf("opening log file '%s' failed: %s", name, strerror(errno));
        return -1;
    }

    return fd;
}
Exemplo n.º 19
0
Arquivo: main.c Projeto: hiciu/ekg2
/*
 * otwarcie pliku do zapisu/odczytu
 * tworzy wszystkie katalogi po drodze, jeśli nie istnieją i mkdir =1
 * ff - xml 2 || irssi 3 || simple 1
 * zwraca numer deskryptora bądź NULL
 */
static int logs_open_file(logs_log_t *ll) {

	g_return_val_if_fail(ll != NULL, -1);

	if (ll->file)
		return fseek(ll->file, 0, SEEK_END);

	g_return_val_if_fail(ll->fname != NULL, -1);
	g_return_val_if_fail(ll->format != LOG_FORMAT_NONE, -1);

// XXX temp
debug("[logs] opening log file %s ff:%d\n", __(ll->fname), ll->format);

	if (!g_file_test(ll->fname, G_FILE_TEST_IS_REGULAR) && mkdir_recursive(ll->fname, 0)) {
		print("directory_cant_create", ll->fname, strerror(errno));
		return -1;
	}

	if (!(ll->file = fopen(ll->fname, "a+")))
		return -1;

	if (ll->format == LOG_FORMAT_XML) {
		/* prepare xml file */
		fputs(EKG_EMPTY_XML_LOG, ll->file);
	}

	// move ll on top
	if (ll != g_ptr_array_index(logs_logs, logs_logs->len - 1)) {
		g_ptr_array_set_free_func(logs_logs, NULL);
		g_ptr_array_remove(logs_logs, ll);
		g_ptr_array_add(logs_logs, ll);
		g_ptr_array_set_free_func(logs_logs, logs_log_destroy);
	}

	open_files_count++;
	logs_open_files_check();

	return fseek(ll->file, 0, SEEK_END);
}
Exemplo n.º 20
0
void fs_mkdir(const char *name) {
	EUID_ASSERT();

	// check directory name
	invalid_filename(name, 0); // no globbing
	char *expanded = expand_macros(name);
	if (strncmp(expanded, cfg.homedir, strlen(cfg.homedir)) != 0 &&
	    strncmp(expanded, "/tmp", 4) != 0) {
		fprintf(stderr, "Error: only directories in user home or /tmp are supported by mkdir\n");
		exit(1);
	}

	struct stat s;
	if (stat(expanded, &s) == 0) {
		// file exists, do nothing
		goto doexit;
	}

	// create directory
	pid_t child = fork();
	if (child < 0)
		errExit("fork");
	if (child == 0) {
		// drop privileges
		drop_privs(0);

		// create directory
		mkdir_recursive(expanded);
#ifdef HAVE_GCOV
		__gcov_flush();
#endif
		_exit(0);
	}
	// wait for the child to finish
	waitpid(child, NULL, 0);

doexit:
	free(expanded);
}
Exemplo n.º 21
0
Arquivo: util.c Projeto: demo4sc/patch
void make_link(const char *oldpath, const char *newpath)
{
    int ret;
    char buf[256];
    char *slash;
    int width;

    slash = strrchr(newpath, '/');
    if (!slash)
        return;
    width = slash - newpath;
    if (width <= 0 || width > (int)sizeof(buf) - 1)
        return;
    memcpy(buf, newpath, width);
    buf[width] = 0;
    ret = mkdir_recursive(buf, 0755);
    if (ret)
        ERROR("Failed to create directory %s: %s (%d)\n", buf, strerror(errno), errno);

    ret = symlink(oldpath, newpath);
    if (ret && errno != EEXIST)
        ERROR("Failed to symlink %s to %s: %s (%d)\n", oldpath, newpath, strerror(errno), errno);
}
Exemplo n.º 22
0
void
otr_keygen(ProfAccount *account)
{
    if (data_loaded) {
        cons_show("OTR key already generated.");
        return;
    }

    if (jid) {
        free(jid);
    }
    jid = strdup(account->jid);
    log_info("Generating OTR key for %s", jid);

    gchar *data_home = xdg_get_data_home();
    GString *basedir = g_string_new(data_home);
    free(data_home);

    gchar *account_dir = str_replace(jid, "@", "_at_");
    g_string_append(basedir, "/profanity/otr/");
    g_string_append(basedir, account_dir);
    g_string_append(basedir, "/");
    free(account_dir);

    if (!mkdir_recursive(basedir->str)) {
        log_error("Could not create %s for account %s.", basedir->str, jid);
        cons_show_error("Could not create %s for account %s.", basedir->str, jid);
        g_string_free(basedir, TRUE);
        return;
    }

    gcry_error_t err = 0;

    GString *keysfilename = g_string_new(basedir->str);
    g_string_append(keysfilename, "keys.txt");
    log_debug("Generating private key file %s for %s", keysfilename->str, jid);
    cons_show("Generating private key, this may take some time.");
    cons_show("Moving the mouse randomly around the screen may speed up the process!");
    ui_update();
    err = otrl_privkey_generate(user_state, keysfilename->str, account->jid, "xmpp");
    if (!err == GPG_ERR_NO_ERROR) {
        g_string_free(basedir, TRUE);
        g_string_free(keysfilename, TRUE);
        log_error("Failed to generate private key");
        cons_show_error("Failed to generate private key");
        return;
    }
    log_info("Private key generated");
    cons_show("");
    cons_show("Private key generation complete.");

    GString *fpsfilename = g_string_new(basedir->str);
    g_string_append(fpsfilename, "fingerprints.txt");
    log_debug("Generating fingerprints file %s for %s", fpsfilename->str, jid);
    err = otrl_privkey_write_fingerprints(user_state, fpsfilename->str);
    if (!err == GPG_ERR_NO_ERROR) {
        g_string_free(basedir, TRUE);
        g_string_free(keysfilename, TRUE);
        log_error("Failed to create fingerprints file");
        cons_show_error("Failed to create fingerprints file");
        return;
    }
    log_info("Fingerprints file created");

    err = otrl_privkey_read(user_state, keysfilename->str);
    if (!err == GPG_ERR_NO_ERROR) {
        g_string_free(basedir, TRUE);
        g_string_free(keysfilename, TRUE);
        log_error("Failed to load private key");
        data_loaded = FALSE;
        return;
    }

    err = otrl_privkey_read_fingerprints(user_state, fpsfilename->str, NULL, NULL);
    if (!err == GPG_ERR_NO_ERROR) {
        g_string_free(basedir, TRUE);
        g_string_free(keysfilename, TRUE);
        log_error("Failed to load fingerprints");
        data_loaded = FALSE;
        return;
    }

    data_loaded = TRUE;

    g_string_free(basedir, TRUE);
    g_string_free(keysfilename, TRUE);
    g_string_free(fpsfilename, TRUE);
    return;
}
Exemplo n.º 23
0
int pl_file_mkdir_recursive(const char *path)
{
  return mkdir_recursive(path);
}
Exemplo n.º 24
0
bool extract_files(const std::string &filename, const std::string &target,
                   const std::vector<std::string> &files)
{
    if (files.empty()) {
        return false;
    }

    autoclose::archive in(archive_read_new(), archive_read_free);
    autoclose::archive out(archive_write_disk_new(), archive_write_free);

    if (!in || !out) {
        LOGE("Out of memory");
        return false;
    }

    archive_entry *entry;
    int ret;
    std::string cwd = get_cwd();
    unsigned int count = 0;

    if (cwd.empty()) {
        return false;
    }

    if (!set_up_input(in.get(), filename)) {
        return false;
    }

    set_up_output(out.get());

    if (!mkdir_recursive(target, S_IRWXU | S_IRWXG | S_IRWXO)) {
        LOGE("%s: Failed to create directory: %s",
             target.c_str(), strerror(errno));
        return false;
    }

    if (chdir(target.c_str()) < 0) {
        LOGE("%s: Failed to change to target directory: %s",
             target.c_str(), strerror(errno));
        return false;
    }

    auto chdir_back = finally([&] {
        chdir(cwd.c_str());
    });

    while ((ret = archive_read_next_header(in.get(), &entry)) == ARCHIVE_OK) {
        if (std::find(files.begin(), files.end(),
                archive_entry_pathname(entry)) != files.end()) {
            ++count;

            if (libarchive_copy_header_and_data(in.get(), out.get(), entry) != ARCHIVE_OK) {
                return false;
            }
        }
    }

    if (ret != ARCHIVE_EOF) {
        LOGE("Archive extraction ended without reaching EOF: %s",
             archive_error_string(in.get()));
        return false;
    }

    if (count != files.size()) {
        LOGE("Not all specified files were extracted");
        return false;
    }

    return true;
}
Exemplo n.º 25
0
int main(int argc, const char **argv)
{
    char path[512];
    char cmd[1024];
    int rc;

    printf("razorclaw - asus backup local root exploit.\n");
    printf("by androidroot.mobi\n");
    printf("-------------------------------------------\n\n");

    if(getuid() == 0) {
        if(argc > 1 && !strcasecmp(argv[1], "--install")) {
            printf("[+] installing SuperUser and su\n");
            return do_root();
        } else {
            printf("[-] already root and nothing to do.\n\n");
            printf("[*] hint: to install SuperUser and su pass the "
                   "--install parameter on the command line.\n");
            return 1;
        }
    }

    readlink("/proc/self/exe", path, sizeof(path));
    path[strrchr(path, '/') - path] = '\0';

    if(chdir(path)) {
        printf("[-] could not chdir into directory: %s\n", path);
        return 2;
    }

    if(!mkdir_recursive(DB_DIR)) {
        printf("[-] could not create directory: %s\n", DB_DIR);
        return 3;
    } else {
        printf("[+] created fake relative path.\n");
    }

    if(!create_database()) {
        printf("[-] failed to create fake database.\n");
        return 4;
    } else {
        printf("[+] created fake database.\n");
    }

    snprintf(cmd, sizeof(cmd),
             "/system/xbin/asus-backup %s %s/%s --install >/dev/null",
             SECURE_ARG, path, strrchr(argv[0], '/') + 1);

    if(argc > 1 && !strcasecmp(argv[1], "--install")) {
        rc = system(cmd);

        switch(rc) {
            case DO_ROOT_OK:
                printf("[!] successfully rooted your device.\n");
            break;
            case DO_ROOT_FAIL_MOUNT:
                printf("[-] failed to remount /system\n");
            break;
            case DO_ROOT_FAIL_SU:
                printf("[-] failed to install su binary\n");
            break;
            case DO_ROOT_FAIL_SU_SUID:
                printf("[-] failed to set su binary suid\n");
            break;
            case DO_ROOT_FAIL_APK:
                printf("[-] failed to install Superuser.apk\n");
            break;
            default:
                printf("[-] unknown error occurred whist "
                       "trying to root device: %d\n", rc);
            break;
        }

    } else {
        printf("[!] spawning your root shell...\n");
        rc = execl("/system/xbin/asus-backup", "/system/xbin/asus-backup",
                   SECURE_ARG, "/system/bin/sh", NULL);
    }

    return rc;
}
Exemplo n.º 26
0
int FileStreamWrapper::mkdir(const String& path, int mode, int options) {
  if (options & k_STREAM_MKDIR_RECURSIVE)
    return mkdir_recursive(path, mode);
  return ::mkdir(File::TranslatePath(path).data(), mode);
}
Exemplo n.º 27
0
void parseArgs(VersionUpdateConfig *config, int argc, char *args[]) {

	if(argc < 4) {
		fprintf(stderr, "USAGE:%s\n", USAGE);
		exit(3);
	}

	if(debug) {
		int i = 0;
		for(i = 0; i < argc; i++) {
			fprintf(stdout, "param $%d == %s\n", i, args[i]);
		}
	}

	char *URL = args[1];
	char *path = args[2];
	int   intervalSecond = atoi(args[3]);
	char *lockURL = args[4];

	if(argc > 5) {
		debug = atoi(args[5]);
	}
	//global var
	size_t URLLen = strlen(URL);
	size_t pathLen = strlen(path);
	
	if(!parseLockUrl(lockURL, config)){
		exit(1);
	}
	
	//interval time
	config->intervalSecond = intervalSecond;
	//url
	buffer *URLDomain = buffer_init_size(URLLen + 1);
	stringAppend(URLDomain, URL, URLLen);
	config->URLDomain = URLDomain;
	debug_buffer(URLDomain, "URLDomain");
	
	//dir
	buffer *versionFileDir = buffer_init_size(pathLen + 1);
	char *lastChar = strrchr(path, '/');
	if(NULL == lastChar) {
		fprintf(stderr, "USAGE:%s\n", USAGE);
		exit(5);
	}
	stringAppend(versionFileDir, path, pathLen - strlen(lastChar));
	config->versionFileDir = versionFileDir;
	struct stat st;
	if (-1 == stat(versionFileDir->ptr, &st)) {
		//mkdir
		mkdir_recursive(versionFileDir->ptr);
		debug_buffer(versionFileDir, "mkdir_recursive make done....");
	}
	debug_buffer(versionFileDir, "versionFileDir");
	//source
	buffer *versionFilePath = buffer_init_size(pathLen + 1);
	stringAppend(versionFilePath, path, pathLen);
	config->versionFilePath = versionFilePath;
	debug_buffer(versionFilePath, "versionFilePath");
	//expect
	buffer *expectVersionFilePath = buffer_init_size(versionFilePath->size);
	stringAppend(expectVersionFilePath, path, pathLen - 3); //--clean .gz
	config->expectVersionFilePath = expectVersionFilePath;
	debug_buffer(expectVersionFilePath, "expectVersionFilePath");
	//response
	buffer *reponseFilePath = buffer_init_size(versionFilePath->size + REPONSE_LOG_LEN);
	stringAppend(reponseFilePath, expectVersionFilePath->ptr, expectVersionFilePath->used);
	stringAppend(reponseFilePath, REPONSE_LOG, REPONSE_LOG_LEN);
	config->reponseFilePath = reponseFilePath;
	debug_buffer(reponseFilePath, "reponseFilePath");
	//tmp
	buffer *tmpVersionFilePath = buffer_init_size(versionFilePath->size + TMP_LEN);
	stringAppend(tmpVersionFilePath, versionFilePath->ptr, versionFilePath->used);
	stringAppend(tmpVersionFilePath, TMP, TMP_LEN);
	config->tmpVersionFilePath = tmpVersionFilePath;
	debug_buffer(tmpVersionFilePath, "tmpVersionFilePath");
}
Exemplo n.º 28
0
void
otr_on_connect(ProfAccount *account)
{
    if (jid) {
        free(jid);
    }
    jid = strdup(account->jid);
    log_info("Loading OTR key for %s", jid);

    gchar *data_home = xdg_get_data_home();
    GString *basedir = g_string_new(data_home);
    free(data_home);

    gchar *account_dir = str_replace(jid, "@", "_at_");
    g_string_append(basedir, "/profanity/otr/");
    g_string_append(basedir, account_dir);
    g_string_append(basedir, "/");
    free(account_dir);

    if (!mkdir_recursive(basedir->str)) {
        log_error("Could not create %s for account %s.", basedir->str, jid);
        cons_show_error("Could not create %s for account %s.", basedir->str, jid);
        g_string_free(basedir, TRUE);
        return;
    }

    user_state = otrl_userstate_create();

    gcry_error_t err = 0;

    GString *keysfilename = g_string_new(basedir->str);
    g_string_append(keysfilename, "keys.txt");
    if (!g_file_test(keysfilename->str, G_FILE_TEST_IS_REGULAR)) {
        log_info("No OTR private key file found %s", keysfilename->str);
        data_loaded = FALSE;
    } else {
        log_info("Loading OTR private key %s", keysfilename->str);
        err = otrl_privkey_read(user_state, keysfilename->str);
        if (!err == GPG_ERR_NO_ERROR) {
            log_warning("Failed to read OTR private key file: %s", keysfilename->str);
            cons_show_error("Failed to read OTR private key file: %s", keysfilename->str);
            g_string_free(basedir, TRUE);
            g_string_free(keysfilename, TRUE);
            return;
        }

        OtrlPrivKey* privkey = otrl_privkey_find(user_state, jid, "xmpp");
        if (!privkey) {
            log_warning("No OTR private key found for account \"%s\", protocol \"xmpp\" in file: %s", jid, keysfilename->str);
            cons_show_error("No OTR private key found for account \"%s\", protocol \"xmpp\" in file: %s", jid, keysfilename->str);
            g_string_free(basedir, TRUE);
            g_string_free(keysfilename, TRUE);
            return;
        }
        log_info("Loaded OTR private key");
        data_loaded = TRUE;
    }

    GString *fpsfilename = g_string_new(basedir->str);
    g_string_append(fpsfilename, "fingerprints.txt");
    if (!g_file_test(fpsfilename->str, G_FILE_TEST_IS_REGULAR)) {
        log_info("No OTR fingerprints file found %s", fpsfilename->str);
        data_loaded = FALSE;
    } else {
        log_info("Loading OTR fingerprints %s", fpsfilename->str);
        err = otrl_privkey_read_fingerprints(user_state, fpsfilename->str, NULL, NULL);
        if (!err == GPG_ERR_NO_ERROR) {
            log_error("Failed to load OTR fingerprints file: %s", fpsfilename->str);
            g_string_free(basedir, TRUE);
            g_string_free(keysfilename, TRUE);
            g_string_free(fpsfilename, TRUE);
            return;
        } else {
            log_info("Loaded OTR fingerprints");
            data_loaded = TRUE;
        }
    }

    if (data_loaded) {
        cons_show("Loaded OTR private key for %s", jid);
    }

    g_string_free(basedir, TRUE);
    g_string_free(keysfilename, TRUE);
    g_string_free(fpsfilename, TRUE);
    return;
}
Exemplo n.º 29
0
bool extract_file(CTar32CmdInfo &cmdinfo, CTar32 *pTarfile, const char *fname,std::vector<char> &buffer)
{
	CTar32FileStatus &stat = pTarfile->m_currentfile_status;
	std::string fname2 = fname;

	EXTRACTINGINFOEX extractinfo;
	EXTRACTINGINFOEX64 exinfo64;
	MakeExtractingInfo(pTarfile,fname2.c_str(),extractinfo,exinfo64);
	{
		int ret = SendArcMessage(cmdinfo, ARCEXTRACT_BEGIN, &extractinfo,&exinfo64);
		if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
		fname2 = extractinfo.exinfo.szDestFileName;
	}

	//上書き確認
	if(cmdinfo.b_confirm_overwrite){
		switch(ConfirmOverwrite(cmdinfo, exinfo64)){
		case -1://cancel(abort)
			throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);
			break;
		case 1:	//yes to all
			cmdinfo.b_confirm_overwrite=false;
			break;
		}
	}

	size64 filesize = pTarfile->m_currentfile_status.original_size;

	CTar32InternalFile file; file.open(pTarfile);


	//std::ofstream fs_w;
	fast_fstream fs_w;
	if(!cmdinfo.b_print){
		mkdir_recursive(get_dirname(fname2.c_str()).c_str());
		fs_w.open(fname2.c_str(), std::ios::out|std::ios::binary);
		if(fs_w.fail()){return false;}
	}

	size64 readsize = 0;
	//static std::vector<char> buf;
	//const int bufsize=512*1024;
	//buf.resize(bufsize);
	const size_t bufsize=buffer.size();
	while(filesize ==-1 || readsize<filesize){
		size64 nextreadsize;
		if(filesize == -1){ // case ".gz",".Z",".bz2"
			//nextreadsize = sizeof(buf);
			nextreadsize=bufsize;
		}else{
			size64 nextreadsize64 = filesize-readsize;
			if(nextreadsize64 > bufsize){nextreadsize64 = bufsize;}
			nextreadsize = nextreadsize64;
			if(nextreadsize==0){
				Sleep(0);
			}
			// nextreadsize = (int)min(filesize-readsize, sizeof(buf));
		}
		if(nextreadsize==0){
			Sleep(0);
		}
		size64 n = file.read(&buffer[0],nextreadsize);
		readsize += n;
		if(cmdinfo.b_print){
			cmdinfo.output.write(&buffer[0],(size_t)n);	//TODO:size lost
		}else{
			fs_w.write(&buffer[0],n);
			if(fs_w.fail()){return false;}
		}
		if(n != nextreadsize){
			if(filesize == -1){ // case .gz/.Z/.bz2"
				break;
			}else{
				return false;
			}
		}
//		if(cmdinfo.hTar32StatusDialog){
			extractinfo.exinfo.dwWriteSize = (DWORD)readsize;
			exinfo64.exinfo.dwWriteSize = (DWORD)readsize;
			exinfo64.llWriteSize = readsize;
			int ret = SendArcMessage(cmdinfo, ARCEXTRACT_INPROCESS, &extractinfo,&exinfo64);
			if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
//		}
	}
	if(!cmdinfo.b_print){
		fs_w.close();
		struct _utimbuf ut;
		ut.actime = (stat.atime ? stat.atime : time(NULL));
		ut.modtime = (stat.mtime ? stat.mtime : time(NULL));
		int ret;
		ret = _utime(fname2.c_str(), &ut);
		ret = _chmod(fname2.c_str(), stat.mode);
	}
//	if(cmdinfo.hTar32StatusDialog){
		extractinfo.exinfo.dwWriteSize = (DWORD)readsize;
		exinfo64.exinfo.dwWriteSize = (DWORD)readsize;
		exinfo64.llWriteSize = readsize;
		int ret = SendArcMessage(cmdinfo, 6, &extractinfo,&exinfo64);
		if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);}
//	}
	return true;
}
Exemplo n.º 30
0
Arquivo: main.c Projeto: 11mariom/ekg2
static FILE* logs_open_file(char *path, int ff) {
	char fullname[PATH_MAX];
#ifdef HAVE_LIBZ
	int zlibmode = 0;
#endif
	if (ff != LOG_FORMAT_IRSSI && ff != LOG_FORMAT_SIMPLE && ff != LOG_FORMAT_XML && ff != LOG_FORMAT_RAW) {
		if (ff == LOG_FORMAT_NONE)
			debug("[logs] opening log file %s with ff == LOG_FORMAT_NONE CANCELLED\n", __(path), ff);
		else	debug("[logs] opening log file %s with ff == %d CANCELED\n", __(path), ff);
		return NULL;
	}

	debug("[logs] opening log file %s ff:%d\n", __(path), ff);

	if (!path) {
		errno = EACCES; /* = 0 ? */
		return NULL;
	}

	{	/* check if such file was already open SLOW :( */
		list_t l;

		for (l=log_logs; l; l = l->next) {
			logs_log_t *ll = l->data;
			log_window_t *lw;

			if (!ll || !(lw = ll->lw))
				continue;

/*			debug_error("here: %x [%s, %s] [%d %d]\n", lw->file, lw->path, path, lw->logformat, ff); */

			if (lw->file && lw->logformat == ff && !xstrcmp(lw->path, path)) {
				FILE *f = lw->file;
				lw->file = NULL;	/* simulate fclose() on this */
				return f;		/* simulate fopen() here */
			}
		}
	}

	if (mkdir_recursive(path, 0)) {
		print("directory_cant_create", path, strerror(errno));
		return NULL;
	}

	g_strlcpy(fullname, path, PATH_MAX);

	if (ff == LOG_FORMAT_IRSSI)		g_strlcat(fullname, ".log", PATH_MAX);
	else if (ff == LOG_FORMAT_SIMPLE)	g_strlcat(fullname, ".txt", PATH_MAX);
	else if (ff == LOG_FORMAT_XML)		g_strlcat(fullname, ".xml", PATH_MAX);
	else if (ff == LOG_FORMAT_RAW)		g_strlcat(fullname, ".raw", PATH_MAX);

#ifdef HAVE_LIBZ /* z log.c i starego ekg1. Wypadaloby zaimplementowac... */
	/* nawet je¶li chcemy gzipowane logi, a istnieje nieskompresowany log,
	 * olewamy kompresjê. je¶li loga nieskompresowanego nie ma, dodajemy
	 * rozszerzenie .gz i balujemy. */
	if (config_log & 4) {
		struct stat st;
		if (stat(fullname, &st) == -1) {
			gzFile f;

			if (!(f = gzopen(path, "a")))
				return NULL;

			gzputs(f, buf);
			gzclose(f);

			zlibmode = 1;
		}
	}
	if (zlibmode) {
		/* XXX, ustawic jakas flage... */
		g_strlcat(fullname, ".gz", PATH_MAX);
	}
#endif

	/* if xml, prepare xml file */
	if (ff == LOG_FORMAT_XML) {
		FILE *fdesc = fopen(fullname, "r+");
		if (!fdesc) {
			if (!(fdesc = fopen(fullname, "w+")))
				return NULL;
					/* XXX: what about old, locale-encoded logs? */
			fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", fdesc);
			fputs("<!DOCTYPE ekg2log PUBLIC \"-//ekg2log//DTD ekg2log 1.0//EN\" ", fdesc);
			fputs("\"http://www.ekg2.org/DTD/ekg2log.dtd\">\n", fdesc);
			fputs("<ekg2log xmlns=\"http://www.ekg2.org/DTD/\">\n", fdesc);
			fputs("</ekg2log>\n", fdesc);
		} 
		return fdesc;
	}

	return fopen(fullname, "a+");
}