Example #1
0
static void
prepare (void)
{
  char *dirbuf;
  char dir_name[] = "/tst-fts.XXXXXX";

  if (asprintf (&dirbuf, "%s%s", test_dir, dir_name) < 0)
    {
      puts ("out of memory");
      exit (1);
    }

  if (mkdtemp (dirbuf) == NULL)
    {
      puts ("cannot create temporary directory");
      exit (1);
    }

  add_temp_file (dirbuf);
  fts_test_dir = dirbuf;

  make_file ("12");
  make_file ("345");
  make_file ("6789");

  make_dir ("aaa");
  make_file ("aaa/1234");
  make_file ("aaa/5678");

  make_dir ("bbb");
  make_file ("bbb/1234");
  make_file ("bbb/5678");
  make_file ("bbb/90ab");
}
Example #2
0
/* Make a t_file reference to a stream. */
void
make_stream_file(ref * pfile, stream * s, const char *access)
{
    uint attrs =
	(access[1] == '+' ? a_write + a_read + a_execute : 0) |
	imemory_space((gs_ref_memory_t *) s->memory);

    if (access[0] == 'r') {
	make_file(pfile, attrs | (a_read | a_execute), s->read_id, s);
	s->write_id = 0;
    } else {
	make_file(pfile, attrs | a_write, s->write_id, s);
	s->read_id = 0;
    }
}
Example #3
0
int
install_stdin(void)
    /* install what we get through stdin */
{
    int tmp_fd = 0;
    FILE *tmp_file = NULL;
    char *tmp_str = NULL;
    int c;
    short return_val = EXIT_OK;
	    	    
    tmp_fd = temp_file(&tmp_str);
    
    if( (tmp_file = fdopen(tmp_fd, "w")) == NULL )
	die_e("Could not fdopen file %s", tmp_str);

    while ( (c = getc(stdin)) != EOF )
	putc(c, tmp_file);

    fclose(tmp_file);
    close(tmp_fd);

    if ( make_file(tmp_str) == ERR )
	goto exiterr;
    else
	goto exit;

  exiterr:
	return_val = EXIT_ERR;    
  exit:
    if ( remove(tmp_str) != 0 )
	error_e("Could not remove %s", tmp_str);
    free(tmp_str);
    return return_val;

}
Example #4
0
static int
stderr_open(gx_io_device * iodev, const char *access, stream ** ps,
	    gs_memory_t * mem)
{
    i_ctx_t *i_ctx_p = (i_ctx_t *)iodev->state;	/* see above */
    stream *s;

    if (!streq1(access, 'w'))
	return_error(e_invalidfileaccess);
    if (file_is_invalid(s, &ref_stderr)) {
	gs_memory_t *mem = imemory_system;
	byte *buf;

	s = file_alloc_stream(mem, "stderr_open(stream)");
	buf = gs_alloc_bytes(mem, STDERR_BUF_SIZE, "stderr_open(buffer)");
	if (s == 0 || buf == 0)
	    return_error(e_VMerror);
	swrite_file(s, gs_stderr, buf, STDERR_BUF_SIZE);
	s->save_close = s->procs.flush;
	s->procs.close = file_close_file;
	make_file(&ref_stderr, a_write | avm_system, s->write_id, s);
	*ps = s;
	return 1;
    }
    *ps = s;
    return 0;
}
Example #5
0
oyster *builtin_open(machine *m){
    ARG(name);
    FILE *in = fopen(string_of(name), "r");
    if (in == NULL)
        toss_signal(make_signal(make_string("File open failure!"), m), m);
    return make_file(in);
}
Example #6
0
static int
stdin_open(gx_io_device * iodev, const char *access, stream ** ps,
	   gs_memory_t * mem)
{
    i_ctx_t *i_ctx_p = (i_ctx_t *)iodev->state;	/* see above */
    stream *s;

    if (!streq1(access, 'r'))
	return_error(e_invalidfileaccess);
    if (file_is_invalid(s, &ref_stdin)) {
	/****** stdin SHOULD NOT LINE-BUFFER ******/
	gs_memory_t *mem = imemory_system;
	byte *buf;

	s = file_alloc_stream(mem, "stdin_open(stream)");
	/* We want stdin to read only one character at a time, */
	/* but it must have a substantial buffer, in case it is used */
	/* by a stream that requires more than one input byte */
	/* to make progress. */
	buf = gs_alloc_bytes(mem, STDIN_BUF_SIZE, "stdin_open(buffer)");
	if (s == 0 || buf == 0)
	    return_error(e_VMerror);
	sread_file(s, gs_stdin, buf, STDIN_BUF_SIZE);
	s->procs.process = s_stdin_read_process;
	s->save_close = s_std_null;
	s->procs.close = file_close_file;
	make_file(&ref_stdin, a_readonly | avm_system, s->read_id, s);
	*ps = s;
	return 1;
    }
    *ps = s;
    return 0;
}
Example #7
0
bool direction::create_file(std::string name)
{
	if (m_data.find(name) != m_data.end())
	{
		return false;
	}
	m_data[name] = make_file(name);
	return true;
}
Example #8
0
int main(int argc, char* argv[])
{
  if (argc < 5) usage("Too few parameters");
  if (argc > 7) usage("Too many parameters");
  logacct = getpwnam(argv[1]);
  maindir = argv[2];
  logdir = argv[3];
  if (maindir[0] != '/' || logdir[0] != '/')
    die1(1, "Directory names must start with /.");
  cvmpath = argv[4];
  if (argc > 5) {
    ip = argv[5];
    if (argc > 6) dochroot = argv[6];
  }
  if (!logacct) die1(1, "Unknown logacct user name");

  umask(0);

  if (mkdir(maindir, 0755) == -1) die1sys(1, "Error creating main directory");
  if (chmod(maindir, 01755) == -1)
    die1sys(1, "Error setting permissions on main directory");
  
  if (mkdir(logdir, 0700) == -1) die1sys(1, "Error creating log directory");
  if (chown(logdir, logacct->pw_uid, logacct->pw_gid) == -1)
    die1sys(1, "Error setting owner on log directory");

  if (chdir(maindir) == -1) die1sys(1, "Error changing to main directory");
  if (mkdir("log", 0755) == -1)
    die1sys(1, "Error creating log service directory");
  if (mkdir("env", 0755) == -1)
    die1sys(1, "Error creating env directory");

  start_file("run", 0755);
  obuf_put5s(&conf_out,
	     "#!/bin/sh\n"
	     "exec 2>&1\n"
	     "umask 022\n"
	     "exec \\\n"
	     "tcpserver -DRHv -llocalhost ", ip, " 21 \\\n"
	     "envdir ", maindir, "/env \\\n");
  obuf_put7s(&conf_out,
	     "softlimit -m 2000000 \\\n",
	     conf_bin, "/twoftpd-auth \\\n",
	     cvmpath, " \\\n",
	     conf_bin, "/twoftpd-xfer");
  end_file();

  make_file("log/run", 0755,
	    "#!/bin/sh\n"
	    "exec \\\n"
	    "setuidgid ", logacct->pw_name, " \\\n"
	    "multilog t ", logdir, 0, 0, 0);
  
  if (dochroot) make_fileu("env/CHROOT", 1);
  
  return 0;
}
Example #9
0
File: cpp.c Project: rui314/8cc-old
static File *open_header(CppContext *ctx, String *name, List *paths) {
    for (int i = 0; i < LIST_LEN(paths); i++) {
        String *path = construct_path((String *)LIST_REF(paths, i), name);
        FILE *stream = fopen(STRING_BODY(path), "r");
        if (!stream)
            continue;
        return make_file(stream, STRING_BODY(path));
    }
    error_cpp_ctx(ctx, "Cannot find header: '%s'", STRING_BODY(name));
}
Example #10
0
	int file_write_content(const std::string& path, const std::string& content)
	{
		make_file(path);
		FILE *fp;
		if ((fp = fopen(path.c_str(), "wb")) == NULL)
		{
			return -1;
		}
		fwrite(content.c_str(), 1, content.size(), fp);
		fclose(fp);
		return 0;
	}
Example #11
0
Translations::Translations()
: _translator(NULL)
, _multiTouchTranslator(NULL)
, _webTranslator(NULL)
{
	_translator = new QTranslator();
	QString locale; // = QLocale::system().name();
	winOS->LoadSettingsFile();
	locale = winOS->GetLocaleLanguage();

	// load the base translation file if there is one
	QString localeFileName = QString(QT_NT("BumpTop.%1.qm")).arg(locale);
	QString localeFile = native(make_file(winOS->GetLanguagesDirectory(), localeFileName));
	bool loaded = _translator->load(localeFile, native(winOS->GetExecutableDirectory()));
	assert(loaded);

	// load the multitouch override file if there is one
	int isTouchScreen = GetSystemMetrics(SM_TABLETPC);
	if (isTouchScreen)
	{
		_multiTouchTranslator = new QTranslator();
		localeFileName = QString(QT_NT("BumpTop_Multitouch.%1.qm")).arg(locale);
		localeFile = native(make_file(winOS->GetLanguagesDirectory(), localeFileName));
		if (exists(localeFile))
		{
			loaded = _multiTouchTranslator->load(localeFile, native(winOS->GetExecutableDirectory()));
			assert(loaded);
		}
	}

	// load the web-related translations
	_webTranslator = new QTranslator();
	localeFileName = QString(QT_NT("BumpTop_Web.%1.qm")).arg(locale);
	localeFile = native(make_file(winOS->GetLanguagesDirectory(), localeFileName));
	if (exists(localeFile))
	{
		loaded = _webTranslator->load(localeFile, native(winOS->GetExecutableDirectory()));
		assert(loaded);
	}
}
Example #12
0
void test_latex_link( latex_type * latex ) {
  const char * path = "/tmp/linkFarm";
  const char * file1 = util_alloc_filename( path , "File1" , NULL );
  const char * file2 = util_alloc_filename( path , "File2" , NULL );
  const char * file3 = util_alloc_filename( path , "File3" , NULL );
  

  util_make_path( path );
  make_file( file1 );
  make_file( file2 );
  make_file( file3 );
  
  latex_link_path( latex , path );
  latex_link_directory_content( latex , path );
  
  test_link( latex , "File1" , file1);
  test_link( latex , "File2" , file2);
  test_link( latex , "File3" , file3);
  test_link( latex , "linkFarm" , path);
  
  util_clear_directory( path , true , true );
}
Example #13
0
// Protokolldatei eröffnen ----------------------------------------------------
static void protocol_open (char *pFile) 
{
char cbProtocol[_MAX_PATH];

	make_file (cbProtocol, pFile, ".lst");

	if (fpProt)
		fclose (fpProt);		// evtl. vorherige Datei schließen

	fpProt = fopen (cbProtocol, "w");
	if (fpProt)
		setvbuf (fpProt, NULL, _IONBF, 0);	// Buffering ausschalten
}
Example #14
0
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  main
 *  Description: Recovers pictures from card.raw, solution to pset 5 from Harvard's CS50
 * =====================================================================================
 */
    int
main ( int argc, char *argv[] )
{
    
    // open file card.raw to read data
    FILE *fp = fopen("card.raw", "r");
    if(fp == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    //int to hold value for sequential filenames 
    int num = 0;

    //allocate space for buffer to hold 512 byte blocks and next block
    BYTE buffer[512];
    
    //sequence through filenames and open files for writing
    while(fread(buffer, sizeof(BYTE), 512, fp) != 0)
    {
        while(isJpeg(buffer))
        {
            // create outfile 
            FILE *outfile = make_file(num);
            
            // write out jpeg to outfile
            fwrite(buffer, sizeof(BYTE), 512, outfile);
            
            // read next block checking for eof 
            if(fread(buffer, sizeof(BYTE), 512, fp) == 0)
                break;
            
            // while next block isnt the start of new jpeg keep writing
            while(!isJpeg(buffer))
            {
                fwrite(buffer, sizeof(BYTE), 512, outfile);
                if(fread(buffer, sizeof(BYTE), 512, fp) == 0)
                    break;
            }

            // close outfile 
            fclose(outfile);
            num++;
        }
        
    }
    // close file pointer 
    fclose(fp);
    return EXIT_SUCCESS;
}			
Example #15
0
 static void reopen_default_logfile()
 {
     if (!kLogFilePath.empty())
     {
         make_file(kLogFilePath);
         kLogFile = fopen(kLogFilePath.c_str(), "a+");
         if (NULL == kLogFile)
         {
             kLogFile = stdout;
             WARN_LOG("Failed to open log file:%s, use stdout instead.");
             return;
         }
     }
 }
Example #16
0
/* The string must be allocated in non-garbage-collectable (foreign) space. */
int
file_read_string(const byte *str, uint len, ref *pfile, gs_ref_memory_t *imem)
{
    stream *s = file_alloc_stream((gs_memory_t *)imem, "file_read_string");

    if (s == 0)
	return_error(e_VMerror);
    sread_string(s, str, len);
    s->foreign = 1;
    s->write_id = 0;
    make_file(pfile, a_readonly | imemory_space(imem), s->read_id, s);
    s->save_close = s->procs.close;
    s->procs.close = file_close_disable;
    return 0;
}
Example #17
0
int main(int argc, char* argv[])
{
  if ((ip = getenv("TCPREMOTEIP")) == 0 || (ip = validate_ip(ip)) == 0)
    die1(111, "Must be run from tcp-env or tcpserver.");
  if ((dir = getenv("RELAY_CTRL_DIR")) == 0)
    warn1("$RELAY_CTRL_DIR is not set.");
  else
    if (is_authenticated())
      make_file(ip, argc > 1);

  if (argc > 1) {
    execvp(argv[1], argv+1);
    return 111;
  }
  return 0;
}
void
testDeepScanLineMultipleRead()
{
    
    cout << "\n\nTesting random re-reads from deep scanline file:\n" << endl;
    
    
    srand(1);
    
    make_file(source_filename);
    read_file(source_filename);
    remove(source_filename);
    
    cout << " ok\n" << endl;
    
}
Example #19
0
main(int argc, char *argv[])
{
	int fd;

	use_lod2 = 0;
//	use_lod2 = 1;

	img_filename = strdup("disk.img");
	mcr_filename = strdup("ucadr.mcr.841");
	lod1_filename = strdup("partition-78.48.lod1");
	lod2_filename = strdup("partition-sys210.lod2");

#if 0
	mcr_filename = strdup("ucadr.mcr.979");
#endif

#if 0
	use_lod2 = 1;
	mcr_filename = strdup("ucadr.mcr.979");
	lod1_filename = strdup("partition-sys210.lod2");
#endif

#if 0
	use_lod2 = 1;
	mcr_filename = strdup("ucadr.mcr.896");
	lod1_filename = strdup("partition-sys210.lod2");
#endif

	fd = open(img_filename, O_RDWR | O_CREAT, 0666);
	if (fd < 0) {
		perror(img_filename);
		exit(1);
	}

	make_labl(fd);
	make_mcr1(fd);
make_page(fd);
	make_lod1(fd);
	if (use_lod2) {
		make_lod2(fd);
	}
	make_file(fd);

	exit(0);
}
Example #20
0
static void init_sysfs(void)
{
    if (fakerootdir && fakesysfscgroupdir)
        return;

    if (!(fakerootdir = getenv("LIBVIRT_FAKE_ROOT_DIR"))) {
        fprintf(stderr, "Missing LIBVIRT_FAKE_ROOT_DIR env variable\n");
        abort();
    }

    if (virAsprintfQuiet(&fakesysfscgroupdir, "%s%s",
                         fakerootdir, SYSFS_CGROUP_PREFIX) < 0)
        abort();

    if (virFileMakePath(fakesysfscgroupdir) < 0) {
        fprintf(stderr, "Cannot create %s\n", fakesysfscgroupdir);
        abort();
    }

# define MAKE_CONTROLLER(subpath)                                      \
    do {                                                               \
        char *path;                                                    \
        if (asprintf(&path, "%s/%s", fakesysfscgroupdir, subpath) < 0) \
            abort();                                                   \
        if (make_controller(path, 0755) < 0) {                         \
            fprintf(stderr, "Cannot initialize %s\n", path);           \
            free(path);                                                \
            abort();                                                   \
        }                                                              \
        free(path);                                                    \
    } while (0)

    MAKE_CONTROLLER("cpu");
    MAKE_CONTROLLER("cpuacct");
    MAKE_CONTROLLER("cpu,cpuacct");
    MAKE_CONTROLLER("cpu,cpuacct/system");
    MAKE_CONTROLLER("cpuset");
    MAKE_CONTROLLER("blkio");
    MAKE_CONTROLLER("memory");
    MAKE_CONTROLLER("freezer");

    if (make_file(fakesysfscgroupdir,
                  SYSFS_CPU_PRESENT_MOCKED, "8-23,48-159\n") < 0)
        abort();
}
int main()
{
    setlocale(LC_ALL, "Russian");
    printf("This is assorting of %s\n", FILEREAD);
    int len = 0;
    char* buffer;
    if (readfileD(FILEREAD, &buffer, &len))
    {
        printf("INPUT ERROR\n");
    }
    int nline = 0;
    char** text = split_linesD(buffer, len, &nline);
    simplesort(text, nline);
    make_file(FILEWRITE, text, nline);
    free(text[0]);
    free(text);
    return OK;
}
Example #22
0
/* Write a buffer to stdout, potentially writing to callback */
static int
s_stdout_write_process(stream_state * st, stream_cursor_read * ignore_pr,
		     stream_cursor_write * pw, bool last)
{
    uint count = pr->limit - pr->ptr;
    int written;

    if (count == 0) 
	return 0;
    written = outwrite(st->memory, pr->ptr + 1, count);
    if (written < count) {
	return ERRC;
    pr->ptr += written;
    return 0;
}

static int
stdout_open(gx_io_device * iodev, const char *access, stream ** ps,
	    gs_memory_t * mem)
{
    i_ctx_t *i_ctx_p = (i_ctx_t *)iodev->state;	/* see above */
    stream *s;

    if (!streq1(access, 'w'))
	return_error(e_invalidfileaccess);
    if (file_is_invalid(s, &ref_stdout)) {
	gs_memory_t *mem = imemory_system;
	byte *buf;

	s = file_alloc_stream(mem, "stdout_open(stream)");
	buf = gs_alloc_bytes(mem, STDOUT_BUF_SIZE, "stdout_open(buffer)");
	if (s == 0 || buf == 0)
	    return_error(e_VMerror);
	swrite_file(s, gs_stdout, buf, STDOUT_BUF_SIZE);
	s->save_close = s->procs.flush;
	s->procs.close = file_close_file;
	s->procs.process = s_stdout_write_process;
	make_file(&ref_stdout, a_write | avm_system, s->write_id, s);
	*ps = s;
	return 1;
    }
    *ps = s;
    return 0;
}
Example #23
0
//Analogous to getUniqueNewFolderPathInWorkingDirectory, this function returns a unique file path using the parameter as a template
QFileInfo FileSystemManager::getUniqueNewFilePathInWorkingDirectory(QString fileName) {
	QFileInfo newFile;
	int file_extension_division = fileName.lastIndexOf(".");
	QString ext = fileName.mid(file_extension_division,fileName.size()-file_extension_division);
	QString fileBase = fileName.mid(0,file_extension_division);
	QString oldBase = fileBase;
	int x = 1;
	do
	{
		QString counter = QString::number(x);
		fileBase.append(counter);
		fileBase.append(ext);
		newFile = make_file(GLOBAL(getWorkingDirectory()), fileBase);
		fileBase = oldBase;
		x++;
	} 
	while (exists(newFile));

	return newFile;
}
Example #24
0
int
main(int argc, char **argv)
{
    char **env = NULL;
    int count = 0;
    char fn[MAXPATHLEN];
    int error = 0;

    make_file(fn, sizeof(fn));

    write_file(fn, s1);
    count = read_environment(fn, &env);
    if(count != 3) {
	warnx("test 1: variable count %d != 3", count);
	error++;
    }

    write_file(fn, s2);
    count = read_environment(fn, &env);
    if(count != 1) {
	warnx("test 2: variable count %d != 1", count);
	error++;
    }

    unlink(fn);
    count = read_environment(fn, &env);
    if(count != 0) {
	warnx("test 3: variable count %d != 0", count);
	error++;
    }
    for(count = 0; env && env[count]; count++);
    if(count != 3) {
	warnx("total variable count %d != 3", count);
	error++;
    }
    free_environment(env);


    return error;
}
void FlickrPhotoFrameSource::onSourceUpdate(const FileTransfer& transfer)
{
	vector<PhotoFrameSourceItem> items;

	// extract the urls froms the transfer result and create associated
	// photo frame source items
	FlickrClient flickrClient(FLICKR_AUTH_TOKEN);
	vector<QString> urls = flickrClient.extractPhotoUrls(transfer);
	for (int i = 0; i < urls.size(); i++)
	{
		PhotoFrameSourceItem item(urls[i]);			
		//convertToValidDirectoryName(urls[i]);
		QString url = urls[i];
		url = url.right(url.size() - url.lastIndexOf("/") - 1);
		QString localFileName = native(make_file(_localCacheDirectory, url));
		item.setTexturePath(localFileName);
		items.push_back(item);
	}
	
	// set the new items and increment update count
	_items = items;
	++_sourceUpdateCount;
}
static u32 build_default_directory_structure()
{
	u32 inode;
	u32 root_inode;
	struct dentry dentries = {
			.filename = "lost+found",
			.file_type = EXT4_FT_DIR,
			.mode = S_IRWXU,
			.uid = 0,
			.gid = 0,
			.mtime = 0,
	};
	root_inode = make_directory(0, 1, &dentries, 1);
	inode = make_directory(root_inode, 0, NULL, 0);
	*dentries.inode = inode;
	inode_set_permissions(inode, dentries.mode,
		dentries.uid, dentries.gid, dentries.mtime);

	return root_inode;
}

#ifndef USE_MINGW
/* Read a local directory and create the same tree in the generated filesystem.
   Calls itself recursively with each directory in the given directory */
static u32 build_directory_structure(const char *full_path, const char *dir_path,
		u32 dir_inode, fs_config_func_t fs_config_func,
		struct selabel_handle *sehnd)
{
	int entries = 0;
	struct dentry *dentries;
	struct dirent **namelist = NULL;
	struct stat stat;
	int ret;
	int i;
	u32 inode;
	u32 entry_inode;
	u32 dirs = 0;
	bool needs_lost_and_found = false;

	if (full_path) {
		entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
		if (entries < 0) {
			error_errno("scandir");
			return EXT4_ALLOCATE_FAILED;
		}
	}

	if (dir_inode == 0) {
		/* root directory, check if lost+found already exists */
		for (i = 0; i < entries; i++)
			if (strcmp(namelist[i]->d_name, "lost+found") == 0)
				break;
		if (i == entries)
			needs_lost_and_found = true;
	}

	dentries = calloc(entries, sizeof(struct dentry));
	if (dentries == NULL)
		critical_error_errno("malloc");

	for (i = 0; i < entries; i++) {
		dentries[i].filename = strdup(namelist[i]->d_name);
		if (dentries[i].filename == NULL)
			critical_error_errno("strdup");

		asprintf(&dentries[i].path, "%s/%s", dir_path, namelist[i]->d_name);
		asprintf(&dentries[i].full_path, "%s/%s", full_path, namelist[i]->d_name);

		free(namelist[i]);

		ret = lstat(dentries[i].full_path, &stat);
		if (ret < 0) {
			error_errno("lstat");
			i--;
			entries--;
			continue;
		}

		dentries[i].size = stat.st_size;
		dentries[i].mode = stat.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
		dentries[i].mtime = stat.st_mtime;
		if (fs_config_func != NULL) {
#ifdef ANDROID
			unsigned int mode = 0;
			unsigned int uid = 0;
			unsigned int gid = 0;
			int dir = S_ISDIR(stat.st_mode);
			fs_config_func(dentries[i].path, dir, &uid, &gid, &mode);
			dentries[i].mode = mode;
			dentries[i].uid = uid;
			dentries[i].gid = gid;
#else
			error("can't set android permissions - built without android support");
#endif
		}
#ifdef HAVE_SELINUX
		if (sehnd) {
			char *sepath = NULL;
			asprintf(&sepath, "/%s", dentries[i].path);
			if (selabel_lookup(sehnd, &dentries[i].secon, sepath, stat.st_mode) < 0) {
				error("cannot lookup security context for %s", sepath);
			}
			if (dentries[i].secon)
				printf("Labeling %s as %s\n", sepath, dentries[i].secon);
			free(sepath);
		}
#endif

		if (S_ISREG(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_REG_FILE;
		} else if (S_ISDIR(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_DIR;
			dirs++;
		} else if (S_ISCHR(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_CHRDEV;
		} else if (S_ISBLK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_BLKDEV;
		} else if (S_ISFIFO(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_FIFO;
		} else if (S_ISSOCK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_SOCK;
		} else if (S_ISLNK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_SYMLINK;
			dentries[i].link = calloc(info.block_size, 1);
			readlink(dentries[i].full_path, dentries[i].link, info.block_size - 1);
		} else {
			error("unknown file type on %s", dentries[i].path);
			i--;
			entries--;
		}
	}
	free(namelist);

	if (needs_lost_and_found) {
		/* insert a lost+found directory at the beginning of the dentries */
		struct dentry *tmp = calloc(entries + 1, sizeof(struct dentry));
		memset(tmp, 0, sizeof(struct dentry));
		memcpy(tmp + 1, dentries, entries * sizeof(struct dentry));
		dentries = tmp;

		dentries[0].filename = strdup("lost+found");
		asprintf(&dentries[0].path, "%s/lost+found", dir_path);
		dentries[0].full_path = NULL;
		dentries[0].size = 0;
		dentries[0].mode = S_IRWXU;
		dentries[0].file_type = EXT4_FT_DIR;
		dentries[0].uid = 0;
		dentries[0].gid = 0;
#ifdef HAVE_SELINUX
		if (sehnd) {
			char *sepath = NULL;
			asprintf(&sepath, "/%s", dentries[0].path);
			if (selabel_lookup(sehnd, &dentries[0].secon, sepath, dentries[0].mode) < 0)
				error("cannot lookup security context for %s", dentries[0].path);
			free(sepath);
		}
#endif
		entries++;
		dirs++;
	}

	inode = make_directory(dir_inode, entries, dentries, dirs);

	for (i = 0; i < entries; i++) {
		if (dentries[i].file_type == EXT4_FT_REG_FILE) {
			entry_inode = make_file(dentries[i].full_path, dentries[i].size);
		} else if (dentries[i].file_type == EXT4_FT_DIR) {
			entry_inode = build_directory_structure(dentries[i].full_path,
					dentries[i].path, inode, fs_config_func, sehnd);
		} else if (dentries[i].file_type == EXT4_FT_SYMLINK) {
			entry_inode = make_link(dentries[i].full_path, dentries[i].link);
		} else {
			error("unknown file type on %s", dentries[i].path);
			entry_inode = 0;
		}
		*dentries[i].inode = entry_inode;

		ret = inode_set_permissions(entry_inode, dentries[i].mode,
			dentries[i].uid, dentries[i].gid,
			dentries[i].mtime);
		if (ret)
			error("failed to set permissions on %s\n", dentries[i].path);
		ret = inode_set_selinux(entry_inode, dentries[i].secon);
		if (ret)
			error("failed to set SELinux context on %s\n", dentries[i].path);

		free(dentries[i].path);
		free(dentries[i].full_path);
		free(dentries[i].link);
		free((void *)dentries[i].filename);
		free(dentries[i].secon);
	}

	free(dentries);
	return inode;
}
Example #27
0
bool FileSystemManager::moveFilesXP(vector<FileSystemActor *>& objList, QString& destDir, vector<FileSystemActor *>& failedObj, vector<FileSystemActor*>& replacedObj)
{
	SHFILEOPSTRUCT fileOperation = { 0 };
	QString toPath(destDir);
	set<FileSystemActor *> duplicateExists;

	TCHAR * fromPaths = allocateStringFromPathsArray(objList);
	TCHAR * fromPathsOffset = fromPaths;

	for (uint i = 0; i < objList.size(); i++)
	{
		FileSystemActor *fsData = objList[i];
		
		if (!isValidFileName(fsData->getFullPath()))
		{
			failedObj = objList;
			delete fromPaths;
			return false;
		}

		// build the from-path string
		lstrcpy(fromPathsOffset, (LPCTSTR) fsData->getFullPath().utf16());
		fromPathsOffset += fsData->getFullPath().size() + 1;

		// save the set of items that have duplicate names, so that we
		// can reference them if the move fails
		QDir destP(destDir);
		if (isValidFileName(native(make_file(destDir, filename(fsData->getFullPath())))))
			duplicateExists.insert(fsData);
	}

	TCHAR newp[MAX_PATH] = {0};
	lstrcpy(newp, (LPCTSTR) toPath.utf16());

	fileOperation.hwnd = winOS->GetWindowsHandle();
	fileOperation.wFunc = FO_MOVE;
	fileOperation.pFrom = fromPaths;
	fileOperation.pTo = newp;
	fileOperation.fFlags = FOF_ALLOWUNDO;

	// Do the windows file operations for Move
	bool succeeded = (SHFileOperation(&fileOperation) == 0) && !fileOperation.fAnyOperationsAborted;

	for (uint i = 0; i < objList.size(); i++)
	{
		FileSystemActor * fsData = objList[i];

		QFileInfo p(fsData->getFullPath());
		QFileInfo destP = make_file(destDir, p.fileName());

		// Determine which files failed and which replaced existing ones
		if (isValidFileName(fsData->getFullPath()))
		{
			failedObj.push_back(fsData);
		}
		else if (duplicateExists.find(fsData) != duplicateExists.end())
		{
			replacedObj.push_back(fsData);
		}
	}

	delete fromPaths;
	return succeeded;
}
Example #28
0
/* Make an invalid file object. */
void
make_invalid_file(ref * fp)
{
    make_file(fp, avm_invalid_file_entry, ~0, invalid_file_entry);
}
Example #29
0
/* Read a local directory and create the same tree in the generated filesystem.
   Calls itself recursively with each directory in the given directory.
   full_path is an absolute or relative path, with a trailing slash, to the
   directory on disk that should be copied, or NULL if this is a directory
   that does not exist on disk (e.g. lost+found).
   dir_path is an absolute path, with trailing slash, to the same directory
   if the image were mounted at the specified mount point */
static u32 build_directory_structure(const char *full_path, const char *dir_path,
		u32 dir_inode, fs_config_func_t fs_config_func,
		int verbose, time_t fixed_time)
{
	int entries = 0;
	struct dentry *dentries;
	struct dirent **namelist = NULL;
	struct stat stat;
	int ret;
	int i;
	u32 inode;
	u32 entry_inode;
	u32 dirs = 0;
	bool needs_lost_and_found = false;

    /* alphasort is locale-dependent; let's fix the locale to some sane value */
    setlocale(LC_ALL, "C");

	if (full_path) {
		entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
		if (entries < 0) {
#ifdef __GLIBC__
			/* The scandir function implemented in glibc has a bug that makes it
			   erroneously fail with ENOMEM under certain circumstances.
			   As a workaround we can retry the scandir call with the same arguments.
			   GLIBC BZ: https://sourceware.org/bugzilla/show_bug.cgi?id=17804 */
			if (errno == ENOMEM)
				entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
#endif
			if (entries < 0) {
				error_errno("scandir");
				return EXT4_ALLOCATE_FAILED;
			}
		}
	}

	if (dir_inode == 0) {
		/* root directory, check if lost+found already exists */
		for (i = 0; i < entries; i++)
			if (strcmp(namelist[i]->d_name, "lost+found") == 0)
				break;
		if (i == entries)
			needs_lost_and_found = true;
	}

	dentries = calloc(entries, sizeof(struct dentry));
	if (dentries == NULL)
		critical_error_errno("malloc");

	for (i = 0; i < entries; i++) {
		dentries[i].filename = strdup(namelist[i]->d_name);
		if (dentries[i].filename == NULL)
			critical_error_errno("strdup");

		asprintf(&dentries[i].path, "%s%s", dir_path, namelist[i]->d_name);
		asprintf(&dentries[i].full_path, "%s%s", full_path, namelist[i]->d_name);

		free(namelist[i]);

		ret = lstat(dentries[i].full_path, &stat);
		if (ret < 0) {
			error_errno("lstat");
			i--;
			entries--;
			continue;
		}

		dentries[i].size = stat.st_size;
		dentries[i].mode = stat.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
		if (fixed_time == -1) {
			dentries[i].mtime = stat.st_mtime;
		} else {
			dentries[i].mtime = fixed_time;
		}
		uint64_t capabilities;
		if (fs_config_func != NULL) {
			unsigned int mode = 0;
			unsigned int uid = 0;
			unsigned int gid = 0;
			int dir = S_ISDIR(stat.st_mode);
			if (fs_config_func(dentries[i].path, dir, &uid, &gid, &mode, &capabilities)) {
				dentries[i].mode = mode;
				dentries[i].uid = uid;
				dentries[i].gid = gid;
				dentries[i].capabilities = capabilities;
			}
		}

		if (S_ISREG(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_REG_FILE;
		} else if (S_ISDIR(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_DIR;
			dirs++;
		} else if (S_ISCHR(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_CHRDEV;
		} else if (S_ISBLK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_BLKDEV;
		} else if (S_ISFIFO(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_FIFO;
		} else if (S_ISSOCK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_SOCK;
		} else if (S_ISLNK(stat.st_mode)) {
			dentries[i].file_type = EXT4_FT_SYMLINK;
			dentries[i].link = calloc(info.block_size, 1);
			readlink(dentries[i].full_path, dentries[i].link, info.block_size - 1);
		} else {
			error("unknown file type on %s", dentries[i].path);
			i--;
			entries--;
		}
	}
	free(namelist);

	if (needs_lost_and_found) {
		/* insert a lost+found directory at the beginning of the dentries */
		struct dentry *tmp = calloc(entries + 1, sizeof(struct dentry));
		memset(tmp, 0, sizeof(struct dentry));
		memcpy(tmp + 1, dentries, entries * sizeof(struct dentry));
		dentries = tmp;

		dentries[0].filename = strdup("lost+found");
		asprintf(&dentries[0].path, "%slost+found", dir_path);
		dentries[0].full_path = NULL;
		dentries[0].size = 0;
		dentries[0].mode = S_IRWXU;
		dentries[0].file_type = EXT4_FT_DIR;
		dentries[0].uid = 0;
		dentries[0].gid = 0;
		entries++;
		dirs++;
	}

	inode = make_directory(dir_inode, entries, dentries, dirs);

	for (i = 0; i < entries; i++) {
		if (dentries[i].file_type == EXT4_FT_REG_FILE) {
			entry_inode = make_file(dentries[i].full_path, dentries[i].size);
		} else if (dentries[i].file_type == EXT4_FT_DIR) {
			char *subdir_full_path = NULL;
			char *subdir_dir_path;
			if (dentries[i].full_path) {
				ret = asprintf(&subdir_full_path, "%s/", dentries[i].full_path);
				if (ret < 0)
					critical_error_errno("asprintf");
			}
			ret = asprintf(&subdir_dir_path, "%s/", dentries[i].path);
			if (ret < 0)
				critical_error_errno("asprintf");
			entry_inode = build_directory_structure(subdir_full_path,
					subdir_dir_path, inode, fs_config_func, verbose, fixed_time);
			free(subdir_full_path);
			free(subdir_dir_path);
		} else if (dentries[i].file_type == EXT4_FT_SYMLINK) {
			entry_inode = make_link(dentries[i].link);
		} else if (dentries[i].file_type == EXT4_FT_CHRDEV ||
		           dentries[i].file_type == EXT4_FT_BLKDEV ||
		           dentries[i].file_type == EXT4_FT_SOCK ||
		           dentries[i].file_type == EXT4_FT_FIFO) {
			entry_inode = make_special(dentries[i].full_path);
		} else {
			error("unknown file type on %s", dentries[i].path);
			entry_inode = 0;
		}
		*dentries[i].inode = entry_inode;

		ret = inode_set_permissions(entry_inode, dentries[i].mode,
			dentries[i].uid, dentries[i].gid,
			dentries[i].mtime);
		if (ret)
			error("failed to set permissions on %s\n", dentries[i].path);

		ret = inode_set_capabilities(entry_inode, dentries[i].capabilities);
		if (ret)
			error("failed to set capability on %s\n", dentries[i].path);

		free(dentries[i].path);
		free(dentries[i].full_path);
		free(dentries[i].link);
		free((void *)dentries[i].filename);
	}

	free(dentries);
	return inode;
}
Example #30
0
/* Make an invalid file object. */
void
make_invalid_file(i_ctx_t *i_ctx_p, ref * fp)
{
    make_file(fp, avm_invalid_file_entry, ~0, i_ctx_p->invalid_file_stream);
}