Example #1
0
List* ReadDirectory(char* name, List* l){
	DIR* rep = NULL;
	struct dirent* current;
	
	
	if ( (rep=opendir(name)) == NULL){
		printf("Error\n");
		
		return NULL;
	}
	
	while ((current = readdir(rep)) != NULL){
		struct stat stats; 
		
		if(strcmp(current->d_name, ".") && strcmp(current->d_name, ".."))
		{	
			char* path = Path(name,current->d_name);
    		
    		stat(path, &stats);
           	
           	if(S_ISDIR(stats.st_mode)){
           		
           		char temp[MAX_LENGTH] = "";
           		
           		strncpy(temp,path,MAX_LENGTH);
           		
           		printf("%s \n", temp);
           		
           		l = ReadDirectory(temp,l);
           	}
		
			else {
				if (test_file(current->d_name) == 0){
					
					char temp[MAX_LENGTH] = "";
					
					strncpy(temp,path,MAX_LENGTH);
					
					printf("%s\n", temp);
					
					l = add_file(l,current->d_name,temp);	
				}
			}
		}
		
	}
	closedir(rep);
	
	return l;
}
Example #2
0
/*
 * ReadDirectory
 * Read directory tree into memory structure
 * returns first (dummy) node
 */
TreeNode *ReadDirectory(TreeNode *node, char *path)
{
	//printf("%s\n", path);

	DIR *dir = opendir(path);
	if (!dir) { fprintf(stderr, "Cannot open directory '%s'.\n", path); exit(1); }

	struct dirent *de;
	while ((de = readdir(dir)))
	{
		if (!strcmp(de->d_name, ".")) continue;
		if (!strcmp(de->d_name, "..")) continue;

		char strbuf[MAXPATHLEN];
		strcpy(strbuf, path);
		strcat(strbuf, "/");
		strcat(strbuf, de->d_name);
		//printf("%s\n", strbuf);

		struct stat st;
		if (stat(strbuf, &st)) { fprintf(stderr, "Cannot get stat of '%s'.\n", strbuf); exit(1); }

		//if (S_ISDIR(st.st_mode) && !subdirs) continue;		// skip subdirectories

		total_name_size += strlen(de->d_name);

		if (S_ISDIR(st.st_mode))
		{
			node = node->New(de->d_name, true);
			node->dir_id = free_dir_id++;
			directory_count++;
			node->directory = ReadDirectory(new TreeNode(), strbuf);
		}
		else if (S_ISREG(st.st_mode))
		{
			node = node->New(de->d_name, false);
			file_count++;
		}
		else
		{
			fprintf(stderr, "'%s' is not a file or directory!\n", strbuf);
			exit(1);
		}
	}
	closedir(dir);

	while (node->prev) node = node->prev;	// return first
	return node;
}
void PanelView::Reload(void)
////////////////////////////////////////////////////////////////////////
{
	switch (m_PanelMode)
	{
		case PM_NORMAL:
			ClearFileList();
			ReadDirectory();
			break;
		case PM_DISKS:
			ClearFileList();
			ReadDisks();
			break;
	}
}
void PanelView::Reload(const char *itemname)
////////////////////////////////////////////////////////////////////////
{
	switch (m_PanelMode)
	{
		case PM_NORMAL:
			ClearFileList();
			ReadDirectory(itemname);
			break;
		case PM_DISKS:
			ClearFileList();
			ReadDisks();
			break;
	}
}
Example #5
0
ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevice, std::string _restrictPath) 
{
	if (!_restrictPath.empty())
	{
		size_t pos = _restrictPath.find_first_not_of('/');
		while (pos != _restrictPath.npos)
		{
			size_t endPos = _restrictPath.find_first_of('/', pos);
			if (endPos == _restrictPath.npos)
				endPos = _restrictPath.length();
			if (pos != endPos)
				restrictTree.push_back(_restrictPath.substr(pos, endPos - pos));
			pos = _restrictPath.find_first_not_of('/', endPos);
		}
	}

	blockDevice = _blockDevice;
	hAlloc = _hAlloc;

	VolDescriptor desc;
	blockDevice->ReadBlock(16, (u8*)&desc);

	entireISO.name = "";
	entireISO.isDirectory = false;
	entireISO.startingPosition = 0;
	entireISO.size = _blockDevice->GetNumBlocks();
	entireISO.flags = 0;
	entireISO.parent = NULL;

	treeroot = new TreeEntry();
	treeroot->isDirectory = true;
	treeroot->startingPosition = 0;
	treeroot->size = 0;
	treeroot->flags = 0;
	treeroot->parent = NULL;

	if (memcmp(desc.cd001, "CD001", 5)) {
		ERROR_LOG(FILESYS, "ISO looks bogus? Giving up...");
		return;
	}

	u32 rootSector = desc.root.firstDataSector();
	u32 rootSize = desc.root.dataLength();

	ReadDirectory(rootSector, rootSize, treeroot, 0);
}
Example #6
0
NS_IMETHODIMP
nsJARInputStream::Read(char* aBuffer, PRUint32 aCount, PRUint32 *aBytesRead)
{
    NS_ENSURE_ARG_POINTER(aBuffer);
    NS_ENSURE_ARG_POINTER(aBytesRead);

    *aBytesRead = 0;

    nsresult rv = NS_OK;
    if (mClosed)
        return rv;

    if (mDirectory) {
        rv = ReadDirectory(aBuffer, aCount, aBytesRead);
    } else {
        if (mInflate) {
            rv = ContinueInflate(aBuffer, aCount, aBytesRead);
        } else {
            PRInt32 bytesRead = 0;
            aCount = PR_MIN(aCount, mInSize - mCurPos);
            if (aCount) {
                bytesRead = PR_Read(mFd, aBuffer, aCount);
                if (bytesRead < 0)
                    return NS_ERROR_FILE_CORRUPTED;
                mCurPos += bytesRead;
                if (bytesRead != aCount) {
                    // file is truncated or was lying about size, we're done
                    PR_Close(mFd);
                    mFd = nsnull;
                    return NS_ERROR_FILE_CORRUPTED;
                }
            }
            *aBytesRead = bytesRead;
        }

        // be aggressive about closing!
        // note that sometimes, we will close mFd before we've finished
        // deflating - this is because zlib buffers the input
        // So, don't free the ReadBuf/InflateStruct yet.
        if (mCurPos >= mInSize && mFd) {
            PR_Close(mFd);
            mFd = nsnull;
        }
    }
    return rv;
}
void PanelView::GotoParent(void)
////////////////////////////////////////////////////////////////////////
{
	// To set the cursor to the child entry where we came from...
	BString oldpath;
	SetPanelMode(PM_NORMAL);
	oldpath.SetTo(m_Path.String());
	oldpath.Remove(0,oldpath.FindLast('/')+1);
	
	BPath path((const char *)m_Path.String());
	
	if (path.GetParent(&path)==B_OK)
		m_Path.SetTo(path.Path());

	SetPathStringView();
	ClearFileList();
	ReadDirectory(oldpath.String());
}
Example #8
0
static void
dump(int fd, uint32 diroff)
{
	unsigned i;

	lseek(fd, (off_t) 0, 0);
	if (read(fd, (char*) &hdr, sizeof (hdr)) != sizeof (hdr))
		ReadError("TIFF header");
	/*
	 * Setup the byte order handling.
	 */
	if (hdr.tiff_magic != TIFF_BIGENDIAN && hdr.tiff_magic != TIFF_LITTLEENDIAN)
		Fatal("Not a TIFF file, bad magic number %u (%#x)",
		    hdr.tiff_magic, hdr.tiff_magic);
	InitByteOrder(hdr.tiff_magic);
	/*
	 * Swap header if required.
	 */
	if (swabflag) {
		TIFFSwabShort(&hdr.tiff_version);
		TIFFSwabLong(&hdr.tiff_diroff);
	}
	/*
	 * Now check version (if needed, it's been byte-swapped).
	 * Note that this isn't actually a version number, it's a
	 * magic number that doesn't change (stupid).
	 */
	if (hdr.tiff_version != TIFF_VERSION)
		Fatal("Not a TIFF file, bad version number %u (%#x)",
		    hdr.tiff_version, hdr.tiff_version); 
	printf("Magic: %#x <%s-endian> Version: %#x\n",
	    hdr.tiff_magic,
	    hdr.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
	    hdr.tiff_version);
	if (diroff == 0)
	    diroff = hdr.tiff_diroff;
	for (i = 0; diroff != 0; i++) {
		if (i > 0)
			putchar('\n');
		diroff = ReadDirectory(fd, i, diroff);
	}
}
void PanelView::Reload(int index)
////////////////////////////////////////////////////////////////////////
{
	switch (m_PanelMode)
	{
		case PM_NORMAL:
			ClearFileList();
			ReadDirectory();
			if (index > (m_CustomListView->IndexOf(m_CustomListView->LastItem())))
				index = m_CustomListView->IndexOf(m_CustomListView->LastItem());
			
			m_CustomListView->Select(index,false);	// false -> remove previously selected item(s)...
			break;
		case PM_DISKS:
			ClearFileList();
			ReadDisks();
			m_CustomListView->Select(index,false);	// false -> remove previously selected item(s)...
			break;
	}
}
Example #10
0
ReturnCode ES::DeleteTicket(const u8* ticket_view)
{
  const auto fs = m_ios.GetFS();
  const u64 title_id = Common::swap64(ticket_view + offsetof(IOS::ES::TicketView, title_id));

  if (!CanDeleteTitle(title_id))
    return ES_EINVAL;

  auto ticket = FindSignedTicket(title_id);
  if (!ticket.IsValid())
    return FS_ENOENT;

  const u64 ticket_id = Common::swap64(ticket_view + offsetof(IOS::ES::TicketView, ticket_id));
  ticket.DeleteTicket(ticket_id);

  const std::vector<u8>& new_ticket = ticket.GetBytes();
  const std::string ticket_path = Common::GetTicketFileName(title_id);
  if (!new_ticket.empty())
  {
    const auto file = fs->OpenFile(PID_KERNEL, PID_KERNEL, ticket_path, FS::Mode::ReadWrite);
    if (!file || !file->Write(new_ticket.data(), new_ticket.size()))
      return ES_EIO;
  }
  else
  {
    // Delete the ticket file if it is now empty.
    fs->Delete(PID_KERNEL, PID_KERNEL, ticket_path);
  }

  // Delete the ticket directory if it is now empty.
  const std::string ticket_parent_dir =
      StringFromFormat("/ticket/%08x", static_cast<u32>(title_id >> 32));
  const auto ticket_parent_dir_entries =
      fs->ReadDirectory(PID_KERNEL, PID_KERNEL, ticket_parent_dir);
  if (ticket_parent_dir_entries && ticket_parent_dir_entries->empty())
    fs->Delete(PID_KERNEL, PID_KERNEL, ticket_parent_dir);

  return IPC_SUCCESS;
}
Example #11
0
ISOFileSystem::ISOFileSystem(IHandleAllocator *_hAlloc, BlockDevice *_blockDevice) 
{
	blockDevice = _blockDevice;
	hAlloc = _hAlloc;

	VolDescriptor desc;
	blockDevice->ReadBlock(16, (u8*)&desc);

	entireISO.name = "";
	entireISO.isDirectory = false;
	entireISO.startingPosition = 0;
	entireISO.size = _blockDevice->GetNumBlocks() * _blockDevice->GetBlockSize();
	entireISO.isBlockSectorMode = true;
	entireISO.flags = 0;
	entireISO.parent = NULL;

	if (!memcmp(desc.cd001, "CD001", 5))
	{
		INFO_LOG(FILESYS, "Looks like a valid ISO!");
	}
	else
	{
		ERROR_LOG(FILESYS, "ISO looks bogus? trying anyway...");
	}

	treeroot = new TreeEntry;
	treeroot->isDirectory = true;
	treeroot->startingPosition = 0;
	treeroot->size = 0;
	treeroot->isBlockSectorMode = false;
	treeroot->flags = 0;
	treeroot->parent = NULL;

	u32 rootSector = desc.root.firstDataSectorLE;
	u32 rootSize = desc.root.dataLengthLE;

	ReadDirectory(rootSector, rootSize, treeroot);
}
void PanelView::EnterDirectory(const char *p)
////////////////////////////////////////////////////////////////////////
{
	char buf[256];		// TODO: mi a leghosszabb? Ki kellene keresni...
	int len = m_Path.Length();

	// Ha mar van elotte / jel...
	if (m_Path.ByteAt(len-1)=='/')
		sprintf(buf,"%s%s",m_Path.String(),p);
	else
		sprintf(buf,"%s/%s",m_Path.String(),p);

	if (DoesEntryExist(p))
	{
		m_Path.SetTo(buf);
	
		SetPathStringView();
		ClearFileList();
		ReadDirectory();
	}
	else
		GotoRoot();
}
Example #13
0
nfsstat3 CNFS3Prog::ProcedureLINK(void)
{
    PrintLog("LINK");
    char *filePath;
    diropargs3 link;
    std::string dirName;
    std::string fileName;
    nfsstat3 stat;
    post_op_attr obj_attributes;
    wcc_data dir_wcc;

    filePath = GetPath();
    ReadDirectory(dirName, fileName);

    char *linkFullPath = GetFullPath(dirName, fileName);

    if (CreateHardLink(linkFullPath, filePath, NULL) == 0) {
        stat = NFS3ERR_IO;
    }
    stat = CheckFile(linkFullPath);
    if (stat == NFS3_OK) {
        obj_attributes.attributes_follow = GetFileAttributesForNFS(filePath, &obj_attributes.attributes);

        if (!obj_attributes.attributes_follow) {
            stat = NFS3ERR_IO;
        }
    }

    dir_wcc.after.attributes_follow = GetFileAttributesForNFS((char*)dirName.c_str(), &dir_wcc.after.attributes);

    Write(&stat);
    Write(&obj_attributes);
    Write(&dir_wcc);

    return stat;
}
Example #14
0
nfsstat3 CNFS3Prog::ProcedureREMOVE(void)
{
    char *path;
    wcc_data dir_wcc;
    nfsstat3 stat;

    PrintLog("REMOVE");

    std::string dirName;
    std::string fileName;
    ReadDirectory(dirName, fileName);
    path = GetFullPath(dirName, fileName);
    stat = CheckFile((char*)dirName.c_str(), path);

    dir_wcc.before.attributes_follow = GetFileAttributesForNFS((char*)dirName.c_str(), &dir_wcc.before.attributes);

    if (stat == NFS3_OK) {
        DWORD fileAttr = GetFileAttributes(path);
        if ((fileAttr & FILE_ATTRIBUTE_DIRECTORY) && (fileAttr & FILE_ATTRIBUTE_REPARSE_POINT)) {
			if (RemoveFolder(path) == 0) {
                stat = NFS3ERR_IO;
            }
        } else {
            if (!RemoveFile(path)) {
                stat = NFS3ERR_IO;
            }
        }
    }

    dir_wcc.after.attributes_follow = GetFileAttributesForNFS((char*)dirName.c_str(), &dir_wcc.after.attributes);

    Write(&stat);
    Write(&dir_wcc);

    return stat;
}
Example #15
0
/*****************************************************************************
 * Run: Gtk+ thread
 *****************************************************************************
 * this part of the interface is in a separate thread so that we can call
 * gtk_main() from within it without annoying the rest of the program.
 *****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
#ifndef NEED_GTK2_MAIN
    /* gtk_init needs to know the command line. We don't care, so we
     * give it an empty one */
    char  *p_args[] = { "", NULL };
    char **pp_args  = p_args;
    int    i_args   = 1;
    int    i_dummy;
#endif
    playlist_t        *p_playlist;
    GtkCellRenderer   *p_renderer = NULL;
    GtkTreeViewColumn *p_column   = NULL;
    GtkListStore      *p_filelist = NULL;
    GtkListStore      *p_playlist_store = NULL;

#ifndef NEED_GTK2_MAIN
    gtk_set_locale ();
    msg_Dbg( p_intf, "Starting pda GTK2+ interface" );
    gtk_init( &i_args, &pp_args );
#else
    /* Initialize Gtk+ */
    msg_Dbg( p_intf, "Starting pda GTK2+ interface thread" );
    gdk_threads_enter();
#endif

    /* Create some useful widgets that will certainly be used */
/* FIXME: magic path */
    add_pixmap_directory("share");
    add_pixmap_directory("/usr/share/vlc");

    /* Path for pixmaps under linupy 1.4 */
    add_pixmap_directory("/usr/local/share/pixmaps/vlc");
    /* Path for pixmaps under linupy 2.0 */
    add_pixmap_directory("/usr/share/pixmaps/vlc");

    p_intf->p_sys->p_window = create_pda();
    if (p_intf->p_sys->p_window == NULL)
    {
        msg_Err( p_intf, "unable to create pda interface" );
    }

    /* Store p_intf to keep an eye on it */
    gtk_object_set_data( GTK_OBJECT(p_intf->p_sys->p_window),
                         "p_intf", p_intf );

    /* Set the title of the main window */
    gtk_window_set_title( GTK_WINDOW(p_intf->p_sys->p_window),
                          VOUT_TITLE " (PDA Linux interface)");

    /* Get the notebook object */
    p_intf->p_sys->p_notebook = GTK_NOTEBOOK( gtk_object_get_data(
        GTK_OBJECT( p_intf->p_sys->p_window ), "notebook" ) );

    /* Get the slider object */
    p_intf->p_sys->p_slider = (GtkHScale*) lookup_widget( p_intf->p_sys->p_window, "timeSlider" );
    p_intf->p_sys->p_slider_label = (GtkLabel*) lookup_widget( p_intf->p_sys->p_window, "timeLabel" );
    if (p_intf->p_sys->p_slider == NULL)
        msg_Err( p_intf, "Time slider widget not found." );
    if (p_intf->p_sys->p_slider_label == NULL)
        msg_Err( p_intf, "Time label widget not found." );

    /* Connect the date display to the slider */
    p_intf->p_sys->p_adj = gtk_range_get_adjustment( GTK_RANGE(p_intf->p_sys->p_slider) );
    if (p_intf->p_sys->p_adj == NULL)
        msg_Err( p_intf, "Adjustment range not found." );
    g_signal_connect( GTK_OBJECT( p_intf->p_sys->p_adj ), "value_changed",
                         G_CALLBACK( E_(GtkDisplayDate) ), p_intf );
    p_intf->p_sys->f_adj_oldvalue = 0;
    p_intf->p_sys->i_adj_oldvalue = 0;

    /* BEGIN OF FILEVIEW GTK_TREE_VIEW */
    p_intf->p_sys->p_tvfile = NULL;
    p_intf->p_sys->p_tvfile = (GtkTreeView *) lookup_widget( p_intf->p_sys->p_window,
                                                             "tvFileList");
    if (NULL == p_intf->p_sys->p_tvfile)
       msg_Err(p_intf, "Error obtaining pointer to File List");

    /* Insert columns 0 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvfile, 0, (gchar *) N_("Filename"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvfile, 0 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 0 );
    gtk_tree_view_column_set_sort_column_id(p_column, 0);
    /* Insert columns 1 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvfile, 1, (gchar *) N_("Permissions"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvfile, 1 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 1 );
    gtk_tree_view_column_set_sort_column_id(p_column, 1);
    /* Insert columns 2 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvfile, 2, (gchar *) N_("Size"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvfile, 2 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 2 );
    gtk_tree_view_column_set_sort_column_id(p_column, 2);
    /* Insert columns 3 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvfile, 3, (gchar *) N_("Owner"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvfile, 3 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 3 );
    gtk_tree_view_column_set_sort_column_id(p_column, 3);
    /* Insert columns 4 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvfile, 4, (gchar *) N_("Group"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvfile, 4 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 4 );
    gtk_tree_view_column_set_sort_column_id(p_column, 4);

    /* Get new directory listing */
    p_filelist = gtk_list_store_new (5,
                G_TYPE_STRING, /* Filename */
                G_TYPE_STRING, /* permissions */
                G_TYPE_UINT64, /* File size */
                G_TYPE_STRING, /* Owner */
                G_TYPE_STRING);/* Group */
    ReadDirectory(p_intf, p_filelist, ".");
    gtk_tree_view_set_model(GTK_TREE_VIEW(p_intf->p_sys->p_tvfile), GTK_TREE_MODEL(p_filelist));
    g_object_unref(p_filelist);     /* Model will be released by GtkTreeView */
    gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(p_intf->p_sys->p_tvfile)),GTK_SELECTION_MULTIPLE);

    /* Column properties */
    gtk_tree_view_set_headers_visible(p_intf->p_sys->p_tvfile, TRUE);
    gtk_tree_view_columns_autosize(p_intf->p_sys->p_tvfile);
    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(p_intf->p_sys->p_tvfile),TRUE);
    /* END OF FILEVIEW GTK_TREE_VIEW */

    /* BEGIN OF PLAYLIST GTK_TREE_VIEW */
    p_intf->p_sys->p_tvplaylist = NULL;
    p_intf->p_sys->p_tvplaylist = (GtkTreeView *) lookup_widget( p_intf->p_sys->p_window, "tvPlaylist");
    if (NULL == p_intf->p_sys->p_tvplaylist)
       msg_Err(p_intf, "Error obtaining pointer to Play List");

    /* Columns 1 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvplaylist, 0, (gchar *) N_("Filename"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvplaylist, 0 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 0 );
    gtk_tree_view_column_set_sort_column_id(p_column, 0);
    /* Column 2 */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvplaylist, 1, (gchar *) N_("Time"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvplaylist, 1 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 1 );
    gtk_tree_view_column_set_sort_column_id(p_column, 1);
#if 0
    /* Column 3 - is a hidden column used for reliable deleting items from the underlying playlist */
    p_renderer = gtk_cell_renderer_text_new ();
    gtk_tree_view_insert_column_with_attributes(p_intf->p_sys->p_tvplaylist, 2, (gchar *) N_("Index"), p_renderer, NULL);
    p_column = gtk_tree_view_get_column(p_intf->p_sys->p_tvplaylist, 2 );
    gtk_tree_view_column_add_attribute(p_column, p_renderer, "text", 2 );
    gtk_tree_view_column_set_sort_column_id(p_column, 2);
#endif
    /* update the playlist */
    p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );
    p_playlist_store = gtk_list_store_new (3,
                G_TYPE_STRING, /* Filename */
                G_TYPE_STRING, /* Time */
                G_TYPE_UINT);  /* Hidden index */
    PlaylistRebuildListStore(p_playlist_store, p_playlist);
    gtk_tree_view_set_model(GTK_TREE_VIEW(p_intf->p_sys->p_tvplaylist), GTK_TREE_MODEL(p_playlist_store));
    g_object_unref(p_playlist_store);
    vlc_object_release(p_playlist); /* Free the playlist */
    gtk_tree_selection_set_mode(gtk_tree_view_get_selection(GTK_TREE_VIEW(p_intf->p_sys->p_tvplaylist)),GTK_SELECTION_MULTIPLE);

    /* Column properties */
    gtk_tree_view_set_headers_visible(p_intf->p_sys->p_tvplaylist, TRUE);
    gtk_tree_view_columns_autosize(p_intf->p_sys->p_tvplaylist);
    gtk_tree_view_set_headers_clickable(p_intf->p_sys->p_tvplaylist, TRUE);
    /* END OF PLAYLIST GTK_TREE_VIEW */

    /* Hide the Preference TAB for now. */
    GtkWidget *p_preference_tab = NULL;
    p_preference_tab = gtk_notebook_get_nth_page(p_intf->p_sys->p_notebook,5);
    if (p_preference_tab != NULL)
      gtk_widget_hide(p_preference_tab);

    /* Show the control window */
    gtk_widget_show( p_intf->p_sys->p_window );

#ifdef NEED_GTK2_MAIN
    msg_Dbg( p_intf, "Manage GTK keyboard events using threads" );
    while( !p_intf->b_die )
    {
        Manage( p_intf );

        /* Sleep to avoid using all CPU - since some interfaces need to
         * access keyboard events, a 100ms delay is a good compromise */
        gdk_threads_leave();
        if (p_intf->p_libvlc->i_cpu & CPU_CAPABILITY_FPU)
            msleep( INTF_IDLE_SLEEP );
        else
            msleep( 1000 );
        gdk_threads_enter();
    }
#else
    msg_Dbg( p_intf, "Manage GTK keyboard events using timeouts" );
    /* Sleep to avoid using all CPU - since some interfaces needs to access
     * keyboard events, a 1000ms delay is a good compromise */
    if (p_intf->p_libvlc->i_cpu & CPU_CAPABILITY_FPU)
        i_dummy = gtk_timeout_add( INTF_IDLE_SLEEP / 1000, (GtkFunction)Manage, p_intf );
    else
        i_dummy = gtk_timeout_add( 1000, (GtkFunction)Manage, p_intf );

    /* Enter Gtk mode */
    gtk_main();
    /* Remove the timeout */
    gtk_timeout_remove( i_dummy );
#endif

    gtk_object_destroy( GTK_OBJECT(p_intf->p_sys->p_window) );
#ifdef NEED_GTK2_MAIN
    gdk_threads_leave();
#endif
}
// -----------------------------------------------------------------------------
// CAknFileSelectionModel::UpdateItemListL
// -----------------------------------------------------------------------------
//
TInt CAknFileSelectionModel::UpdateItemListL()
    {
    iEntryArray->Reset();
    iImageIndexArray.Reset();

    CDir* entryArray = ReadDirectory( iCurrentPath.DriveAndPath() );
    if ( !entryArray )
        {
        return KErrNotFound;
        }
    CleanupStack::PushL( entryArray );

    TInt itemCount( entryArray->Count() );
    if ( itemCount > 0 )
        {
        TInt filterCount( iFilterArray->Count() );
        TInt filterIndex;
        TBool accepted;
        CDesC16Array* desC16FoldersArray = new ( ELeave )
                           CDesC16ArrayFlat( KEntryArrayGranularity );
        CleanupStack::PushL( desC16FoldersArray );
        CDesC16Array* desC16FilesArray = new ( ELeave )
                           CDesC16ArrayFlat( KEntryArrayGranularity );
        CleanupStack::PushL( desC16FilesArray );
        CArrayPakFlat<TEntry>* tmpFoldersArray = new( ELeave ) 
            CArrayPakFlat<TEntry>( KEntryArrayGranularity );
        CleanupStack::PushL( tmpFoldersArray );
        CArrayPakFlat<TEntry>* tmpFilesArray = new( ELeave ) 
            CArrayPakFlat<TEntry>( KEntryArrayGranularity );
        CleanupStack::PushL( tmpFilesArray );
            
        tmpFoldersArray->Reset();
        desC16FoldersArray->Reset();
        tmpFilesArray->Reset();
        desC16FilesArray->Reset();
        
        for ( TInt i( 0 ); i < itemCount; i++ ) // Generate filtered list
            {
            accepted = ETrue; // If there are no filters, accept the entry
            TEntry entry = ( *entryArray )[i];
            filterIndex = 0;
            // Go thru the filters while the entry is accepted
            while( ( filterIndex < filterCount ) && ( accepted ) )
                {
                accepted = iFilterArray->At( filterIndex )->Accept(
                    iCurrentPath.DriveAndPath(), entry );
                filterIndex++;
                }
            if ( accepted ) // Directory entry has passed all filters
                {
                 // Add filename to filtered list
                if ( entry.IsDir() )
                    {
                    desC16FoldersArray->AppendL( GetLocalizedName( entry.iName ) );
                    tmpFoldersArray->AppendL( entry, sizeof( TEntry ) );
                    }
                else
                    {
                    desC16FilesArray->AppendL( GetLocalizedName( entry.iName ) );
                    tmpFilesArray->AppendL( entry, sizeof( TEntry ) );
                    }
                }
            }
        
        TInt entryCount = 0;
        TInt index;
        TKeyArrayPak key( _FOFF( TEntry, iName ), ECmpCollated );
        
        // Add folder entries
        desC16FoldersArray->Sort( ECmpCollated );
        entryCount = desC16FoldersArray->MdcaCount();
        for( TInt j( 0 ); j < entryCount; j++ )
            {
            for( TInt k( 0 ); k < entryCount; k++ )
                {
                if( ( *desC16FoldersArray )[j] == 
                        GetLocalizedName( ( *tmpFoldersArray )[k].iName ) &&
                    iEntryArray->Find( ( *tmpFoldersArray )[k], key, index ) != 0 )
                    {
                    TEntry tmpEntry = ( *tmpFoldersArray )[k];
                    
                    iEntryArray->AppendL( tmpEntry, sizeof( TEntry ) );
                    
                    // Entry is a directory
                    TFileTypeIcon folderIcon( EFolderIcon );
                    
                    if( !AknCFDUtility::IsRemoteDrive( iCurrentPath.Drive() ) )
                        {
                        if ( ContainsSubfolders( tmpEntry.iName ) )
                            {
                            folderIcon = ESubFolderIcon;
                            }
                        else if ( !ContainsFiles( tmpEntry.iName ) )
                            {
                            folderIcon = EFolderEmptyIcon;
                            }
                        }
                    iImageIndexArray.Append( folderIcon );
                    
                    break;
                    }
                }
            }
        
        // Add file entries
        desC16FilesArray->Sort( ECmpCollated );
        entryCount = desC16FilesArray->MdcaCount();
        for( TInt j( 0 ); j < entryCount; j++ )
            {
            for( TInt k( 0 ); k < entryCount; k++ )
                {
                if( ( *desC16FilesArray )[j] == 
                        GetLocalizedName( ( *tmpFilesArray )[k].iName ) &&
                    iEntryArray->Find( ( *tmpFilesArray )[k], key, index ) != 0 )
                    {
                    TEntry tmpFile = ( *tmpFilesArray )[k];
                    
                    iEntryArray->AppendL( tmpFile, sizeof( TEntry ) );
                    
                    // Entry is a file
                    AppendIconForFileL( tmpFile.iName );
                    
                    break;
                    }
                }
            }
        
        CleanupStack::PopAndDestroy( tmpFilesArray );
        CleanupStack::PopAndDestroy( tmpFoldersArray );
        CleanupStack::Pop( desC16FilesArray );
        desC16FilesArray->Reset();
        delete desC16FilesArray;
        CleanupStack::Pop( desC16FoldersArray );
        desC16FoldersArray->Reset();
        delete desC16FoldersArray;
        }
    
    CleanupStack::PopAndDestroy( entryArray );
    
    if ( AknCFDUtility::DirectoriesOnly( iDialogType ) )
        {
        // Set the current folder name as first item.
        // Current folder is for example "E:\Images\Holiday\"
        // Remove trailing backslash, we get "E:\Images\Holiday"
        // Parse the path with TParse and ask for NameAndExt().
        // TParse interpretes "Holiday" as file name and returns it.

        HBufC * bufFolder = HBufC::NewLC(KMaxPath);
        * bufFolder = iCurrentPath.DriveAndPath() ;
        TPtr folder = bufFolder->Des();

        AknCFDUtility::RemoveTrailingBackslash( folder ); // ignore error

        TParsePtr parsedFolder(folder);

        folder = parsedFolder.NameAndExt();
        iFolderEntry.iName = folder;
        iEntryArray->InsertL( 0, iFolderEntry, sizeof( TEntry ) );
        iImageIndexArray.Insert( EThisFolderIcon, 0 );

        CleanupStack::PopAndDestroy(); //bufFolder
        }
    
    return iEntryArray->Count();
    }
Example #17
0
Zip::Zip(Control &control_, char *zipfile_name) : control(control_),
                                                  magic(0),
                                                  zipbuffer(NULL)
{
#ifdef UNIX_FILE_SYSTEM
    zipfile = SystemFopen(zipfile_name, "rb");
    if (zipfile)
    {
        int rc = fseek(zipfile, -END_SIZE, SEEK_END);
        if (rc == 0)
        {
            zipbuffer = new char[END_SIZE];
            buffer_ptr = zipbuffer;
            SystemFread(buffer_ptr, sizeof(char), END_SIZE, zipfile);

            magic = GetU4();
        }
    }
#elif defined(WIN32_FILE_SYSTEM)
    zipfile = CreateFile(zipfile_name,
                         GENERIC_READ,
                         FILE_SHARE_READ,
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_READONLY,
                         NULL);
    if (zipfile != INVALID_HANDLE_VALUE)
    {
        mapfile = CreateFileMapping(zipfile, NULL, PAGE_READONLY, 0, 0, NULL);
        zipbuffer = (mapfile == INVALID_HANDLE_VALUE ?
                     NULL :
                     (char *) MapViewOfFile(mapfile,
                                            FILE_MAP_READ,
                                            0, 0, 0)
                     );
        if (zipbuffer)
        {
            buffer_ptr = &zipbuffer[GetFileSize(zipfile, NULL) - END_SIZE];
            magic = GetU4();
        }
    }
#endif

    // The following was posted to the dev list, but was just
    // too good to not put in here, the next person to have to
    // deal with this crap will appreciate it. -=Chris
    //
    // From: Mo DeJong <*****@*****.**>
    //
    //   Ode to a zip file:
    //
    //   I can't read it forwards
    //   I can't read it backwards
    //   I must know where to begin
    //   so I need to look in the middle
    //   to find the middle, I must know the end
    //   but I don't know where that is, so I guess
    //
    // -------------------------------------------------


    // This may or may not be a valid zip file. The zip file might have
    // a file comment so we can't be sure where the END header is located.
    // We check for the LOC header at byte 0 to make sure this is a valid
    // zip file and then scan over the file backwards in search of the
    // END header.

    if (zipbuffer != NULL && ! IsValid()) {
        u4 sig = 0;

#ifdef UNIX_FILE_SYSTEM
        int res = fseek(zipfile, 0, SEEK_SET);
        assert(res == 0);

        char *tmpbuffer = new char[LOC_SIZE];
        buffer_ptr = tmpbuffer;
        SystemFread(buffer_ptr, sizeof(char), LOC_SIZE, zipfile);
        sig = GetU4();
        delete [] tmpbuffer;
        buffer_ptr = NULL;

        if (sig == LOC_SIG)
        {
            int block_size = 8192;
            tmpbuffer = new char[block_size];
            char *holdbuffer = new char[8];
            char *index_ptr;

            res = fseek(zipfile, 0, SEEK_END);
            assert(res == 0);

            long zip_file_size = ftell(zipfile);
            int num_loops = zip_file_size / block_size;
            magic = 0;

            for (; magic == 0 && num_loops >= 0 ; num_loops--) {

                if ((ftell(zipfile) - block_size) < 0)
                {
                    block_size = ftell(zipfile);
                    res = fseek(zipfile, 0L, SEEK_SET);
                }
                else
                {
                    res = fseek(zipfile, -block_size, SEEK_CUR);
                }

                assert(res == 0);
                SystemFread(tmpbuffer, sizeof(char), block_size, zipfile);
                res = fseek(zipfile, -block_size, SEEK_CUR); // undo fread
                assert(res == 0);

                for (index_ptr = tmpbuffer + block_size - 1;
                     index_ptr >= tmpbuffer;
                     index_ptr--)
                {
                    if (*index_ptr == 'P')
                    {
                        // Check for header signature that spans buffer
                        int span = (tmpbuffer + block_size) - index_ptr;

                        if (span < 4)
                        {
                            memmove(holdbuffer+span, holdbuffer, 3);
                            memmove(holdbuffer, index_ptr, span);
                            buffer_ptr = holdbuffer;
                        }
                        else
                        {
                            buffer_ptr = index_ptr;
                        }

                        sig = GetU4();

                        if (sig == END_SIG)
                        {
                            // Found the END header, put it in zipbuffer.
                            buffer_ptr = zipbuffer;
                            fseek(zipfile, block_size-span, SEEK_CUR);
                            SystemFread(buffer_ptr, sizeof(char),
                                END_SIZE, zipfile);

                            magic = GetU4();
                            break;
                        }
                    }
                }

                // Copy first 3 bytes into holdbuffer in case sig spans
                holdbuffer[0] = tmpbuffer[0];
                holdbuffer[1] = tmpbuffer[1];
                holdbuffer[2] = tmpbuffer[2];
            }

            delete [] tmpbuffer;
            delete [] holdbuffer;
        }
#elif defined(WIN32_FILE_SYSTEM)
        buffer_ptr = &zipbuffer[0];
        sig = GetU4();

        if (sig == LOC_SIG)
        {
            buffer_ptr = &zipbuffer[GetFileSize(zipfile, NULL) - END_SIZE];
            for ( ; buffer_ptr >= zipbuffer; buffer_ptr--)
            {
                if (*buffer_ptr == 'P')
                {
                    sig = GetU4();
                    if (sig == END_SIG)
                    {
                       magic = sig;
                       break;
                    }
                    else
                       buffer_ptr -= 4;
                }
            }
        }
#endif
    }

    ReadDirectory();
}
Example #18
0
void ISOFileSystem::ReadDirectory(u32 startsector, u32 dirsize, TreeEntry *root, size_t level)
{
	for (u32 secnum = startsector, endsector = dirsize/2048 + startsector; secnum < endsector; ++secnum)
	{
		u8 theSector[2048];
		blockDevice->ReadBlock(secnum, theSector);
		lastReadBlock_ = secnum;

		for (int offset = 0; offset < 2048; )
		{
			DirectoryEntry &dir = *(DirectoryEntry *)&theSector[offset];
			u8 sz = theSector[offset];

			// Nothing left in this sector.  There might be more in the next one.
			if (sz == 0)
				break;

			const int IDENTIFIER_OFFSET = 33;
			if (offset + IDENTIFIER_OFFSET + dir.identifierLength > 2048)
			{
				ERROR_LOG(FILESYS, "Directory entry crosses sectors, corrupt iso?");
				return;
			}

			offset += dir.size;

			bool isFile = (dir.flags & 2) ? false : true;
			bool relative;

			TreeEntry *e = new TreeEntry();
			if (dir.identifierLength == 1 && (dir.firstIdChar == '\x00' || dir.firstIdChar == '.'))
			{
				e->name = ".";
				relative = true;
			}
			else if (dir.identifierLength == 1 && dir.firstIdChar == '\x01')
			{
				e->name = "..";
				relative = true;
			}
			else
			{
				e->name = std::string((char *)&dir.firstIdChar, dir.identifierLength);
				relative = false;
			}

			e->size = dir.dataLength();
			e->startingPosition = dir.firstDataSector() * 2048;
			e->isDirectory = !isFile;
			e->flags = dir.flags;
			e->parent = root;

			// Let's not excessively spam the log - I commented this line out.
			//DEBUG_LOG(FILESYS, "%s: %s %08x %08x %i", e->isDirectory?"D":"F", e->name.c_str(), dir.firstDataSectorLE, e->startingPosition, e->startingPosition);

			if (e->isDirectory && !relative)
			{
				if (dir.firstDataSector() == startsector)
				{
					ERROR_LOG(FILESYS, "WARNING: Appear to have a recursive file system, breaking recursion");
				}
				else
				{
					bool doRecurse = true;
					if (!restrictTree.empty())
						doRecurse = level < restrictTree.size() && restrictTree[level] == e->name;

					if (doRecurse)
						ReadDirectory(dir.firstDataSector(), dir.dataLength(), e, level + 1);
					else
						continue;
				}
			}
			root->children.push_back(e);
		}
	}
}
Example #19
0
void CACEdit::OnChange()
{
	CString m_Text;
	int pos=0,len;

	if(m_iType == -1)
	{ASSERT(0); return;}

	GetWindowText(m_EditText);
	len = m_EditText.GetLength();
	//----------------------------------------------
	if(m_iMode & _MODE_FILESYSTEM_ || m_iMode & _MODE_FS_START_DIR_)
	{
		if(!m_CursorMode)
		{
			if(m_iType == _EDIT_)
				pos = LOWORD(((CEdit*)this)->CharFromPos(GetCaretPos()));

			if(m_iType == _COMBOBOX_)
				pos = m_pEdit->CharFromPos(m_pEdit->GetCaretPos());

			if(m_iMode & _MODE_FS_START_DIR_)
			{
				if(len)
					m_Liste.FindString(-1,m_EditText);
				else
					m_Liste.ShowWindow(false);
			}
			else
			{
				if(len > 2 && pos == len)
				{
					if(_taccess(m_EditText,0) == 0)
					{
						ReadDirectory(m_EditText);
					}
					m_Liste.FindString(-1,m_EditText);
				}
				else
					m_Liste.ShowWindow(false);
			}
		} // m_CursorMode
	}
	//----------------------------------------------
	if(m_iMode & _MODE_SEPARATION_)
	{
		if(!m_CursorMode)
		{
			if(m_iType == _EDIT_)
				pos = LOWORD(((CEdit*)this)->CharFromPos(GetCaretPos()));

			if(m_iType == _COMBOBOX_)
				pos = m_pEdit->CharFromPos(m_pEdit->GetCaretPos());

			int left,right;
			left  = FindSepLeftPos(pos-1);
			right = FindSepRightPos(pos);
			m_Text = m_EditText.Mid(left,right-left);
			m_Liste.FindString(-1,m_Text);
		}
	}
	//----------------------------------------------
	if(m_iMode & _MODE_STANDARD_)
	{
		if(!m_CursorMode)
			m_Liste.FindString(-1,m_EditText);
	}
	//----------------------------------------------
	GetParent()->SendMessage(ENAC_UPDATE, EN_UPDATE, GetDlgCtrlID());
}
Example #20
0
static void
dump(int fd, uint64 diroff)
{
	unsigned i;

	lseek(fd, (off_t) 0, 0);
	if (read(fd, (char*) &hdr, sizeof (TIFFHeaderCommon)) != sizeof (TIFFHeaderCommon))
		ReadError("TIFF header");
	if (hdr.common.tiff_magic != TIFF_BIGENDIAN
	    && hdr.common.tiff_magic != TIFF_LITTLEENDIAN &&
#if HOST_BIGENDIAN
	    /* MDI is sensitive to the host byte order, unlike TIFF */
	    MDI_BIGENDIAN != hdr.common.tiff_magic
#else
	    MDI_LITTLEENDIAN != hdr.common.tiff_magic
#endif
	   ) {
		Fatal("Not a TIFF or MDI file, bad magic number %u (%#x)",
		    hdr.common.tiff_magic, hdr.common.tiff_magic);
	}
	if (hdr.common.tiff_magic == TIFF_BIGENDIAN
	    || hdr.common.tiff_magic == MDI_BIGENDIAN)
		swabflag = !bigendian;
	else
		swabflag = bigendian;
	if (swabflag)
		TIFFSwabShort(&hdr.common.tiff_version);
	if (hdr.common.tiff_version==42)
	{
		if (read(fd, (char*) &hdr.classic.tiff_diroff, 4) != 4)
			ReadError("TIFF header");
		if (swabflag)
			TIFFSwabLong(&hdr.classic.tiff_diroff);
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.classic.tiff_magic,
		    hdr.classic.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    42,"ClassicTIFF");
		if (diroff == 0)
			diroff = hdr.classic.tiff_diroff;
	}
	else if (hdr.common.tiff_version==43)
	{
		if (read(fd, (char*) &hdr.big.tiff_offsetsize, 12) != 12)
			ReadError("TIFF header");
		if (swabflag)
		{
			TIFFSwabShort(&hdr.big.tiff_offsetsize);
			TIFFSwabShort(&hdr.big.tiff_unused);
			TIFFSwabLong8(&hdr.big.tiff_diroff);
		}
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.big.tiff_magic,
		    hdr.big.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    43,"BigTIFF");
		printf("OffsetSize: %#x Unused: %#x\n",
		    hdr.big.tiff_offsetsize,hdr.big.tiff_unused);
		if (diroff == 0)
			diroff = hdr.big.tiff_diroff;
		bigtiff = 1;
	}
	else
		Fatal("Not a TIFF file, bad version number %u (%#x)",
		    hdr.common.tiff_version, hdr.common.tiff_version);
	for (i = 0; diroff != 0; i++) {
		if (i > 0)
			putchar('\n');
		diroff = ReadDirectory(fd, i, diroff);
	}
}
Example #21
0
void ISOFileSystem::ReadDirectory(u32 startsector, u32 dirsize, TreeEntry *root)
{
	u8 buffer[2048];
	int offset = 0;
	u32 secnum = startsector;

	u8 theSector[2048];
	blockDevice->ReadBlock(secnum, theSector);

	while (secnum < (dirsize/2048 + startsector))
	{
		DirectoryEntry &dir = *((DirectoryEntry *)buffer);
		u8 sz = theSector[offset];
		if (sz == 0) // NOT the correct way
			goto nextblock; //done

		memcpy(&dir, theSector + offset, sz);
		
		buffer[2047]=0;
		offset += dir.size;
		if (offset >= 2048)
		{
nextblock:
			offset=0;
			secnum++;
			blockDevice->ReadBlock(secnum, theSector);
			memcpy(&dir, theSector + offset, sz);
		}
		bool isFile = (dir.flags & 2) ? false : true;

		int fnLength = dir.identifierLength;

		char name[256];
		for (int i = 0; i < fnLength; i++)
			name[i] = buffer[33+i] ? buffer[33+i] : '.';
		name[fnLength] = '\0';

		if (!strcmp(name, "."))	// "." record
			continue;
		if (strlen(name) == 1 && name[0] == '\x01')	 // ".." record
			continue;

		TreeEntry *e = new TreeEntry;
		e->name = name;
		e->size = dir.dataLengthLE;
		e->startingPosition = dir.firstDataSectorLE * 2048;
		e->isDirectory = !isFile;
		e->flags = dir.flags;
		e->isBlockSectorMode = false;
				
		DEBUG_LOG(FILESYS, "%s: %s %08x %08x %i", e->isDirectory?"D":"F", name, dir.firstDataSectorLE, e->startingPosition, e->startingPosition);

		if (e->isDirectory)
		{
			if (dir.firstDataSectorLE == startsector)
			{
				ERROR_LOG(FILESYS, "WARNING: Appear to have a recursive file system, breaking recursion");
			}
			else
			{
				ReadDirectory(dir.firstDataSectorLE, dir.dataLengthLE, e);
			}
		}
		root->children.push_back(e);
	}

}
Example #22
0
nfsstat3 CNFS3Prog::ProcedureSYMLINK(void)
{
    PrintLog("SYMLINK");

    char* path;
    post_op_fh3 obj;
    post_op_attr obj_attributes;
    wcc_data dir_wcc;
    nfsstat3 stat;

    diropargs3 where;
    symlinkdata3 symlink;

    DWORD targetFileAttr;
    DWORD dwFlags;

    std::string dirName;
    std::string fileName;
    ReadDirectory(dirName, fileName);
    path = GetFullPath(dirName, fileName);

    Read(&symlink);

    _In_ LPTSTR lpSymlinkFileName = path; // symlink (full path)

    // TODO: Maybe revisit this later for a cleaner solution
    // Convert target path to windows path format, maybe this could also be done
    // in a safer way by a combination of PathRelativePathTo and GetFullPathName.
    // Without this conversion nested folder symlinks do not work cross platform.
    std::string strFromChar;
    strFromChar.append(symlink.symlink_data.path); // target (should be relative path));
    std::replace(strFromChar.begin(), strFromChar.end(), '/', '\\');
    _In_ LPTSTR lpTargetFileName = const_cast<LPSTR>(strFromChar.c_str());

    std::string fullTargetPath = dirName + std::string("\\") + std::string(lpTargetFileName);

    // Relative path do not work with GetFileAttributes (directory are not recognized)
    // so we normalize the path before calling GetFileAttributes
    TCHAR fullTargetPathNormalized[MAX_PATH];
    _In_ LPTSTR fullTargetPathString = const_cast<LPSTR>(fullTargetPath.c_str());;
    GetFullPathName(fullTargetPathString, MAX_PATH, fullTargetPathNormalized, NULL);
    targetFileAttr = GetFileAttributes(fullTargetPathNormalized);

    dwFlags = 0x0;
	if (targetFileAttr & FILE_ATTRIBUTE_DIRECTORY) {
        dwFlags = SYMBOLIC_LINK_FLAG_DIRECTORY;
    }

    BOOLEAN failed = CreateSymbolicLink(lpSymlinkFileName, lpTargetFileName, dwFlags);

    if (failed != 0) {
        stat = NFS3_OK;
        obj.handle_follows = GetFileHandle(path, &obj.handle);
        obj_attributes.attributes_follow = GetFileAttributesForNFS(path, &obj_attributes.attributes);
    }
    else {
        stat = NFS3ERR_IO;
        PrintLog("An error occurs or file already exists.");
        stat = CheckFile(path);
        if (stat != NFS3_OK) {
            stat = NFS3ERR_IO;
        }
    }

    dir_wcc.after.attributes_follow = GetFileAttributesForNFS((char*)dirName.c_str(), &dir_wcc.after.attributes);

    Write(&stat);

    if (stat == NFS3_OK) {
        Write(&obj);
        Write(&obj_attributes);
    }

    Write(&dir_wcc);

    return stat;
}
Example #23
0
static void
dump(int fd, uint64 diroff)
{
	unsigned i, j;
	uint64* visited_diroff = NULL;
	unsigned int count_visited_dir = 0;

	_TIFF_lseek_f(fd, (_TIFF_off_t) 0, 0);
	if (read(fd, (char*) &hdr, sizeof (TIFFHeaderCommon)) != sizeof (TIFFHeaderCommon))
		ReadError("TIFF header");
	if (hdr.common.tiff_magic != TIFF_BIGENDIAN
	    && hdr.common.tiff_magic != TIFF_LITTLEENDIAN &&
#if HOST_BIGENDIAN
	    /* MDI is sensitive to the host byte order, unlike TIFF */
	    MDI_BIGENDIAN != hdr.common.tiff_magic
#else
	    MDI_LITTLEENDIAN != hdr.common.tiff_magic
#endif
	   ) {
		Fatal("Not a TIFF or MDI file, bad magic number %u (%#x)",
		    hdr.common.tiff_magic, hdr.common.tiff_magic);
	}
	if (hdr.common.tiff_magic == TIFF_BIGENDIAN
	    || hdr.common.tiff_magic == MDI_BIGENDIAN)
		swabflag = !bigendian;
	else
		swabflag = bigendian;
	if (swabflag)
		TIFFSwabShort(&hdr.common.tiff_version);
	if (hdr.common.tiff_version==42)
	{
		if (read(fd, (char*) &hdr.classic.tiff_diroff, 4) != 4)
			ReadError("TIFF header");
		if (swabflag)
			TIFFSwabLong(&hdr.classic.tiff_diroff);
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.classic.tiff_magic,
		    hdr.classic.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    42,"ClassicTIFF");
		if (diroff == 0)
			diroff = hdr.classic.tiff_diroff;
	}
	else if (hdr.common.tiff_version==43)
	{
		if (read(fd, (char*) &hdr.big.tiff_offsetsize, 12) != 12)
			ReadError("TIFF header");
		if (swabflag)
		{
			TIFFSwabShort(&hdr.big.tiff_offsetsize);
			TIFFSwabShort(&hdr.big.tiff_unused);
			TIFFSwabLong8(&hdr.big.tiff_diroff);
		}
		printf("Magic: %#x <%s-endian> Version: %#x <%s>\n",
		    hdr.big.tiff_magic,
		    hdr.big.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
		    43,"BigTIFF");
		printf("OffsetSize: %#x Unused: %#x\n",
		    hdr.big.tiff_offsetsize,hdr.big.tiff_unused);
		if (diroff == 0)
			diroff = hdr.big.tiff_diroff;
		bigtiff = 1;
	}
	else
		Fatal("Not a TIFF file, bad version number %u (%#x)",
		    hdr.common.tiff_version, hdr.common.tiff_version);
	for (i = 0; diroff != 0; i++) {
		for(j=0; j<count_visited_dir; j++)
		{
		    if( visited_diroff[j] == diroff )
		    {
			free(visited_diroff);
			Fatal("Cycle detected in chaining of TIFF directories!");
		    }
		}
                {
                    size_t alloc_size;
                    alloc_size=TIFFSafeMultiply(tmsize_t,(count_visited_dir + 1),
                                                sizeof(uint64));
                    if (alloc_size == 0)
                    {
                        if (visited_diroff)
                            free(visited_diroff);
                        visited_diroff = 0;
                    }
                    else
                    {
                        visited_diroff = (uint64*) realloc(visited_diroff,alloc_size);
                    }
                }
		if( !visited_diroff )
		    Fatal("Out of memory");
		visited_diroff[count_visited_dir] = diroff;
		count_visited_dir ++;

		if (i > 0)
			putchar('\n');
		diroff = ReadDirectory(fd, i, diroff);
	}
	if( visited_diroff )
	    free(visited_diroff);
}
Example #24
0
/*
 * Create
 */
void Create()
{
	fNDS = fopen(ndsfilename, "wb");
	if (!fNDS) { fprintf(stderr, "Cannot open file '%s'.\n", ndsfilename); exit(1); }

	bool bSecureSyscalls = false;
	char *headerfilename = (headerfilename_or_size && (strtoul(headerfilename_or_size,0,0) == 0)) ? headerfilename_or_size : 0;
	u32 headersize = headerfilename_or_size ? strtoul(headerfilename_or_size,0,0) : 0x200;

	// initial header data
	if (headerfilename)
	{
		// header template
		FILE *fi = fopen(headerfilename, "rb");
		if (!fi) { fprintf(stderr, "Cannot open file '%s'.\n", headerfilename); exit(1); }
		fread(&header, 1, 0x200, fi);
		fclose(fi);

		if ((header.arm9_ram_address + 0x800 == header.arm9_entry_address) || (header.rom_header_size > 0x200))
		{
			bSecureSyscalls = true;
		}
	}
	else	// set header default values
	{
		// clear header
		memset(&header, 0, sizeof(header));
		memcpy(header.gamecode, "####", 4);

		if ((arm9RamAddress + 0x800 == arm9Entry) || (headersize > 0x200))
		{
			bSecureSyscalls = true;
		}
		else
		{
			header.reserved2 = 0x04;		// autostart
			*(unsigned_int *)(((unsigned char *)&header) + 0x0) = 0xEA00002E;		// for PassMe's that start @ 0x08000000
		}
		*(unsigned_int *)(((unsigned char *)&header) + 0x60) = 1<<22 | latency2<<16 | 1<<14 | 1<<13 | latency1;	// ROM control info 1
		*(unsigned_int *)(((unsigned char *)&header) + 0x64) = 1<<29 | latency2<<16 | latency1;	// ROM control info 2
		*(unsigned_short *)(((unsigned char *)&header) + 0x6E) = 0x051E;	// ROM control info 3
	}
	if (headersize) header.rom_header_size = headersize;
	if (header.rom_header_size == 0) header.rom_header_size = bSecureSyscalls ? 0x4000 : 0x200;

	// load a logo
	if (logofilename)
	{
		char *p = strrchr(logofilename, '.');
		if (!strcmp(p, ".bmp"))
		{
			CRaster raster;
			if (raster.LoadBMP(logofilename) < 0) exit(1);
			unsigned char white = (raster.palette[0].rgbGreen >= 128) ? 0 : 1;
			if (LogoConvert(raster.raster, header.logo, white) < 0) exit(1);
		}
		else
		{
			FILE *fi = fopen(logofilename, "rb");
			if (!fi) { fprintf(stderr, "Cannot open file '%s'.\n", logofilename); exit(1); }
			fread(&header.logo, 1, 156, fi);
			fclose(fi);
		}
	}
	else if (bSecureSyscalls)	// use Nintendo logo
	{
		memcpy(((unsigned char *)&header) + 0xC0, nintendo_logo, sizeof(nintendo_logo));
	}
	else	// add small NDS loader
	{
		if (loadme_size != 156) { fprintf(stderr, "loadme size error\n"); exit(1); }
		memcpy(header.logo, loadme, loadme_size);		// self-contained NDS loader for *Me GBA cartridge boot
		memcpy(&header.offset_0xA0, "SRAM_V110", 9);		// allow GBA cartridge SRAM backup
		memcpy(&header.offset_0xAC, "PASS01\x96", 7);		// automatically start with FlashMe, make it look more like a GBA rom
	}

	// override default title/game/maker codes
	if (title) strncpy(header.title, title, 12);
	if (gamecode) strncpy(header.gamecode, gamecode, 4);
	if (makercode) strncpy((char *)header.makercode, makercode, 2);

	// --------------------------

	fseek(fNDS, header.rom_header_size, SEEK_SET);

	// ARM9 binary
	if (arm9filename)
	{
		header.arm9_rom_offset = (ftell(fNDS) + arm9_align) &~ arm9_align;
		fseek(fNDS, header.arm9_rom_offset, SEEK_SET);

		unsigned int entry_address = arm9Entry ? arm9Entry : (unsigned int)header.arm9_entry_address;		// template
		unsigned int ram_address = arm9RamAddress ? arm9RamAddress : (unsigned int)header.arm9_ram_address;		// template
		if (!ram_address && entry_address) ram_address = entry_address;
		if (!entry_address && ram_address) entry_address = ram_address;
		if (!ram_address) { ram_address = entry_address = 0x02000000; }

		// add dummy area for secure syscalls
		header.arm9_size = 0;
		if (bSecureSyscalls)
		{
			unsigned_int x;
			FILE *fARM9 = fopen(arm9filename, "rb");
			if (fARM9)
			{
				fread(&x, sizeof(x), 1, fARM9);
				fclose(fARM9);
				if (x != 0xE7FFDEFF)	// not already exist?
				{
					x = 0xE7FFDEFF;
					for (int i=0; i<0x800/4; i++) fwrite(&x, sizeof(x), 1, fNDS);
					header.arm9_size = 0x800;
				}
			}
		}

		unsigned int size = 0;


		if (HasElfExtension(arm9filename) || HasElfHeader(arm9filename) )
			CopyFromElf(arm9filename, &entry_address, &ram_address, &size);
		else
			CopyFromBin(arm9filename, 0, &size);
		header.arm9_entry_address = entry_address;
		header.arm9_ram_address = ram_address;
		header.arm9_size = header.arm9_size + ((size + 3) &~ 3);
	}
	else
	{
		fprintf(stderr, "ARM9 binary file required.\n");
		exit(1);
	}

	// ARM9 overlay table
	if (arm9ovltablefilename)
	{
		unsigned_int x1 = 0xDEC00621; fwrite(&x1, sizeof(x1), 1, fNDS);		// 0x2106c0de magic
		unsigned_int x2 = 0x00000AD8; fwrite(&x2, sizeof(x2), 1, fNDS);		// ???
		unsigned_int x3 = 0x00000000; fwrite(&x3, sizeof(x3), 1, fNDS);		// ???

		header.arm9_overlay_offset = ftell(fNDS);		// do not align
		fseek(fNDS, header.arm9_overlay_offset, SEEK_SET);
		unsigned int size = 0;
		CopyFromBin(arm9ovltablefilename, &size);
		header.arm9_overlay_size = size;
		overlay_files += size / sizeof(OverlayEntry);
		if (!size) header.arm9_overlay_offset = 0;
	}

	// COULD BE HERE: ARM9 overlay files, no padding before or between. end is padded with 0xFF's and then followed by ARM7 binary
	// fseek(fNDS, 1388772, SEEK_CUR);		// test for ASME

	// ARM7 binary
	header.arm7_rom_offset = (ftell(fNDS) + arm7_align) &~ arm7_align;
	fseek(fNDS, header.arm7_rom_offset, SEEK_SET);

	char *devkitProPATH;
	devkitProPATH = getenv("DEVKITPRO");

	#ifdef __WIN32__
	// convert to standard windows path
	if ( devkitProPATH && devkitProPATH[0] == '/' ) {
		devkitProPATH[0] = devkitProPATH[1];
		devkitProPATH[1] = ':';
	}
	#endif

	if ( !arm7filename) {
		char arm7PathName[MAXPATHLEN];

		if (!devkitProPATH) {
			fprintf(stderr,"No arm7 specified and DEVKITPRO missing from environment!\n");
			exit(1);
		}

		strcpy(arm7PathName,devkitProPATH);
		strcat(arm7PathName,"/libnds/default.elf");
		arm7filename = arm7PathName;
	}

	unsigned int entry_address = arm7Entry ? arm7Entry : (unsigned int)header.arm7_entry_address;		// template
	unsigned int ram_address = arm7RamAddress ? arm7RamAddress : (unsigned int)header.arm7_ram_address;		// template
	if (!ram_address && entry_address) ram_address = entry_address;
	if (!entry_address && ram_address) entry_address = ram_address;
	if (!ram_address) { ram_address = entry_address = 0x037f8000; }

	unsigned int size = 0;

	if (HasElfExtension(arm7filename))
		CopyFromElf(arm7filename, &entry_address, &ram_address, &size);
	else
		CopyFromBin(arm7filename, &size);

	header.arm7_entry_address = entry_address;
	header.arm7_ram_address = ram_address;
	header.arm7_size = ((size + 3) &~ 3);

	// ARM7 overlay table
	if (arm7ovltablefilename)
	{
		header.arm7_overlay_offset = ftell(fNDS);		// do not align
		fseek(fNDS, header.arm7_overlay_offset, SEEK_SET);
		unsigned int size = 0;
		CopyFromBin(arm7ovltablefilename, &size);
		header.arm7_overlay_size = size;
		overlay_files += size / sizeof(OverlayEntry);
		if (!size) header.arm7_overlay_offset = 0;
	}

	// COULD BE HERE: probably ARM7 overlay files, just like for ARM9
	//

	if (overlay_files && !overlaydir)
	{
		fprintf(stderr, "Overlay directory required!.\n");
		exit(1);
	}

	// filesystem
	//if (filerootdir || overlaydir)
	{
		// read directory structure
		free_file_id = overlay_files;
		free_dir_id++;
		directory_count++;
		TreeNode *filetree;
		if (filerootdir)
			filetree = ReadDirectory(new TreeNode(), filerootdir);
		else
			filetree = new TreeNode();		// dummy root node 0xF000

		// calculate offsets required for FNT and FAT
		_entry_start = 8*directory_count;		// names come after directory structs
		header.fnt_offset = (ftell(fNDS) + fnt_align) &~ fnt_align;
		header.fnt_size =
			_entry_start +		// directory structs
			total_name_size +	// total number of name characters for dirs and files
			directory_count*4 +	// directory: name length (1), dir id (2), end-character (1)
			file_count*1 +		// files: name length (1)
			- 3;				// root directory only has an end-character
		file_count += overlay_files;		// didn't take overlay files into FNT size, but have to be calculated into FAT size
		header.fat_offset = (header.fnt_offset + header.fnt_size + fat_align) &~ fat_align;
		header.fat_size = file_count * 8;		// each entry contains top & bottom offset

		// banner after FNT/FAT
		if (bannerfilename)
		{
			header.banner_offset = (header.fat_offset + header.fat_size + banner_align) &~ banner_align;
			file_top = header.banner_offset + 0x840;
			fseek(fNDS, header.banner_offset, SEEK_SET);
			if (bannertype == BANNER_IMAGE)
			{
				char * Ext = strrchr(bannerfilename, '.');
				if (Ext && strcasecmp(Ext, ".bmp") == 0)
					IconFromBMP();
				else if (Ext && strcasecmp(Ext, ".grf") == 0)
					IconFromGRF();
				else
				{
					fprintf(stderr,
						"Banner File Error: Unknown extension '%s'!\n", Ext);
					exit(1);
				}
			}
			else
			{
				CopyFromBin(bannerfilename, 0);
			}
		}
		else
		{
			file_top = header.fat_offset + header.fat_size;
			header.banner_offset = 0;
		}

		file_end = file_top;	// no file data as yet

		// add (hidden) overlay files
		for (unsigned int i=0; i<overlay_files; i++)
		{
			char s[32]; sprintf(s, OVERLAY_FMT, i/*free_file_id*/);
			AddFile(overlaydir, "/", s, i/*free_file_id*/);
			//free_file_id++;		// incremented up to overlay_files
		}

		// add all other (visible) files
		AddDirectory(filetree, "/", 0xF000, directory_count);
		fseek(fNDS, file_end, SEEK_SET);

		if (verbose)
		{
			printf("%u directories.\n", directory_count);
			printf("%u normal files.\n", file_count - overlay_files);
			printf("%u overlay files.\n", overlay_files);
		}
	}

	// --------------------------

	// align file size
	unsigned int newfilesize = file_end;	//ftell(fNDS);
	newfilesize = (newfilesize + 3) & ~3;	// align to 4 bytes
	header.application_end_offset = newfilesize;
	if (newfilesize != file_end ) {
		fseek(fNDS, newfilesize-1, SEEK_SET);
		fputc(0, fNDS);
	}
	// calculate device capacity
	newfilesize |= newfilesize >> 16; newfilesize |= newfilesize >> 8;
	newfilesize |= newfilesize >> 4; newfilesize |= newfilesize >> 2;
	newfilesize |= newfilesize >> 1; newfilesize++;
	if (newfilesize <= 128*1024) newfilesize = 128*1024;
	int devcap = -18;
	unsigned int x = newfilesize;
	while (x != 0) { x >>= 1; devcap++; }
	header.devicecap = (devcap < 0) ? 0 : devcap;

	// fix up header CRCs and write header
	header.logo_crc = CalcLogoCRC(header);
	header.header_crc = CalcHeaderCRC(header);
	fseek(fNDS, 0, SEEK_SET);
	fwrite(&header, 0x200, 1, fNDS);

	fclose(fNDS);
}
Example #25
0
FileNameDatabaseHeader::FndbOffset
FndbManager::ProcessFolder
(/*[in]*/ FileNameDatabaseHeader::FndbOffset	foParent,
 /*[in]*/ const char *				lpszParentPath,
 /*[in]*/ const char *				lpszFolderName,
 /*[in]*/ FileNameDatabaseHeader::FndbOffset	foFolderName)
{
  const size_t cReservedEntries = 0;
  
  if (currentLevel > deepestLevel)
    {
      deepestLevel = currentLevel;
    }

  vector<string> subDirectoryNames;
  subDirectoryNames.reserve (40);

  vector<FILENAMEINFO> fileNames;
  fileNames.reserve (100);

  bool done = false;

  PathName path (lpszParentPath, lpszFolderName);

  path.MakeAbsolute ();

  if (pCallback != 0)
    {
      if (! pCallback->OnProgress(currentLevel, path.Get()))
	{
	  throw OperationCancelledException ();
	}
      char * lpszSubDirNames = 0;
      char * lpszFileNames = 0;
      char * lpszFileNameInfos = 0;
      done =
	pCallback->ReadDirectory(path.Get(),
				 &lpszSubDirNames,
				 &lpszFileNames,
				 &lpszFileNameInfos);
      if (done)
	{
	  AutoMemoryPointer xxx (lpszSubDirNames);
	  AutoMemoryPointer xxy (lpszFileNames);
	  AutoMemoryPointer xxz (lpszFileNameInfos);
	  const char * lpsz = lpszSubDirNames;
	  while (*lpsz != 0)
	    {
	      subDirectoryNames.push_back (lpsz);
	      lpsz += strlen(lpsz) + 1;
	    }
	  lpsz = lpszFileNames;
	  const char * lpsz2 = lpszFileNameInfos;
	  while (*lpsz != 0)
	    {
	      FILENAMEINFO filenameinfo;
	      filenameinfo.FileName = lpsz;
	      lpsz += strlen(lpsz) + 1;
	      if (lpsz2 != 0)
		{
		  filenameinfo.Info = lpsz2;
		  lpsz2 += strlen(lpsz2) + 1;
		}
	      fileNames.push_back (filenameinfo);
	    }
	}
    }

  if (! done)
    {
      ReadDirectory (path.Get(), subDirectoryNames, fileNames);
    }

  numDirectories += static_cast<unsigned long>(subDirectoryNames.size());
  numFiles += static_cast<unsigned long>(fileNames.size());

  sort (subDirectoryNames.begin(),
	subDirectoryNames.end(),
	StringComparerIgnoringCase());
  sort (fileNames.begin(), fileNames.end(), COMPAREFILENAMEINFO());
  
  // store all names; build offset table
  vector<FileNameDatabaseHeader::FndbOffset> vecfndboff;
  vecfndboff.reserve ((storeFileNameInfo ? 2 : 1) * fileNames.size()
		      + 2 * subDirectoryNames.size()
		      + cReservedEntries);
  vector<FILENAMEINFO>::iterator it;
  vector<string>::iterator it2;
  for (it = fileNames.begin(); it != fileNames.end(); ++ it)
    {
      vecfndboff.push_back (PushBack((*it).FileName.c_str()));
    }
  for (it2 = subDirectoryNames.begin(); it2 != subDirectoryNames.end(); ++ it2)
    {
      vecfndboff.push_back (PushBack((*it2).c_str()));
    }
  for (it2 = subDirectoryNames.begin(); it2 != subDirectoryNames.end(); ++ it2)
    {
      vecfndboff.push_back (null_byte);
    }
  if (storeFileNameInfo)
    {
      for (it = fileNames.begin(); it != fileNames.end(); ++ it)
	{
	  vecfndboff.push_back (PushBack((*it).Info.c_str()));
	}
    }
  vecfndboff.insert (vecfndboff.end(), cReservedEntries, 0);
  
  // store directory data (excluding offsets)
  FileNameDatabaseDirectory dirdata;
  dirdata.Init ();
  dirdata.foName = foFolderName;
  dirdata.foParent = foParent;
  dirdata.numSubDirs = static_cast<unsigned long>(subDirectoryNames.size());
  dirdata.numFiles = static_cast<unsigned long>(fileNames.size());
  dirdata.capacity = static_cast<unsigned long>(vecfndboff.size());
  AlignMem (AlignmentDirectory);
  FileNameDatabaseHeader::FndbOffset foThis =
    PushBack(&dirdata, offsetof(FileNameDatabaseDirectory, table));

  if (vecfndboff.size() == 0)
    {
      return (foThis);
    }

  // reserve memory for offset table
  FileNameDatabaseHeader::FndbOffset foOffsetTable =
    ReserveMem(vecfndboff.size() * sizeof(FileNameDatabaseHeader::FndbOffset));
  
  // recurse into sub-directories and remember offsets
  PathName pathFolder (lpszParentPath, lpszFolderName, 0);
  size_t i = 0;
  ++ currentLevel;
  for (it2 = subDirectoryNames.begin();
       it2 != subDirectoryNames.end();
       ++ it2, ++ i)
    {
      vecfndboff[dirdata.numFiles + dirdata.numSubDirs + i]
	// <recursivecall>
	= ProcessFolder(foThis,
			pathFolder.Get(),
			it2->c_str(),
			vecfndboff[dirdata.numFiles + i]);
	// </recursivecall>
    }
  -- currentLevel;
  
  // store offset table
  SetMem (foOffsetTable,
	  &vecfndboff[0],
	  vecfndboff.size() * sizeof(FileNameDatabaseHeader::FndbOffset));
  
  return (foThis);
}
Example #26
0
nfsstat3 CNFS3Prog::ProcedureRENAME(void)
{
    char pathFrom[MAXPATHLEN], *pathTo;
    wcc_data fromdir_wcc, todir_wcc;
    nfsstat3 stat;

    PrintLog("RENAME");

    std::string dirFromName;
    std::string fileFromName;
    ReadDirectory(dirFromName, fileFromName);
    strcpy_s(pathFrom, GetFullPath(dirFromName, fileFromName));

    std::string dirToName;
    std::string fileToName;
    ReadDirectory(dirToName, fileToName);
    pathTo = GetFullPath(dirToName, fileToName);

    stat = CheckFile((char*)dirFromName.c_str(), pathFrom);

    fromdir_wcc.before.attributes_follow = GetFileAttributesForNFS((char*)dirFromName.c_str(), &fromdir_wcc.before.attributes);
    todir_wcc.before.attributes_follow = GetFileAttributesForNFS((char*)dirToName.c_str(), &todir_wcc.before.attributes);
    
    if (FileExists(pathTo)) {
		DWORD fileAttr = GetFileAttributes(pathTo);
		if ((fileAttr & FILE_ATTRIBUTE_DIRECTORY) && (fileAttr & FILE_ATTRIBUTE_REPARSE_POINT)) {
			if (RemoveFolder(pathTo) == 0) {
				stat = NFS3ERR_IO;
			}
		}
		else {
			if (!RemoveFile(pathTo)) {
				stat = NFS3ERR_IO;
			}
		}
    } 
    
    if (stat == NFS3_OK) {
        errno_t errorNumber = RenameDirectory(pathFrom, pathTo);

        if (errorNumber != 0) {
            char buffer[BUFFER_SIZE];
            strerror_s(buffer, BUFFER_SIZE, errorNumber);
            PrintLog(buffer);

            if (errorNumber == 13) {
                stat = NFS3ERR_ACCES;
            } else {
                stat = NFS3ERR_IO;
            }
        }
    }

    fromdir_wcc.after.attributes_follow = GetFileAttributesForNFS((char*)dirFromName.c_str(), &fromdir_wcc.after.attributes);
    todir_wcc.after.attributes_follow = GetFileAttributesForNFS((char*)dirToName.c_str(), &todir_wcc.after.attributes);

    Write(&stat);
    Write(&fromdir_wcc);
    Write(&todir_wcc);

    return stat;
}
Example #27
0
void ReadDirectory(const char* szPath, LPSTORAGE pStg)
{
    // recursive function
    USES_CONVERSION;
    WIN32_FIND_DATA fData;
    HANDLE h;
    char szNewPath[MAX_PATH];
    char szStorageName[100];
    char szStreamName[100];
	char szData[81];
    char* pch = NULL;

    LPSTORAGE pSubStg = NULL;
    LPSTREAM pStream = NULL;

    g_nIndent++;
    strcpy(szNewPath, szPath);
    strcat(szNewPath, "*.*");
    h = ::FindFirstFile(szNewPath, &fData);
    if (h == (HANDLE) 0xFFFFFFFF) return;  // can't find directory
    do {
      if (!strcmp(fData.cFileName, "..") ||
          !strcmp(fData.cFileName, ".") ) continue;
	  while((pch = strchr(fData.cFileName, '!')) != NULL) {
	      *pch = '|';
	  }
      if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		// It's a directory, so make a storage
        strcpy(szNewPath, szPath);
        strcat(szNewPath,fData.cFileName);
        strcat(szNewPath, "\\");

        strcpy(szStorageName, fData.cFileName);
        szStorageName[31] = '\0';    // limit imposed by OLE
        TRACE("%0.*sStorage = %s\n", (g_nIndent - 1) * 4,
              g_szBlanks, szStorageName);
        VERIFY(pStg->CreateStorage(T2COLE(szStorageName),
            STGM_CREATE | STGM_READWRITE | STGM_SHARE_EXCLUSIVE,
            0, 0, &pSubStg) == S_OK);
        ASSERT(pSubStg != NULL);
        ReadDirectory(szNewPath, pSubStg);
        pSubStg->Release();
      }
      else {
        if ((pch = strrchr(fData.cFileName, '.')) != NULL) {
          if (!stricmp(pch, ".TXT")) {
			// It's a text file, so make a stream
			strcpy(szStreamName, fData.cFileName);
            strcpy(szNewPath, szPath);
            strcat(szNewPath, szStreamName);
 			szStreamName[32] = '\0'; // OLE max length
            TRACE("%0.*sStream = %s\n", (g_nIndent - 1) * 4,
                g_szBlanks, szNewPath);
			CStdioFile file(szNewPath, CFile::modeRead);
            // Ignore zero-length files
			if(file.ReadString(szData, 80)) {
              TRACE("%s\n", szData);
              VERIFY(pStg->CreateStream(T2COLE(szStreamName),
                     STGM_CREATE | STGM_READWRITE | 
				     STGM_SHARE_EXCLUSIVE,
                     0, 0, &pStream) == S_OK);
              ASSERT(pStream != NULL);
			  // Include the null terminator in the stream
              pStream->Write(szData, strlen(szData) + 1, NULL);
              pStream->Release();
            }
          }
        }
      }
    } while (::FindNextFile(h, &fData));
    g_nIndent--;
}
Example #28
0
ISOFileSystem::TreeEntry *ISOFileSystem::GetFromPath(const std::string &path, bool catchError) {
	const size_t pathLength = path.length();

	if (pathLength == 0) {
		// Ah, the device!	"umd0:"
		return &entireISO;
	}

	size_t pathIndex = 0;

	// Skip "./"
	if (pathLength > pathIndex + 1 && path[pathIndex] == '.' && path[pathIndex + 1] == '/')
		pathIndex += 2;

	// Skip "/"
	if (pathLength > pathIndex && path[pathIndex] == '/')
		++pathIndex;

	if (pathLength <= pathIndex)
		return treeroot;

	TreeEntry *entry = treeroot;
	while (true) {
		if (!entry->valid) {
			ReadDirectory(entry);
		}
		TreeEntry *nextEntry = nullptr;
		std::string name = "";
		if (pathLength > pathIndex) {
			size_t nextSlashIndex = path.find_first_of('/', pathIndex);
			if (nextSlashIndex == std::string::npos)
				nextSlashIndex = pathLength;

			const std::string firstPathComponent = path.substr(pathIndex, nextSlashIndex - pathIndex);
			for (size_t i = 0; i < entry->children.size(); i++) {
				const std::string &n = entry->children[i]->name;
				if (firstPathComponent == n) {
					//yay we got it
					nextEntry = entry->children[i];
					name = n;
					break;
				}
			}
		}
		
		if (nextEntry) {
			entry = nextEntry;
			if (!entry->valid)
				ReadDirectory(entry);
			pathIndex += name.length();
			if (pathIndex < pathLength && path[pathIndex] == '/')
				++pathIndex;

			if (pathLength <= pathIndex)
				return entry;
		} else {
			if (catchError)
				ERROR_LOG(FILESYS,"File %s not found", path.c_str());

			return 0;
		}
	}
}