예제 #1
3
파일: sevenzip.c 프로젝트: pagolo/ezinstall
int Unseven(const char *filename, STRING **list)
{
  CFileInStream archiveStream;
  CLookToRead lookStream;
  CSzArEx db;
  SRes res;
  ISzAlloc allocImp;
  ISzAlloc allocTempImp;
  UInt16 *temp = NULL;
  size_t tempSize = 0;
  Bool do_save = (globaldata.gd_inidata->archive_dir && *(globaldata.gd_inidata->archive_dir))? False : True;
  char *subdir = NULL;
  // UInt32 parents[NUM_PARENTS_MAX];

//  printf("\n7z ANSI-C Decoder " MY_VERSION_COPYRIGHT_DATE "\n\n");

  if (!filename || !*filename) return -1; // error

  #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE)
  g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  #endif

  allocImp.Alloc = SzAlloc;
  allocImp.Free = SzFree;

  allocTempImp.Alloc = SzAllocTemp;
  allocTempImp.Free = SzFreeTemp;

  #ifdef UNDER_CE
  if (InFile_OpenW(&archiveStream.file, L"\test.7z"))
  #else
  if (InFile_Open(&archiveStream.file, filename))
  #endif
  {
    PrintError("can not open input file");
    return -1;
  }

  FileInStream_CreateVTable(&archiveStream);
  LookToRead_CreateVTable(&lookStream, False);
  
  lookStream.realStream = &archiveStream.s;
  LookToRead_Init(&lookStream);

  CrcGenerateTable();

  SzArEx_Init(&db);
  
  res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
  
    if (res == SZ_OK)
    {
      UInt32 i;

      /*
      if you need cache, use these 3 variables.
      if you use external function, you can make these variable as static.
      */
      UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
      Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
      size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

      for (i = 0; i < db.NumFiles; i++)
      {
        size_t offset = 0;
        size_t outSizeProcessed = 0;
        // const CSzFileItem *f = db.Files + i;
        size_t len;
        unsigned isDir = SzArEx_IsDir(&db, i);
        len = SzArEx_GetFileNameUtf16(&db, i, NULL);
        // len = SzArEx_GetFullNameLen(&db, i);

        if (len > tempSize)
        {
          SzFree(NULL, temp);
          tempSize = len;
          temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0]));
          if (!temp)
          {
            res = SZ_ERROR_MEM;
            break;
          }
        }

        SzArEx_GetFileNameUtf16(&db, i, temp);
/*
    { // progression output
      static char s[256];
      snprintf(s, 255, _("Extracting (%d%%)"), ((i + 1) * 100) / db.NumFiles);
      HandleSemaphoreText(s, list, !i ? 1 : 0);
    }*/
        if (isDir)
          ;//printf("/");
        else
        {
          res = SzArEx_Extract(&db, &lookStream.s, i,
              &blockIndex, &outBuffer, &outBufferSize,
              &offset, &outSizeProcessed,
              &allocImp, &allocTempImp);
          if (res != SZ_OK)
            break;
        }

        // write data to disk        
        {
          CSzFile outFile;
          size_t processedSize;
          size_t j;
          UInt16 *name = (UInt16 *)temp;
          const UInt16 *destPath = (const UInt16 *)name;
          WRes wres;
 
          for (j = 0; name[j] != 0; j++)
            if (name[j] == '/')
            {
              name[j] = 0;
              MyCreateDir(name, &subdir, &do_save);
              name[j] = CHAR_PATH_SEPARATOR;
            }
    
          if (isDir)
          {
            MyCreateDir(destPath, &subdir, &do_save);
            //printf("\n");
            continue;
          }
          if (do_save == False) continue;
          wres = OutFile_OpenUtf16(&outFile, destPath, &subdir, &do_save);
          if (wres == -1) continue;
          if (wres)
          {
            PrintError("can not open output file");
            res = SZ_ERROR_FAIL;
            break;
          }

          processedSize = outSizeProcessed;
          
          if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
          {
            PrintError(_("can not write output file"));
            res = SZ_ERROR_FAIL;
            break;
          }
          
          if (File_Close(&outFile))
          {
            PrintError(_("can not close output file"));
            res = SZ_ERROR_FAIL;
            break;
          }
          
          #ifdef USE_WINDOWS_FILE
          if (SzBitWithVals_Check(&db.Attribs, i))
            SetFileAttributesW(destPath, db.Attribs.Vals[i]);
          #endif
        }
        //printf("\n");
      }
      IAlloc_Free(&allocImp, outBuffer);
    }

  SzArEx_Free(&db, &allocImp);
  SzFree(NULL, temp);

  File_Close(&archiveStream.file);
  
  if (res == SZ_OK)
  {
    //printf("\nEverything is Ok\n");
    return 0;
  }
  
  if (res == SZ_ERROR_UNSUPPORTED)
    PrintError(_("decoder doesn't support this archive"));
  else if (res == SZ_ERROR_MEM)
    PrintError(_("can not allocate memory"));
  else if (res == SZ_ERROR_CRC)
    PrintError(_("CRC error"));
  else
    printf("<br />ERROR #%d\n", res);
  
  return -1;
}
예제 #2
0
파일: test2.c 프로젝트: smartmaster/sscli
int __cdecl main(int argc, char *argv[])
{

    BOOL              testPass       = TRUE;
    BOOL              bRc            = TRUE;
    HANDLE            hFile; 
    WIN32_FIND_DATA   findFileData;
    WIN32_FIND_DATAW  wFindFileData;
    DWORD              fileAttrib;

    const char* sBadFilePath = "bad/badPath.tmp";
    const char* sBadFileName = "badName.tmp";

    const WCHAR wBadFilePath[] = 
    {'w','b','a','d','/','b','a',
    'd','.','t','m','p','\0'};
    const WCHAR wBadFileName[] = 
    {'w','B','a','d','.','t','m','p','\0'};
    const WCHAR wDest[] = 
    {'w','d','e','s','t','.','t','m','p','\0'};


    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /*...................Test MoveFileW.............................*/

    /* test with an invalid path */
    bRc = MoveFileW(wBadFilePath,wDest);
    if(!bRc)
    {
        if(GetLastError()!= ERROR_PATH_NOT_FOUND)
        {
            Trace("MoveFileW: calling GetLastError() after moving a file"
                " with wrong path returned [%u] while it should return [%u]\n"
                ,GetLastError(), ERROR_PATH_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        testPass = FALSE; 
    }

    /* test with invalid file name */
    bRc = MoveFileW(wBadFileName,wDest);
    if(!bRc)
    { 
        if(GetLastError()!= ERROR_FILE_NOT_FOUND)
        {
            Trace("MoveFileW: calling GetLastError() after moving a file"
                " with wrong name returned [%u] while it should return [%u]\n"
                ,GetLastError(), ERROR_FILE_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("MoveFileW: managed to move a file with wrong name\n");     
        testPass = FALSE;
    }

    /*............. Test FindFirstFileA..................................*/

    /* test with an invalid file name */
    hFile = FindFirstFileA(sBadFileName,&findFileData );                    

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        if(GetLastError() != ERROR_FILE_NOT_FOUND)
        {
            Trace("FindFirstFileA: calling GetLastError() returned [%u] "
                "while it should return [%u] for a bad File Name\n",
                GetLastError(),ERROR_FILE_NOT_FOUND);   
            testPass = FALSE;
        }   

    } 
    else
    {
        Trace("FindFirstFileA: managed to find a file with an incorrect "
            "filename\n");   
        testPass = FALSE;

        if(!FindClose(hFile))
        {
            Trace("FindFirstFileA: Call to FindClose failed with ErrorCode"
                " [%u]\n", GetLastError());

        }

    }

    /* test with an invalid path */
    hFile = FindFirstFileA(sBadFilePath,&findFileData); 

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        if(GetLastError() != ERROR_PATH_NOT_FOUND)
        {
            Trace("FindFirstFileA: calling GetLastError() returned [%u] "
                "while it should return [%u] for a bad file path name\n",
                GetLastError(), ERROR_PATH_NOT_FOUND);   
            testPass = FALSE;
        }   

    } 
    else
    {
        Trace("FindFirstFileA: managed to find a file with an incorrect"
            " filename\n");   
        testPass = FALSE;
        /*this should not happen*/
        if(!FindClose(hFile))
        {
            Trace("FindFirstFileA: Call to FindClose Failed with ErrorCode"
                " [%u]\n", GetLastError());

        }

    }



    /*............. Test FindFirstFileW..................................*/

    /* test with an invalid file name */
    hFile = FindFirstFileW(wBadFileName,&wFindFileData );                    

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        if(GetLastError() != ERROR_FILE_NOT_FOUND)
        {
            Trace("FindFirstFileW: calling GetLastError() returned [%u] "
                "while it should return [%u] for a bad File Name\n",
                GetLastError(),ERROR_FILE_NOT_FOUND);   
            testPass = FALSE;
        }   

    } 
    else
    {
        Trace("FindFirstFileW: managed to find a file with an incorrect "
            "filename\n");   
        testPass = FALSE;

        if(!FindClose(hFile))
        {
            Trace("FindFirstFileW: Call to FindClose failed with ErrorCode"
                " [%u]\n", GetLastError());

        }

    }

    /* test with an invalid path */
    hFile = FindFirstFileW(wBadFilePath,&wFindFileData); 

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        if(GetLastError() != ERROR_PATH_NOT_FOUND)
        {
            Trace("FindFirstFileW: calling GetLastError() returned [%u] "
                "while it should return [%u] for a bad file path name\n",
                GetLastError(), ERROR_PATH_NOT_FOUND);   
            testPass = FALSE;
        }   

    } 
    else
    {
        Trace("FindFirstFileW: managed to find a file with an incorrect "
            "filename\n");   
        testPass = FALSE;
        /*this should not happen*/
        if(!FindClose(hFile))
        {
            Trace("FindFirstFileW: Call to FindClose Failed with ErrorCode "
                "[%u]\n", GetLastError());

        }

    }


    /*...................Test GetFileAttributesW.............................*/

    /* test with an invalid path */
    fileAttrib = GetFileAttributesW(wBadFilePath);
    if(fileAttrib == -1)
    {
        if(GetLastError()!= ERROR_PATH_NOT_FOUND)
        {
            Trace("GetFileAttributesW: calling GetLastError() after getting"
                " the attributes of a file with wrong path returned [%u]"
                " while it should return [%u]\n",
                GetLastError(), ERROR_PATH_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("GetFileAttributesW: managed to get the attrib of a file"
            " with wrong path\n");     
        testPass = FALSE;
    }

    /* test with invalid file name */
    fileAttrib = GetFileAttributesW(wBadFileName);
    if(fileAttrib == -1)
    { 
        if(GetLastError()!= ERROR_FILE_NOT_FOUND)
        {
            Trace("GetFileAttributesW: calling GetLastError() after getting"
                " the attributes of a file with wrong name returned [%u] "
                "while it should return [%u]\n"
                ,GetLastError(), ERROR_FILE_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("GetFileAttributesW: managed to get the attrib of a file"
            " with wrong name\n");     
        testPass = FALSE;
    }

    /*...................Test GetFileAttributesA.............................*/

    /* test with an invalid path */
    fileAttrib = GetFileAttributesA(sBadFilePath);
    if(fileAttrib == -1)
    {
        if(GetLastError()!= ERROR_PATH_NOT_FOUND)
        {
            Trace("GetFileAttributesA: calling GetLastError() after getting"
                " the attributes of a file with wrong path returned [%u] while"
                " it should return [%u]\n",
                GetLastError(), ERROR_PATH_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("GetFileAttributesA: managed to get the attrib of a file"
            " with wrong path\n");     
        testPass = FALSE;
    }

    /* test with invalid file name */
    fileAttrib = GetFileAttributesA(sBadFileName);
    if(fileAttrib == -1)
    { 
        if(GetLastError()!= ERROR_FILE_NOT_FOUND)
        {
            Trace("GetFileAttributesA: calling GetLastError() after getting "
                "the attributes of a file with wrong name returned [%u] "
                "while it should return [%u]\n"
                ,GetLastError(), ERROR_FILE_NOT_FOUND);
            testPass = FALSE;
        }

    }
    else
    {
        Trace("GetFileAttributesA: managed to get the attrib of a file with"
              " wrong name\n"); 
        testPass = FALSE;
    }




    /*...................Test SetFileAttributesW.............................*/

    /* test with an invalid path */
    bRc = SetFileAttributesW(wBadFilePath,FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        if(GetLastError()!= ERROR_PATH_NOT_FOUND)
        {
            Trace("SetFileAttributesW: calling GetLastError() after setting"
                " the attributes of a file with wrong path returned [%u] "
                "while it should return [%u]\n",
                GetLastError(), ERROR_PATH_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("SetFileAttributesW: managed to get the attrib of a file"
            " with wrong path\n");     
        testPass = FALSE;
    }

    /* test with invalid file name */
    bRc = SetFileAttributesW(wBadFileName,FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    { 
        if(GetLastError()!= ERROR_FILE_NOT_FOUND)
        {
            Trace("SetFileAttributesW: calling GetLastError() after setting"
                " the attributes of a file with wrong name returned [%u]"
                " while it should return [%u]\n",
                GetLastError(), ERROR_FILE_NOT_FOUND);
            testPass = FALSE;
        }

    }
    else
    {
        Trace("SetFileAttributesW: managed to get the attrib of a file with"
            " wrong name\n");     
        testPass = FALSE;
    }


    /*...................Test SetFileAttributesA.............................*/

    /* test with an invalid path */
    bRc = SetFileAttributesA(sBadFilePath,FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        if(GetLastError()!= ERROR_PATH_NOT_FOUND)
        {
            Trace("SetFileAttributesA: calling GetLastError() after setting "
                "the attributes of a file with wrong path returned [%u] "
                "while it should return [%u]\n"
                ,GetLastError(), ERROR_PATH_NOT_FOUND);
            testPass = FALSE;
        }
    }
    else
    {
        Trace("SetFileAttributesA: managed to get the attrib of a file "
            "with wrong path\n");     
        testPass = FALSE;
    }

    /* test with invalid file name */
    bRc = SetFileAttributesA(sBadFileName,FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    { 
        if(GetLastError()!= ERROR_FILE_NOT_FOUND)
        {
            Trace("SetFileAttributesA: calling GetLastError() after setting"
                " the attributes of a file with wrong name returned [%u]"
                " while it should return [%u]\n",
                GetLastError(), ERROR_FILE_NOT_FOUND);
            testPass = FALSE;
        }

    }
    else
    {
        Trace("SetFileAttributesA: managed to get the attrib of a file with "
            "wrong name\n");     
        testPass = FALSE;
    }


    if(! testPass)
    {
        Fail("");
    }
    PAL_Terminate();
    return PASS;
}
예제 #3
0
파일: movefilew.c 프로젝트: ArildF/masters
int __cdecl main(int argc, char *argv[])
{
    BOOL bRc = TRUE;
    BOOL bSuccess = TRUE;
    char results[40];
    FILE* resultsFile = NULL;
    int nCounter = 0;
    int i, j;
    WCHAR* wSource = NULL;
    WCHAR* wDest = NULL;
    WCHAR tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'};
    WCHAR tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'};
    HANDLE hFile;
    DWORD result;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* read in the expected results to compare with actual results */
    memset (results, 0, 20);
    resultsFile = fopen("expectedresults.txt", "r");
    if (resultsFile == NULL)
    {
        Fail("MoveFileW ERROR: Unable to open \"expectedresults.txt\"\n");
    }

    fgets(results, 20, resultsFile);
    fclose(resultsFile);

    /* clean the slate */
    removeAll();

    if (createExisting() != 0)
    {
        removeAll();
    }


    /* lpSource loop */
    for (i = 0; i < 4; i++)
    {
        /* lpDestination loop */
        for (j = 0; j < 4; j++)
        {
           
            wSource = convert(lpSource[i]);
            wDest = convert(lpDestination[j]);
            bRc = MoveFileW(wSource, wDest);
            free(wSource);
            free(wDest);
            if (bRc == FALSE)
            {
                if (results[nCounter] == '1')
                {
                    Trace("MoveFileW: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n", 
                        i, j, lpSource[i], lpDestination[j]);
                    bSuccess = FALSE;
                }
            }
            else
            {
                if (results[nCounter] == '0')
                {
                    Trace("MoveFileW: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n", 
                        i, j, lpSource[i], lpDestination[j]);
                    bSuccess = FALSE;
                }
            }

            /* undo the last move */
            removeAll();
            createExisting();

            nCounter++;
        }
    }

    removeAll();
    if (bSuccess == FALSE)
    {
        Fail("MoveFileW: Test Failed");
    }

    /* create the temp source file */
    hFile = CreateFileW(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,                        
                            FILE_ATTRIBUTE_NORMAL, 0);

    if( hFile == INVALID_HANDLE_VALUE )
    {
        Fail("MoveFileW: CreateFile failed to "
            "create the file correctly.\n");
    }

    bRc = CloseHandle(hFile);
    if(!bRc)
    {
        Trace("MoveFileW: CloseHandle failed to close the "
            "handle correctly. ERROR:%u\n",GetLastError());
        
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }
        Fail("");
    }

    /* set the file attributes to be readonly */
    bRc = SetFileAttributesW(tempSource, FILE_ATTRIBUTE_READONLY);
    if(!bRc)
    {
        Trace("MoveFileW: SetFileAttributes failed to set file "
            "attributes correctly. GetLastError returned %u\n",GetLastError());
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }
        Fail("");
    }

    /* move the file to the new location */
    bRc = MoveFileW(tempSource, tempDest);
    if(!bRc)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempSource);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
    }

        Fail("MoveFileW(%S, %S): GetFileAttributes "
            "failed to get the file's attributes.\n",
            tempSource, tempDest);
    }

    /* check that the newly moved file has the same file attributes
    as the original */
    result = GetFileAttributesW(tempDest);
    if(result == 0)
    {
        /* delete the created file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
            "the file's attributes.\n");
    }   

    if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: GetFileAttributes failed to get "
            "the correct file attributes.\n");
    }

    /* set the file attributes back to normal, to be deleted */
    bRc = SetFileAttributesW(tempDest, FILE_ATTRIBUTE_NORMAL);
    if(!bRc)
    {
        /* delete the newly moved file */
        bRc = DeleteFileW(tempDest);
        if(!bRc)
        {
            Fail("MoveFileW: DeleteFileW failed to delete the"
                "file correctly.\n");
        }

        Fail("MoveFileW: SetFileAttributes failed to set "
            "file attributes correctly.\n");
    }

    /* delete the newly moved file */
    bRc = DeleteFileW(tempDest);
    if(!bRc)
    {
        Fail("MoveFileW: DeleteFileW failed to delete the"
            "file correctly.\n");
    }

    PAL_Terminate(); 

    return PASS;
}
예제 #4
0
파일: attrib.c 프로젝트: Sunmonds/wine
int wmain(int argc, WCHAR *argv[])
{
    DWORD count;
    HANDLE hff;
    WIN32_FIND_DATAW fd;
    WCHAR flags[9] = {' ',' ',' ',' ',' ',' ',' ',' ','\0'};
    WCHAR name[128];
    WCHAR *param = argc >= 2 ? argv[1] : NULL;
    DWORD attrib_set = 0;
    DWORD attrib_clear = 0;
    WCHAR help_option[] = {'/','?','\0'};

    if (param && !strcmpW(param, help_option))
    {
        ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_HELP));
        return 0;
    }

    if (param && (param[0] == '+' || param[0] == '-')) {
        DWORD attrib = 0;
        /* FIXME: the real cmd can handle many more than two args; this should be in a loop */
        switch (param[1]) {
        case 'H': case 'h': attrib |= FILE_ATTRIBUTE_HIDDEN; break;
        case 'S': case 's': attrib |= FILE_ATTRIBUTE_SYSTEM; break;
        case 'R': case 'r': attrib |= FILE_ATTRIBUTE_READONLY; break;
        case 'A': case 'a': attrib |= FILE_ATTRIBUTE_ARCHIVE; break;
        default:
            ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_NYI));
            return 0;
        }
        switch (param[0]) {
        case '+': attrib_set = attrib; break;
        case '-': attrib_clear = attrib; break;
        }
        param = argc >= 3 ? argv[2] : NULL;
    }

    if (!param || strlenW(param) == 0) {
        static const WCHAR slashStarW[]  = {'\\','*','\0'};

        GetCurrentDirectoryW(sizeof(name)/sizeof(WCHAR), name);
        strcatW (name, slashStarW);
    } else {
        strcpyW(name, param);
    }

    hff = FindFirstFileW(name, &fd);
    if (hff == INVALID_HANDLE_VALUE) {
        ATTRIB_wprintf(ATTRIB_LoadMessage(STRING_FILENOTFOUND), name);
    }
    else {
        do {
            if (attrib_set || attrib_clear) {
                fd.dwFileAttributes &= ~attrib_clear;
                fd.dwFileAttributes |= attrib_set;
                if (!fd.dwFileAttributes)
                    fd.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL;
                SetFileAttributesW(name, fd.dwFileAttributes);
            } else {
                static const WCHAR fmt[] = {'%','1',' ',' ',' ','%','2','\n','\0'};
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
                    flags[0] = 'H';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
                    flags[1] = 'S';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
                    flags[2] = 'A';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
                    flags[3] = 'R';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
                    flags[4] = 'T';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
                    flags[5] = 'C';
                }
                ATTRIB_wprintf(fmt, flags, fd.cFileName);
                for (count=0; count < 8; count++) flags[count] = ' ';
            }
        } while (FindNextFileW(hff, &fd) != 0);
    }
    FindClose (hff);

    return 0;
}
예제 #5
0
파일: files.c 프로젝트: devyn/wine
static HRESULT DELNODE_recurse_dirtree(LPWSTR fname, DWORD flags)
{
    DWORD fattrs = GetFileAttributesW(fname);
    HRESULT ret = E_FAIL;

    static const WCHAR asterisk[] = {'*',0};
    static const WCHAR dot[] = {'.',0};
    static const WCHAR dotdot[] = {'.','.',0};

    if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
    {
        HANDLE hFindFile;
        WIN32_FIND_DATAW w32fd;
        BOOL done = TRUE;
        int fname_len = lstrlenW(fname);

        /* Generate a path with wildcard suitable for iterating */
        if (fname_len && fname[fname_len-1] != '\\') fname[fname_len++] = '\\';
        lstrcpyW(fname + fname_len, asterisk);

        if ((hFindFile = FindFirstFileW(fname, &w32fd)) != INVALID_HANDLE_VALUE)
        {
            /* Iterate through the files in the directory */
            for (done = FALSE; !done; done = !FindNextFileW(hFindFile, &w32fd))
            {
                TRACE("%s\n", debugstr_w(w32fd.cFileName));
                if (lstrcmpW(dot, w32fd.cFileName) != 0 &&
                    lstrcmpW(dotdot, w32fd.cFileName) != 0)
                {
                    lstrcpyW(fname + fname_len, w32fd.cFileName);
                    if (DELNODE_recurse_dirtree(fname, flags) != S_OK)
                    {
                        break; /* Failure */
                    }
                }
            }
            FindClose(hFindFile);
        }

        /* We're done with this directory, so restore the old path without wildcard */
        *(fname + fname_len) = '\0';

        if (done)
        {
            TRACE("%s: directory\n", debugstr_w(fname));
            if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryW(fname))
            {
                ret = S_OK;
            }
        }
    }
    else
    {
        TRACE("%s: file\n", debugstr_w(fname));
        if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileW(fname))
        {
            ret = S_OK;
        }
    }
    
    return ret;
}
예제 #6
0
bool CImageUtility::DeleteDir(const std::wstring& wstrTempDirect)
{ 
	bool bRet = true;
	if(true == wstrTempDirect.empty()) 
	{
		return false;
	}
	std::wstring wstrDirctory = wstrTempDirect;
	if (wstrTempDirect[wstrTempDirect.size() - 1] != TEXT('\\'))
	{
		wstrDirctory +=TEXT('\\');
	}
	std::wstring wstrFiles = wstrDirctory + TEXT("*.*");

	WIN32_FIND_DATA   FindFileData;
	HANDLE hFind = ::FindFirstFile(wstrFiles.c_str(), &FindFileData);

	while(hFind!=INVALID_HANDLE_VALUE)   
	{
		if( _wcsicmp(FindFileData.cFileName,L".") !=0 && _wcsicmp(FindFileData.cFileName,L"..") !=0 )
		{   
			std::wstring wstrDirChild = wstrDirctory + FindFileData.cFileName;
			if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
			{
				bRet = DeleteDir(wstrDirChild.c_str());
				if (!bRet)
				{
					bRet = false;
				}
			}
			else
			{ 
				SetFileAttributesW(wstrDirChild.c_str(),FILE_ATTRIBUTE_NORMAL);
				if(::DeleteFile(wstrDirChild.c_str()))
				{
					bRet = true;
				}
				else
				{
					bRet = false;
				} 
			}
		}
		if (!::FindNextFile(hFind, &FindFileData))
		{
			break;
		}
	}

	if (hFind != INVALID_HANDLE_VALUE)
	{
		::FindClose(hFind);
		hFind = INVALID_HANDLE_VALUE;
	}

	if(bRet)
	{
		if (::RemoveDirectoryW(wstrTempDirect.c_str()))
		{
			return true;
		}
	}
	return false;
}
예제 #7
0
static BOOL
RecursiveRemoveDir (LPCWSTR lpPath)
{
  WCHAR szPath[MAX_PATH];
  WIN32_FIND_DATAW FindData;
  HANDLE hFind;
  BOOL bResult;

  wcscpy (szPath, lpPath);
  wcscat (szPath, L"\\*.*");
  DPRINT ("Search path: '%S'\n", szPath);

  hFind = FindFirstFileW (szPath,
			  &FindData);
  if (hFind == INVALID_HANDLE_VALUE)
    return FALSE;

  bResult = TRUE;
  while (TRUE)
    {
      if (wcscmp (FindData.cFileName, L".") &&
	  wcscmp (FindData.cFileName, L".."))
	{
	  wcscpy (szPath, lpPath);
	  wcscat (szPath, L"\\");
	  wcscat (szPath, FindData.cFileName);
	  DPRINT ("File name: '%S'\n", szPath);

	  if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	    {
	      DPRINT ("Delete directory: '%S'\n", szPath);

	      if (!RecursiveRemoveDir (szPath))
		{
		  bResult = FALSE;
		  break;
		}

	      if (FindData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
		{
		  SetFileAttributesW (szPath,
				      FindData.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
		}

	      if (!RemoveDirectoryW (szPath))
		{
		  bResult = FALSE;
		  break;
		}
	    }
	  else
	    {
	      DPRINT ("Delete file: '%S'\n", szPath);

	      if (FindData.dwFileAttributes & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM))
		{
		  SetFileAttributesW (szPath,
				      FILE_ATTRIBUTE_NORMAL);
		}

	      if (!DeleteFileW (szPath))
		{
		  bResult = FALSE;
		  break;
		}
	    }
	}

      if (!FindNextFileW (hFind, &FindData))
	{
	  if (GetLastError () != ERROR_NO_MORE_FILES)
	    {
	      DPRINT1 ("Error: %lu\n", GetLastError());
	      bResult = FALSE;
	      break;
	    }

	  break;
	}
    }

  FindClose (hFind);

  return bResult;
}
예제 #8
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  #ifdef UNDER_CE
  LPWSTR
  #else
  LPSTR
  #endif
  lpCmdLine, int nCmdShow)
#endif
{
  CFileInStream archiveStream;
  CLookToRead lookStream;
  CSzArEx db;
  SRes res = SZ_OK;
  ISzAlloc allocImp;
  ISzAlloc allocTempImp;
  WCHAR sfxPath[MAX_PATH + 2];
  WCHAR path[MAX_PATH * 3 + 2];
  #ifndef UNDER_CE
  WCHAR workCurDir[MAX_PATH + 32];
  #endif
  size_t pathLen;
  DWORD winRes;
  const wchar_t *cmdLineParams;
  const char *errorMessage = NULL;
  Bool useShellExecute = True;
  DWORD exitCode = 0;

  #ifdef _CONSOLE
  SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  #else
  UNUSED_VAR(hInstance);
  UNUSED_VAR(hPrevInstance);
  UNUSED_VAR(lpCmdLine);
  UNUSED_VAR(nCmdShow);
  #endif

  CrcGenerateTable();

  allocImp.Alloc = SzAlloc;
  allocImp.Free = SzFree;

  allocTempImp.Alloc = SzAllocTemp;
  allocTempImp.Free = SzFreeTemp;

  FileInStream_CreateVTable(&archiveStream);
  LookToRead_CreateVTable(&lookStream, False);
 
  winRes = GetModuleFileNameW(NULL, sfxPath, MAX_PATH);
  if (winRes == 0 || winRes > MAX_PATH)
    return 1;
  {
    cmdLineParams = GetCommandLineW();
    #ifndef UNDER_CE
    {
      Bool quoteMode = False;
      for (;; cmdLineParams++)
      {
        wchar_t c = *cmdLineParams;
        if (c == L'\"')
          quoteMode = !quoteMode;
        else if (c == 0 || (c == L' ' && !quoteMode))
          break;
      }
    }
    #endif
  }

  {
    unsigned i;
    DWORD d;
    winRes = GetTempPathW(MAX_PATH, path);
    if (winRes == 0 || winRes > MAX_PATH)
      return 1;
    pathLen = wcslen(path);
    d = (GetTickCount() << 12) ^ (GetCurrentThreadId() << 14) ^ GetCurrentProcessId();
    
    for (i = 0;; i++, d += GetTickCount())
    {
      if (i >= 100)
      {
        res = SZ_ERROR_FAIL;
        break;
      }
      wcscpy(path + pathLen, L"7z");

      {
        wchar_t *s = path + wcslen(path);
        UInt32 value = d;
        unsigned k;
        for (k = 0; k < 8; k++)
        {
          unsigned t = value & 0xF;
          value >>= 4;
          s[7 - k] = (wchar_t)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
        }
        s[k] = '\0';
      }

      if (DoesFileOrDirExist(path))
        continue;
      if (CreateDirectoryW(path, NULL))
      {
        wcscat(path, WSTRING_PATH_SEPARATOR);
        pathLen = wcslen(path);
        break;
      }
      if (GetLastError() != ERROR_ALREADY_EXISTS)
      {
        res = SZ_ERROR_FAIL;
        break;
      }
    }
    
    #ifndef UNDER_CE
    wcscpy(workCurDir, path);
    #endif
    if (res != SZ_OK)
      errorMessage = "Can't create temp folder";
  }

  if (res != SZ_OK)
  {
    if (!errorMessage)
      errorMessage = "Error";
    PrintErrorMessage(errorMessage);
    return 1;
  }

  if (InFile_OpenW(&archiveStream.file, sfxPath) != 0)
  {
    errorMessage = "can not open input file";
    res = SZ_ERROR_FAIL;
  }
  else
  {
    UInt64 pos = 0;
    if (!FindSignature(&archiveStream.file, &pos))
      res = SZ_ERROR_FAIL;
    else if (File_Seek(&archiveStream.file, (Int64 *)&pos, SZ_SEEK_SET) != 0)
      res = SZ_ERROR_FAIL;
    if (res != 0)
      errorMessage = "Can't find 7z archive";
  }

  if (res == SZ_OK)
  {
    lookStream.realStream = &archiveStream.s;
    LookToRead_Init(&lookStream);
  }

  SzArEx_Init(&db);
  if (res == SZ_OK)
  {
    res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
  }
  
  if (res == SZ_OK)
  {
    UInt32 executeFileIndex = (UInt32)(Int32)-1;
    UInt32 minPrice = 1 << 30;
    UInt32 i;
    UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
    Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
    size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */
    
    for (i = 0; i < db.NumFiles; i++)
    {
      size_t offset = 0;
      size_t outSizeProcessed = 0;
      size_t len;
      WCHAR *temp;
      len = SzArEx_GetFileNameUtf16(&db, i, NULL);
      
      if (len >= MAX_PATH)
      {
        res = SZ_ERROR_FAIL;
        break;
      }
      
      temp = path + pathLen;
      
      SzArEx_GetFileNameUtf16(&db, i, temp);
      {
        res = SzArEx_Extract(&db, &lookStream.s, i,
          &blockIndex, &outBuffer, &outBufferSize,
          &offset, &outSizeProcessed,
          &allocImp, &allocTempImp);
        if (res != SZ_OK)
          break;
      }
      {
        CSzFile outFile;
        size_t processedSize;
        size_t j;
        size_t nameStartPos = 0;
        for (j = 0; temp[j] != 0; j++)
        {
          if (temp[j] == '/')
          {
            temp[j] = 0;
            MyCreateDir(path);
            temp[j] = CHAR_PATH_SEPARATOR;
            nameStartPos = j + 1;
          }
        }

        if (SzArEx_IsDir(&db, i))
        {
          MyCreateDir(path);
          continue;
        }
        else
        {
          unsigned extLen;
          const WCHAR *name = temp + nameStartPos;
          unsigned len = (unsigned)wcslen(name);
          unsigned nameLen = FindExt(temp + nameStartPos, &extLen);
          unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen);
          unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen);

          unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12));
          if (minPrice > price)
          {
            minPrice = price;
            executeFileIndex = i;
            useShellExecute = (extPrice != k_EXE_ExtIndex);
          }
         
          if (DoesFileOrDirExist(path))
          {
            errorMessage = "Duplicate file";
            res = SZ_ERROR_FAIL;
            break;
          }
          if (OutFile_OpenW(&outFile, path))
          {
            errorMessage = "Can't open output file";
            res = SZ_ERROR_FAIL;
            break;
          }
        }
  
        processedSize = outSizeProcessed;
        if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
        {
          errorMessage = "Can't write output file";
          res = SZ_ERROR_FAIL;
        }
        
        #ifdef USE_WINDOWS_FILE
        if (SzBitWithVals_Check(&db.MTime, i))
        {
          const CNtfsFileTime *t = db.MTime.Vals + i;
          FILETIME mTime;
          mTime.dwLowDateTime = t->Low;
          mTime.dwHighDateTime = t->High;
          SetFileTime(outFile.handle, NULL, NULL, &mTime);
        }
        #endif
        
        {
          SRes res2 = File_Close(&outFile);
          if (res != SZ_OK)
            break;
          if (res2 != SZ_OK)
          {
            res = res2;
            break;
          }
        }
        #ifdef USE_WINDOWS_FILE
        if (SzBitWithVals_Check(&db.Attribs, i))
          SetFileAttributesW(path, db.Attribs.Vals[i]);
        #endif
      }
    }

    if (res == SZ_OK)
    {
      if (executeFileIndex == (UInt32)(Int32)-1)
      {
        errorMessage = "There is no file to execute";
        res = SZ_ERROR_FAIL;
      }
      else
      {
        WCHAR *temp = path + pathLen;
        UInt32 j;
        SzArEx_GetFileNameUtf16(&db, executeFileIndex, temp);
        for (j = 0; temp[j] != 0; j++)
          if (temp[j] == '/')
            temp[j] = CHAR_PATH_SEPARATOR;
      }
    }
    IAlloc_Free(&allocImp, outBuffer);
  }
  SzArEx_Free(&db, &allocImp);

  File_Close(&archiveStream.file);

  if (res == SZ_OK)
  {
    HANDLE hProcess = 0;
    
    #ifndef UNDER_CE
    WCHAR oldCurDir[MAX_PATH + 2];
    oldCurDir[0] = 0;
    {
      DWORD needLen = GetCurrentDirectory(MAX_PATH + 1, oldCurDir);
      if (needLen == 0 || needLen > MAX_PATH)
        oldCurDir[0] = 0;
      SetCurrentDirectory(workCurDir);
    }
    #endif
    
    if (useShellExecute)
    {
      SHELLEXECUTEINFO ei;
      UINT32 executeRes;
      BOOL success;
      
      memset(&ei, 0, sizeof(ei));
      ei.cbSize = sizeof(ei);
      ei.lpFile = path;
      ei.fMask = SEE_MASK_NOCLOSEPROCESS
          #ifndef UNDER_CE
          | SEE_MASK_FLAG_DDEWAIT
          #endif
          /* | SEE_MASK_NO_CONSOLE */
          ;
      if (wcslen(cmdLineParams) != 0)
        ei.lpParameters = cmdLineParams;
      ei.nShow = SW_SHOWNORMAL; /* SW_HIDE; */
      success = ShellExecuteEx(&ei);
      executeRes = (UINT32)(UINT_PTR)ei.hInstApp;
      if (!success || (executeRes <= 32 && executeRes != 0))  /* executeRes = 0 in Windows CE */
        res = SZ_ERROR_FAIL;
      else
        hProcess = ei.hProcess;
    }
    else
    {
      STARTUPINFOW si;
      PROCESS_INFORMATION pi;
      WCHAR cmdLine[MAX_PATH * 3];

      wcscpy(cmdLine, path);
      wcscat(cmdLine, cmdLineParams);
      memset(&si, 0, sizeof(si));
      si.cb = sizeof(si);
      if (CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) == 0)
        res = SZ_ERROR_FAIL;
      else
      {
        CloseHandle(pi.hThread);
        hProcess = pi.hProcess;
      }
    }
    
    if (hProcess != 0)
    {
      WaitForSingleObject(hProcess, INFINITE);
      if (!GetExitCodeProcess(hProcess, &exitCode))
        exitCode = 1;
      CloseHandle(hProcess);
    }
    
    #ifndef UNDER_CE
    SetCurrentDirectory(oldCurDir);
    #endif
  }

  path[pathLen] = L'\0';
  RemoveDirWithSubItems(path);

  if (res == SZ_OK)
    return (int)exitCode;
  
  {
    if (res == SZ_ERROR_UNSUPPORTED)
      errorMessage = "Decoder doesn't support this archive";
    else if (res == SZ_ERROR_MEM)
      errorMessage = "Can't allocate required memory";
    else if (res == SZ_ERROR_CRC)
      errorMessage = "CRC error";
    else
    {
      if (!errorMessage)
        errorMessage = "ERROR";
    }
 
    if (errorMessage)
      PrintErrorMessage(errorMessage);
  }
  return 1;
}
예제 #9
0
파일: win_efile.c 프로젝트: DavidPajaro/otp
int
efile_rename(Efile_error* errInfo,	/* Where to return error codes. */
	     char* src,			/* Original name. */
	     char* dst)			/* New name. */
{
    DWORD srcAttr, dstAttr;
    WCHAR *wsrc = (WCHAR *) src;
    WCHAR *wdst = (WCHAR *) dst;
    
    if (MoveFileW(wsrc, wdst) != FALSE) {
	return 1;
    }

    errno = errno_map(GetLastError());
    srcAttr = GetFileAttributesW(wsrc);
    dstAttr = GetFileAttributesW(wdst);
    if (srcAttr == (DWORD) -1) {
	srcAttr = 0;
    }
    if (dstAttr == (DWORD) -1) {
	dstAttr = 0;
    }

    if (errno == EBADF) {
	errno = EACCES;
	return check_error(-1, errInfo);
    }
    if (errno == EACCES) {
	decode:
	if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) {
	    WCHAR srcPath[MAX_PATH], dstPath[MAX_PATH];
	    WCHAR *srcRest, *dstRest;
	    int size;

	    size = GetFullPathNameW(wsrc, MAX_PATH, srcPath, &srcRest);
	    if ((size == 0) || (size > MAX_PATH)) {
		return check_error(-1, errInfo);
	    }
	    size = GetFullPathNameW(wdst, MAX_PATH, dstPath, &dstRest);
	    if ((size == 0) || (size > MAX_PATH)) {
		return check_error(-1, errInfo);
	    }
	    if (srcRest == NULL) {
		srcRest = srcPath + wcslen(srcPath);
	    }
	    if (_wcsnicmp(srcPath, dstPath, srcRest - srcPath) == 0) {
		/*
		 * Trying to move a directory into itself.
		 */

		errno = EINVAL;
	    }
	    if (extract_root(srcPath)) {
		/*
		 * Attempt to move a root directory.  Never allowed.
		 */
		errno = EINVAL;
	    }

	    (void) extract_root(dstPath);
	    if (dstPath[0] == L'\0') {
		/*
		 * The filename was invalid.  (Don't know why,
		 * but play it safe.)
		 */
		errno = EINVAL;
	    }
	    if (_wcsicmp(srcPath, dstPath) != 0) {
		/*
		 * If src is a directory and dst filesystem != src
		 * filesystem, errno should be EXDEV.  It is very
		 * important to get this behavior, so that the caller
		 * can respond to a cross filesystem rename by
		 * simulating it with copy and delete.  The MoveFile
		 * system call already handles the case of moving a
		 * *file* between filesystems.
		 */

		errno = EXDEV;
	    }
	}

	/*
	 * Other types of access failure is that dst is a read-only
	 * filesystem, that an open file referred to src or dest, or that
	 * src or dest specified the current working directory on the
	 * current filesystem.  EACCES is returned for those cases.
	 */

    } else if (errno == EEXIST) {
	/*
	 * Reports EEXIST any time the target already exists.  If it makes
	 * sense, remove the old file and try renaming again.
	 */

	if (srcAttr & FILE_ATTRIBUTE_DIRECTORY) {
	    if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) {
		/*
		 * Overwrite empty dst directory with src directory.  The
		 * following call will remove an empty directory.  If it
		 * fails, it's because it wasn't empty.
		 */

		if (RemoveDirectoryW(wdst)) {
		    /*
		     * Now that that empty directory is gone, we can try
		     * renaming again.  If that fails, we'll put this empty
		     * directory back, for completeness.
		     */

		    if (MoveFileW(wsrc, wdst) != FALSE) {
			return 1;
		    }

		    /*
		     * Some new error has occurred.  Don't know what it
		     * could be, but report this one.
		     */

		    errno = errno_map(GetLastError());
		    CreateDirectoryW(wdst, NULL);
		    SetFileAttributesW(wdst, dstAttr);
		    if (errno == EACCES) {
			/*
			 * Decode the EACCES to a more meaningful error.
			 */

			goto decode;
		    }
		}
	    } else {	/* (dstAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */
		errno = ENOTDIR;
	    }
	} else {    /* (srcAttr & FILE_ATTRIBUTE_DIRECTORY) == 0 */
	    if (dstAttr & FILE_ATTRIBUTE_DIRECTORY) {
		errno = EISDIR;
	    } else {
		/*
		 * Overwrite existing file by:
		 * 
		 * 1. Rename existing file to temp name.
		 * 2. Rename old file to new name.
		 * 3. If success, delete temp file.  If failure,
		 *    put temp file back to old name.
		 */

		WCHAR tempName[MAX_PATH];
		int result, size;
		WCHAR *rest;
		
		size = GetFullPathNameW(wdst, MAX_PATH, tempName, &rest);
		if ((size == 0) || (size > MAX_PATH) || (rest == NULL)) {
		    return check_error(-1, errInfo);
		}
		*rest = L'\0';
		result = -1;
		if (GetTempFileNameW(tempName, L"erlr", 0, tempName) != 0) {
		    /*
		     * Strictly speaking, need the following DeleteFile and
		     * MoveFile to be joined as an atomic operation so no
		     * other app comes along in the meantime and creates the
		     * same temp file.
		     */
		     
		    DeleteFileW(tempName);
		    if (MoveFileW(wdst, tempName) != FALSE) {
			if (MoveFileW(wsrc, wdst) != FALSE) {
			    SetFileAttributesW(tempName, FILE_ATTRIBUTE_NORMAL);
			    DeleteFileW(tempName);
			    return 1;
			} else {
			    DeleteFileW(wdst);
			    MoveFileW(tempName, wdst);
			}
		    } 

		    /*
		     * Can't backup dst file or move src file.  Return that
		     * error.  Could happen if an open file refers to dst.
		     */

		    errno = errno_map(GetLastError());
		    if (errno == EACCES) {
			/*
			 * Decode the EACCES to a more meaningful error.
			 */

			goto decode;
		    }
		}
		return result;
	    }
	}
    }
    return check_error(-1, errInfo);
}
예제 #10
0
파일: misc.c 프로젝트: RareHare/reactos
/***********************************************************************
 *		SetupInitializeFileLogW(SETUPAPI.@)
 */
HSPFILELOG WINAPI SetupInitializeFileLogW(LPCWSTR LogFileName, DWORD Flags)
{
    struct FileLog * Log;
    HANDLE hLog;
    WCHAR Windir[MAX_PATH];
    DWORD ret;

    TRACE("%s, 0x%x\n",debugstr_w(LogFileName),Flags);

    if (Flags & SPFILELOG_SYSTEMLOG)
    {
        if (!pSetupIsUserAdmin() && !(Flags & SPFILELOG_QUERYONLY))
        {
            /* insufficient privileges */
            SetLastError(ERROR_ACCESS_DENIED);
            return INVALID_HANDLE_VALUE;
        }

        if (LogFileName || (Flags & SPFILELOG_FORCENEW))
        {
            /* invalid parameter */
            SetLastError(ERROR_INVALID_PARAMETER);
            return INVALID_HANDLE_VALUE;
        }

        ret = GetSystemWindowsDirectoryW(Windir, MAX_PATH);
        if (!ret || ret >= MAX_PATH)
        {
            /* generic failure */
            return INVALID_HANDLE_VALUE;
        }

        /* append path */
        wcscat(Windir, L"repair\\setup.log");
    }
    else
    {
        if (!LogFileName)
        {
            /* invalid parameter */
            SetLastError(ERROR_INVALID_PARAMETER);
            return INVALID_HANDLE_VALUE;
        }
        /* copy filename */
        wcsncpy(Windir, LogFileName, MAX_PATH);
    }

    if (FileExists(Windir, NULL))
    {
        /* take ownership */
        ret = TakeOwnershipOfFile(Windir);

        if (ret != ERROR_SUCCESS)
        {
            /* failed */
            SetLastError(ret);
            return INVALID_HANDLE_VALUE;
        }

        if (!SetFileAttributesW(Windir, FILE_ATTRIBUTE_NORMAL))
        {
            /* failed */
            return INVALID_HANDLE_VALUE;
        }

        if ((Flags & SPFILELOG_FORCENEW))
        {
            if (!DeleteFileW(Windir))
            {
                /* failed */
                return INVALID_HANDLE_VALUE;
            }
        }
    }

    /* open log file */
    hLog = CreateFileW(Windir,
                       (Flags & SPFILELOG_QUERYONLY) ? GENERIC_READ : GENERIC_WRITE,
                       FILE_SHARE_READ | FILE_SHARE_WRITE,
                       NULL,
                       OPEN_ALWAYS,
                       FILE_ATTRIBUTE_NORMAL,
                       NULL);

    if (hLog == INVALID_HANDLE_VALUE)
    {
        /* failed */
        return INVALID_HANDLE_VALUE;
    }

    /* close log handle */
    CloseHandle(hLog);

    /* allocate file log struct */
    Log = HeapAlloc(GetProcessHeap(), 0, sizeof(struct FileLog));
    if (!Log)
    {
        /* not enough memory */
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return INVALID_HANDLE_VALUE;
    }

    /* initialize log */
    Log->LogName = HeapAlloc(GetProcessHeap(), 0, (wcslen(Windir)+1) * sizeof(WCHAR));
    if (!Log->LogName)
    {
        /* not enough memory */
        HeapFree(GetProcessHeap(), 0, Log);
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return INVALID_HANDLE_VALUE;
    }

    wcscpy(Log->LogName, Windir);
    Log->ReadOnly = (Flags & SPFILELOG_QUERYONLY);
    Log->SystemLog = (Flags & SPFILELOG_SYSTEMLOG);

    return (HSPFILELOG)Log;
}
예제 #11
0
void FSDeleteFolderAndFiles(const unicode_t *dirName)
{
	if ( dirName == NULL ) return;
	if ( *dirName == 0 ) return;

#if defined(WIN32) || defined(_WIN32_WCE)

	UniString	findDir(dirName);

	if ( !findDir.EndWith(USTR("\\*.*")) )
	{
		if ( findDir.GetLastChar() == '\\' )
			findDir += L"*.*";
		else
			findDir += L"\\*.*";

		if ( findDir.GetCount() <= 6 ) return;
	}
	else
	{
		if ( findDir.GetCount() <= 6 ) return;
	}

	HANDLE hFind;

#if defined(_WIN32_WCE)
	WIN32_FIND_DATA findFileData;
	hFind = FindFirstFile(findDir.GetString(), &findFileData);
#else
	WIN32_FIND_DATAW findFileData;
	hFind = FindFirstFileW(findDir.GetString(), &findFileData);
#endif

	if (hFind != INVALID_HANDLE_VALUE) 
	{
		UniString	filePath;

		do
		{
			if ( wcscmp(findFileData.cFileName, L".") == 0 || wcscmp(findFileData.cFileName, L"..") == 0 )
				continue;

			filePath = dirName;
			filePath += L"\\";
			filePath += findFileData.cFileName;

			if ( findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
			{
				FSDeleteFolderAndFiles(filePath);
			}
			else
			{
				if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
					SetFileAttributesW(filePath.GetString(), FILE_ATTRIBUTE_NORMAL);

			#if defined(_WIN32_WCE)
				DeleteFile(filePath);
			#else
				DeleteFileW(filePath);
			#endif
			}
		}
	#if defined(_WIN32_WCE)
		while (FindNextFile(hFind, &findFileData) != 0);
	#else
		while (FindNextFileW(hFind, &findFileData) != 0);
	#endif

		FindClose(hFind);
	}

	RemoveDirectoryW(dirName);

#elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
	FSString	fsString(dirName);
	
	if ( fsString.GetCount() <= 1 ) return;

	_DeleteFolderAndFiles(fsString.GetString());
#else
	FSString	fsString(dirName);
	_DeleteFolderAndFiles(fsString.GetString());
#endif
}
예제 #12
0
BOOL WipeFileW(wchar_t *filename)
{
  DWORD Error=0,OldAttr,needed; void *SD=NULL; int correct_SD=FALSE;
  wchar_t dir[2*MAX_PATH],tmpname[MAX_PATH],*fileptr=wcsrchr(filename,L'\\');
  unsigned char *buffer=(unsigned char *)malloc(BUFF_SIZE);
  if(fileptr&&buffer)
  {
    OldAttr=GetFileAttributesW(filename);
    SetFileAttributesW(filename,OldAttr&(~FILE_ATTRIBUTE_READONLY));
    if(!GetFileSecurityW(filename,DACL_SECURITY_INFORMATION,NULL,0,&needed))
      if(GetLastError()==ERROR_INSUFFICIENT_BUFFER)
      {
        SD=malloc(needed);
        if(SD)
          if(GetFileSecurityW(filename,DACL_SECURITY_INFORMATION,SD,needed,&needed)) correct_SD=TRUE;
      }
    wcsncpy(dir,filename,fileptr-filename+1);
    dir[fileptr-filename+1]=0;
    if(GetTempFileNameW(dir,L"bc",0,tmpname))
    {
      if(MoveFileExW(filename,tmpname,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
      {
        HANDLE f=CreateFileW(tmpname,FILE_GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_SEQUENTIAL_SCAN,NULL);
        if(f!=INVALID_HANDLE_VALUE)
        {
          BY_HANDLE_FILE_INFORMATION info;
          if(GetFileInformationByHandle(f,&info))
          {
            unsigned long long size=(unsigned long long)info.nFileSizeLow+(unsigned long long)info.nFileSizeHigh*4294967296ULL;
            unsigned long long processed_size=0;
            while(size)
            {
              unsigned long outsize=(unsigned long)((size>=BUFF_SIZE)?BUFF_SIZE:size),transferred;
              WriteFile(f,buffer,outsize,&transferred,NULL);
              size-=outsize;
              processed_size+=outsize;
              if(UpdatePosInfo(0ULL,processed_size)) break;
            }
          }
          if((SetFilePointer(f,0,NULL,FILE_BEGIN)==INVALID_SET_FILE_POINTER)||(!SetEndOfFile(f))) Error=GetLastError();
          CloseHandle(f);
        }
        if(Error) MoveFileExW(tmpname,filename,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH);
        else if(!DeleteFileW(tmpname)) Error=GetLastError();
      }
      else
      {
        Error=GetLastError();
        DeleteFileW(tmpname);
      }
    } else Error=GetLastError();
    if(Error)
    {
      SetFileAttributesW(filename,OldAttr);
      if(correct_SD) SetFileSecurityW(filename,DACL_SECURITY_INFORMATION,SD);
    }
  }
  free(SD);
  free(buffer);
  if(Error)
  {
    SetLastError(Error);
    return FALSE;
  }
  return TRUE;
}
예제 #13
0
파일: attrib.c 프로젝트: Dimillian/wine
/* =========================================================================
 * Handle the processing for a single directory, optionally recursing into
 *  subdirectories if needed.
 * Parameters:
 *  rootdir      [I]   The directory to search in
 *  filespec     [I]   The filespec to search for
 *  recurse      [I]   Whether to recurse (search subdirectories before
 *                          current directory)
 *  includedirs  [I]   Whether to set directory attributes as well
 *  attrib_set   [I]   Attributes to set
 *  attrib_clear [I]   Attributes to clear
 *
 * Returns TRUE if at least one file displayed / modified
 * ========================================================================= */
static BOOL ATTRIB_processdirectory(const WCHAR *rootdir, const WCHAR *filespec,
                                    BOOL recurse, BOOL includedirs,
                                    DWORD attrib_set, DWORD attrib_clear)
{
    BOOL found = FALSE;
    WCHAR buffer[MAX_PATH];
    HANDLE hff;
    WIN32_FIND_DATAW fd;
    WCHAR flags[] = {' ',' ',' ',' ',' ',' ',' ',' ','\0'};
    static const WCHAR slashW[] = {'\\','\0'};

    WINE_TRACE("Processing dir '%s', spec '%s', %d,%x,%x\n",
               wine_dbgstr_w(rootdir), wine_dbgstr_w(filespec),
               recurse, attrib_set, attrib_clear);

    if (recurse) {

      /* Build spec to search for */
      strcpyW(buffer, rootdir);
      strcatW(buffer, starW);

      /* Search for directories in the location and recurse if necessary */
      WINE_TRACE("Searching for directories with '%s'\n", wine_dbgstr_w(buffer));
      hff = FindFirstFileW(buffer, &fd);
      if (hff != INVALID_HANDLE_VALUE) {
          do {
              const WCHAR dot[] = {'.', 0};
              const WCHAR dotdot[] = {'.', '.', 0};

              /* Only interested in directories, and not . nor .. */
              if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
                  !strcmpW(fd.cFileName, dot) || !strcmpW(fd.cFileName, dotdot))
                  continue;

              /* Build new root dir to go searching in */
              strcpyW(buffer, rootdir);
              strcatW(buffer, fd.cFileName);
              strcatW(buffer, slashW);
              ATTRIB_processdirectory(buffer, filespec, recurse, includedirs,
                                      attrib_set, attrib_clear);

          } while (FindNextFileW(hff, &fd) != 0);
      }
      FindClose (hff);
    }

    /* Build spec to search for */
    strcpyW(buffer, rootdir);
    strcatW(buffer, filespec);
    WINE_TRACE("Searching for files as '%s'\n", wine_dbgstr_w(buffer));

    /* Search for files in the location with the filespec supplied */
    hff = FindFirstFileW(buffer, &fd);
    if (hff != INVALID_HANDLE_VALUE) {
        do {
            const WCHAR dot[] = {'.', 0};
            const WCHAR dotdot[] = {'.', '.', 0};
            DWORD count;
            WINE_TRACE("Found '%s'\n", wine_dbgstr_w(fd.cFileName));

            if (!strcmpW(fd.cFileName, dot) || !strcmpW(fd.cFileName, dotdot))
                continue;

            if (!includedirs && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
              continue;

            if (attrib_set || attrib_clear) {
                fd.dwFileAttributes &= ~attrib_clear;
                fd.dwFileAttributes |= attrib_set;
                if (!fd.dwFileAttributes)
                    fd.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL;
                strcpyW(buffer, rootdir);
                strcatW(buffer, fd.cFileName);
                SetFileAttributesW(buffer, fd.dwFileAttributes);
                found = TRUE;
            } else {
                static const WCHAR fmt[] = {'%','1',' ',' ',' ',' ',' ','%','2','\n','\0'};
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
                    flags[4] = 'H';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
                    flags[1] = 'S';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
                    flags[0] = 'A';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
                    flags[5] = 'R';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
                    flags[6] = 'T';
                }
                if (fd.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) {
                    flags[7] = 'C';
                }
                strcpyW(buffer, rootdir);
                strcatW(buffer, fd.cFileName);
                ATTRIB_wprintf(fmt, flags, buffer);
                for (count = 0; count < (sizeof(flags)/sizeof(WCHAR) - 1); count++) flags[count] = ' ';
                found = TRUE;
            }
        } while (FindNextFileW(hff, &fd) != 0);
    }
    FindClose (hff);
    return found;
}
예제 #14
0
/* 1. set seafile-data directory to hidden
   2. set seafile folder icon (via Desktop.ini)
*/
static void
set_seafdir_attributes ()
{
    char *seafdir = g_path_get_dirname (applet->seafile_dir);
    char *icon_path = NULL;
    char *ini_file_path = NULL;

    wchar_t *seafile_dir_w = NULL; /* C:\\Seafile\\seafile-data */
    wchar_t *seafdir_w =  NULL;    /* C:\\Seafile */
    wchar_t *icon_path_w = NULL; /* C:\\Program Files\\Seafile\\bin\\seafdir.ico */
    wchar_t * ini_file_path_w = NULL; /* C:\\Seafile\\Desktop.ini */

    FILE *ini_file = NULL;

    seafile_dir_w = wchar_from_utf8 (applet->seafile_dir);
    seafdir_w = wchar_from_utf8 (seafdir);

    /* Make seafile-data directory hidden. */
    SetFileAttributesW (seafile_dir_w,
                        FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);

    /* Set seafdir folder icon. */
    SetFileAttributesW (seafdir_w, FILE_ATTRIBUTE_SYSTEM);
    ini_file_path = g_build_filename (seafdir, "Desktop.ini", NULL);
    ini_file_path_w = wchar_from_utf8 (ini_file_path);

    if (!(ini_file = g_fopen(ini_file_path, "w"))) {
        applet_warning ("failed to open %s\n", ini_file_path);
        goto out;
    }

    icon_path = g_build_filename (seafile_bin_dir, "seafdir.ico", NULL);

    char *ptr = icon_path;
    while (*ptr != '\0') {
        /* Replace all / with \ */
        if (*ptr == '/')
            *ptr = '\\';

        ptr++;
    }
    icon_path_w = wchar_from_utf8 (icon_path);

    fwprintf (ini_file, L"[.ShellClassInfo]\n");
    fwprintf (ini_file, L"IconFile=%s\n", icon_path_w);
    fwprintf (ini_file, L"IconIndex=0\n");

    /* Make the "Desktop.ini" file hidden. */
    SetFileAttributesW (ini_file_path_w,
                        FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);

out:
    g_free (seafile_dir_w);
    g_free (seafdir);
    g_free (seafdir_w);
    g_free (ini_file_path);
    g_free (ini_file_path_w);
    g_free (icon_path);
    g_free (icon_path_w);

    if (ini_file) fclose (ini_file);
}
예제 #15
0
INT_PTR CALLBACK
CFileDefExt::GeneralPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
            LPPROPSHEETPAGEW ppsp = (LPPROPSHEETPAGEW)lParam;

            if (ppsp == NULL || !ppsp->lParam)
                break;

            TRACE("WM_INITDIALOG hwnd %p lParam %p ppsplParam %S\n", hwndDlg, lParam, ppsp->lParam);

            CFileDefExt *pFileDefExt = (CFileDefExt*)ppsp->lParam;
            SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)pFileDefExt);
            pFileDefExt->InitGeneralPage(hwndDlg);
            break;
        }
        case WM_COMMAND:
            if (LOWORD(wParam) == 14024) /* Opens With - Change */
            {
                CFileDefExt *pFileDefExt = (CFileDefExt*)GetWindowLongPtr(hwndDlg, DWLP_USER);
                OPENASINFO oainfo;
                oainfo.pcszFile = pFileDefExt->m_wszPath;
                oainfo.pcszClass = NULL;
                oainfo.oaifInFlags = OAIF_REGISTER_EXT|OAIF_FORCE_REGISTRATION;
                return SUCCEEDED(SHOpenWithDialog(hwndDlg, &oainfo));
            }
            else if (LOWORD(wParam) == 14021 || LOWORD(wParam) == 14022 || LOWORD(wParam) == 14023) /* checkboxes */
                PropSheet_Changed(GetParent(hwndDlg), hwndDlg);
           else if (LOWORD(wParam) == 14001) /* Name */
            {
                if (HIWORD(wParam) == EN_CHANGE)
                    PropSheet_Changed(GetParent(hwndDlg), hwndDlg);
            }
            break;
        case WM_NOTIFY:
        {
            LPPSHNOTIFY lppsn = (LPPSHNOTIFY)lParam;
            if (lppsn->hdr.code == PSN_APPLY)
            {
                CFileDefExt *pFileDefExt = (CFileDefExt*)GetWindowLongPtr(hwndDlg, DWLP_USER);

                /* Update attributes first */
                DWORD dwAttr = GetFileAttributesW(pFileDefExt->m_wszPath);
                if (dwAttr)
                {
                    dwAttr &= ~(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_ARCHIVE);

                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14021, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_READONLY;
                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14022, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_HIDDEN;
                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14023, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_ARCHIVE;

                    if (!SetFileAttributesW(pFileDefExt->m_wszPath, dwAttr))
                        ERR("SetFileAttributesW failed\n");
                }

                /* Update filename now */
                WCHAR wszBuf[MAX_PATH];
                StringCchCopyW(wszBuf, _countof(wszBuf), pFileDefExt->m_wszPath);
                LPWSTR pwszFilename = PathFindFileNameW(wszBuf);
                UINT cchFilenameMax = _countof(wszBuf) - (pwszFilename - wszBuf);
                if (GetDlgItemTextW(hwndDlg, 14001, pwszFilename, cchFilenameMax))
                {
                    if (!MoveFileW(pFileDefExt->m_wszPath, wszBuf))
                        ERR("MoveFileW failed\n");
                }
                    
                SetWindowLongPtr(hwndDlg, DWL_MSGRESULT, PSNRET_NOERROR);
                return TRUE;
            }
            break;
        }
        default:
            break;
    }

    return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_microsoft_tfs_jni_internal_filesystem_NativeFileSystem_nativeSetAttributes(
    JNIEnv *env, jclass cls, jstring jFilepath, jobject jAttributes)
{
    jclass attributesClass;
    jmethodID isReadOnlyMethod, isHiddenMethod, isSystemMethod, isArchiveMethod, isNotContentIndexedMethod;
    jobject timeObj = NULL, attributesObj = NULL;
    const WCHAR *filepath;
    DWORD attributes;
    jboolean readonly, hidden, system, archive, notContentIndexed;
    BOOL result;

    /*
     * Ensure that we can load the necessary classes for our file attributes return value.
     * Note that these methods will return NULL on failure and raise an exception that will
     * be handled when we return to Java.
     */
    attributesClass = (*env)->FindClass(env, "com/microsoft/tfs/jni/FileSystemAttributes");

    if (attributesClass == NULL)
        return JNI_FALSE;

    isReadOnlyMethod = (*env)->GetMethodID(env, attributesClass, "isReadOnly", "()Z");
    isHiddenMethod = (*env)->GetMethodID(env, attributesClass, "isHidden", "()Z");
    isSystemMethod = (*env)->GetMethodID(env, attributesClass, "isSystem", "()Z");
    isArchiveMethod = (*env)->GetMethodID(env, attributesClass, "isArchive", "()Z");
    isNotContentIndexedMethod = (*env)->GetMethodID(env, attributesClass, "isNotContentIndexed", "()Z");

    if (isReadOnlyMethod == NULL || isHiddenMethod == NULL || isSystemMethod == NULL || isArchiveMethod == NULL
        || isNotContentIndexedMethod == NULL)
        return JNI_FALSE;

    readonly = (*env)->CallBooleanMethod(env, jAttributes, isReadOnlyMethod);
    hidden = (*env)->CallBooleanMethod(env, jAttributes, isHiddenMethod);
    system = (*env)->CallBooleanMethod(env, jAttributes, isSystemMethod);
    archive = (*env)->CallBooleanMethod(env, jAttributes, isArchiveMethod);
    notContentIndexed = (*env)->CallBooleanMethod(env, jAttributes, isNotContentIndexedMethod);

    /*
     * Get the file path.
     */
    if (jFilepath == NULL)
        return JNI_FALSE;

    if ((filepath = javaStringToPlatformChars(env, jFilepath)) == NULL)
	{
		// String allocation failed, exception already thrown
		return JNI_FALSE;
	}

    /*
     * Get the current attributes
     */
    attributes = GetFileAttributesW(filepath);

    if (attributes == INVALID_FILE_ATTRIBUTES)
    {
        result = FALSE;
    }
    else
    {
        if (readonly == JNI_TRUE)
        {
            attributes |= FILE_ATTRIBUTE_READONLY;
        }
        else
        {
            attributes &= (~FILE_ATTRIBUTE_READONLY);
        }

        if (hidden == JNI_TRUE)
        {
            attributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        else
        {
            attributes &= (~FILE_ATTRIBUTE_HIDDEN);
        }

        if (system == JNI_TRUE)
        {
            attributes |= FILE_ATTRIBUTE_SYSTEM;
        }
        else
        {
            attributes &= (~FILE_ATTRIBUTE_SYSTEM);
        }

        if (archive == JNI_TRUE)
        {
            attributes |= FILE_ATTRIBUTE_ARCHIVE;
        }
        else
        {
            attributes &= (~FILE_ATTRIBUTE_ARCHIVE);
        }

        if (notContentIndexed == JNI_TRUE)
        {
            attributes |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
        }
        else
        {
            attributes &= (~FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
        }

        result = SetFileAttributesW(filepath, attributes);
    }

    releasePlatformChars(env, jFilepath, filepath);

    return (result == TRUE) ? JNI_TRUE : JNI_FALSE;
}
예제 #17
0
파일: 7zFile.c 프로젝트: huairen/JArchive
static size_t FolderOutStream_Write2(CFolderOutStream *p, const void *data, size_t size)
{
	SizeT processedSize = 0;
	UInt16 *fullPath = NULL;
	SizeT pathLen = 0;
	SizeT curSize = 0;
	SRes res = SZ_OK;
	UInt32 i;
	SizeT dirLen = 0;
	
	if(p->outputDir)
		dirLen = wcslen(p->outputDir);

	while(size != 0)
	{
		if(p->file.handle == INVALID_HANDLE_VALUE)
		{
			UInt16 *filename;
			UInt32 index  = p->startIndex + p->currentIndex;
			const CSzFileItem *fileItem = p->ar->db.Files + index;
			SizeT len = SzArEx_GetFileNameUtf16(p->ar, index, NULL);
			if(len + dirLen > pathLen)
			{
				free(fullPath);
				pathLen = len + dirLen;
				fullPath = (UInt16*)malloc(pathLen * sizeof(fullPath[0]));
				if(fullPath == 0)
				{
					res = SZ_ERROR_MEM;
					break;
				}

				if(p->outputDir)
					wcscpy_s(fullPath,pathLen,p->outputDir);
			}

			filename = fullPath + dirLen;
			SzArEx_GetFileNameUtf16(p->ar, index, filename);
			for (i = 0; fullPath[i] != 0 && i<pathLen; i++)
				if (fullPath[i] == '/')
				{
					fullPath[i] = 0;
					CreateDirectoryW(fullPath,NULL);
					fullPath[i] = CHAR_PATH_SEPARATOR;
				}
				
			if (fileItem->IsDir)
			{
				CreateDirectoryW(fullPath,NULL);
				continue;
			}
			else if(OutFile_OpenW(&p->file, fullPath))
			{
				res = SZ_ERROR_FAIL;
				break;
			}

#ifdef _SZ_ALLOC_DEBUG
			wprintf(L"\nExtract: %s", fullPath);
#endif
			p->fileSize = fileItem->Size;
			p->checkCrc = fileItem->CrcDefined;
			p->crc = CRC_INIT_VAL;
		}

		curSize = size < p->fileSize ? size : (SizeT)p->fileSize;
		if(S_OK != File_Write(&p->file, data, &curSize))
		{
			File_Close(&p->file);
			res = SZ_ERROR_FAIL;
			break;
		}

		if(p->checkCrc)
			p->crc = CrcUpdate(p->crc,data,curSize);

		data = (const Byte*)data + curSize;
		size -= curSize;
		p->fileSize -= curSize;
		p->folderSize -= curSize;
		processedSize += curSize;

		if(p->fileSize == 0)
		{
			UInt32 index  = p->startIndex + p->currentIndex;
			const CSzFileItem *fileItem = p->ar->db.Files + index;

			p->currentIndex += 1;

			if(fileItem->MTimeDefined)
				SetFileTime(p->file.handle,NULL,NULL,(const FILETIME*)&fileItem->MTime);

			File_Close(&p->file);

			if(fileItem->AttribDefined)
				SetFileAttributesW(fullPath, fileItem->Attrib);

			if(fileItem->CrcDefined && CRC_GET_DIGEST(p->crc) != fileItem->Crc)
			{
				res = SZ_ERROR_CRC;
				break;
			}
		}
	}

	free(fullPath);
	return processedSize;
}
예제 #18
0
파일: 7zMain.c 프로젝트: mcmilk/7-Zip-zstd
int MY_CDECL main(int numargs, char *args[])
{
  ISzAlloc allocImp;
  ISzAlloc allocTempImp;

  CFileInStream archiveStream;
  CLookToRead2 lookStream;
  CSzArEx db;
  SRes res;
  UInt16 *temp = NULL;
  size_t tempSize = 0;
  // UInt32 parents[NUM_PARENTS_MAX];

  Print("\n7z Decoder " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE "\n\n");

  if (numargs == 1)
  {
    Print(
      "Usage: 7zDec <command> <archive_name>\n\n"
      "<Commands>\n"
      "  e: Extract files from archive (without using directory names)\n"
      "  l: List contents of archive\n"
      "  t: Test integrity of archive\n"
      "  x: eXtract files with full paths\n");
    return 0;
  }

  if (numargs < 3)
  {
    PrintError("incorrect command");
    return 1;
  }

  #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE)
  g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  #endif


  allocImp = g_Alloc;
  allocTempImp = g_Alloc;

  #ifdef UNDER_CE
  if (InFile_OpenW(&archiveStream.file, L"\test.7z"))
  #else
  if (InFile_Open(&archiveStream.file, args[2]))
  #endif
  {
    PrintError("can not open input file");
    return 1;
  }

  FileInStream_CreateVTable(&archiveStream);
  LookToRead2_CreateVTable(&lookStream, False);
  lookStream.buf = NULL;

  res = SZ_OK;

  {
    lookStream.buf = (Byte *)ISzAlloc_Alloc(&allocImp, kInputBufSize);
    if (!lookStream.buf)
      res = SZ_ERROR_MEM;
    else
    {
      lookStream.bufSize = kInputBufSize;
      lookStream.realStream = &archiveStream.vt;
      LookToRead2_Init(&lookStream);
    }
  }
    
  CrcGenerateTable();
    
  SzArEx_Init(&db);
    
  if (res == SZ_OK)
  {
    res = SzArEx_Open(&db, &lookStream.vt, &allocImp, &allocTempImp);
  }
  
  if (res == SZ_OK)
  {
    char *command = args[1];
    int listCommand = 0, testCommand = 0, fullPaths = 0;
    
    if (strcmp(command, "l") == 0) listCommand = 1;
    else if (strcmp(command, "t") == 0) testCommand = 1;
    else if (strcmp(command, "e") == 0) { }
    else if (strcmp(command, "x") == 0) { fullPaths = 1; }
    else
    {
      PrintError("incorrect command");
      res = SZ_ERROR_FAIL;
    }

    if (res == SZ_OK)
    {
      UInt32 i;

      /*
      if you need cache, use these 3 variables.
      if you use external function, you can make these variable as static.
      */
      UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
      Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
      size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

      for (i = 0; i < db.NumFiles; i++)
      {
        size_t offset = 0;
        size_t outSizeProcessed = 0;
        // const CSzFileItem *f = db.Files + i;
        size_t len;
        unsigned isDir = SzArEx_IsDir(&db, i);
        if (listCommand == 0 && isDir && !fullPaths)
          continue;
        len = SzArEx_GetFileNameUtf16(&db, i, NULL);
        // len = SzArEx_GetFullNameLen(&db, i);

        if (len > tempSize)
        {
          SzFree(NULL, temp);
          tempSize = len;
          temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0]));
          if (!temp)
          {
            res = SZ_ERROR_MEM;
            break;
          }
        }

        SzArEx_GetFileNameUtf16(&db, i, temp);
        /*
        if (SzArEx_GetFullNameUtf16_Back(&db, i, temp + len) != temp)
        {
          res = SZ_ERROR_FAIL;
          break;
        }
        */

        if (listCommand)
        {
          char attr[8], s[32], t[32];
          UInt64 fileSize;

          GetAttribString(SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0, isDir, attr);

          fileSize = SzArEx_GetFileSize(&db, i);
          UInt64ToStr(fileSize, s, 10);
          
          if (SzBitWithVals_Check(&db.MTime, i))
            ConvertFileTimeToString(&db.MTime.Vals[i], t);
          else
          {
            size_t j;
            for (j = 0; j < 19; j++)
              t[j] = ' ';
            t[j] = '\0';
          }
          
          Print(t);
          Print(" ");
          Print(attr);
          Print(" ");
          Print(s);
          Print("  ");
          res = PrintString(temp);
          if (res != SZ_OK)
            break;
          if (isDir)
            Print("/");
          PrintLF();
          continue;
        }

        Print(testCommand ?
            "Testing    ":
            "Extracting ");
        res = PrintString(temp);
        if (res != SZ_OK)
          break;
        
        if (isDir)
          Print("/");
        else
        {
          res = SzArEx_Extract(&db, &lookStream.vt, i,
              &blockIndex, &outBuffer, &outBufferSize,
              &offset, &outSizeProcessed,
              &allocImp, &allocTempImp);
          if (res != SZ_OK)
            break;
        }
        
        if (!testCommand)
        {
          CSzFile outFile;
          size_t processedSize;
          size_t j;
          UInt16 *name = (UInt16 *)temp;
          const UInt16 *destPath = (const UInt16 *)name;
 
          for (j = 0; name[j] != 0; j++)
            if (name[j] == '/')
            {
              if (fullPaths)
              {
                name[j] = 0;
                MyCreateDir(name);
                name[j] = CHAR_PATH_SEPARATOR;
              }
              else
                destPath = name + j + 1;
            }
    
          if (isDir)
          {
            MyCreateDir(destPath);
            PrintLF();
            continue;
          }
          else if (OutFile_OpenUtf16(&outFile, destPath))
          {
            PrintError("can not open output file");
            res = SZ_ERROR_FAIL;
            break;
          }

          processedSize = outSizeProcessed;
          
          if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
          {
            PrintError("can not write output file");
            res = SZ_ERROR_FAIL;
            break;
          }

          #ifdef USE_WINDOWS_FILE
          {
            FILETIME mtime, ctime;
            FILETIME *mtimePtr = NULL;
            FILETIME *ctimePtr = NULL;

            if (SzBitWithVals_Check(&db.MTime, i))
            {
              const CNtfsFileTime *t = &db.MTime.Vals[i];
              mtime.dwLowDateTime = (DWORD)(t->Low);
              mtime.dwHighDateTime = (DWORD)(t->High);
              mtimePtr = &mtime;
            }
            if (SzBitWithVals_Check(&db.CTime, i))
            {
              const CNtfsFileTime *t = &db.CTime.Vals[i];
              ctime.dwLowDateTime = (DWORD)(t->Low);
              ctime.dwHighDateTime = (DWORD)(t->High);
              ctimePtr = &ctime;
            }
            if (mtimePtr || ctimePtr)
              SetFileTime(outFile.handle, ctimePtr, NULL, mtimePtr);
          }
          #endif
          
          if (File_Close(&outFile))
          {
            PrintError("can not close output file");
            res = SZ_ERROR_FAIL;
            break;
          }
          
          #ifdef USE_WINDOWS_FILE
          if (SzBitWithVals_Check(&db.Attribs, i))
          {
            UInt32 attrib = db.Attribs.Vals[i];
            /* p7zip stores posix attributes in high 16 bits and adds 0x8000 as marker.
               We remove posix bits, if we detect posix mode field */
            if ((attrib & 0xF0000000) != 0)
              attrib &= 0x7FFF;
            SetFileAttributesW((LPCWSTR)destPath, attrib);
          }
          #endif
        }
        PrintLF();
      }
      ISzAlloc_Free(&allocImp, outBuffer);
    }
  }

  SzFree(NULL, temp);
  SzArEx_Free(&db, &allocImp);
  ISzAlloc_Free(&allocImp, lookStream.buf);

  File_Close(&archiveStream.file);
  
  if (res == SZ_OK)
  {
    Print("\nEverything is Ok\n");
    return 0;
  }
  
  if (res == SZ_ERROR_UNSUPPORTED)
    PrintError("decoder doesn't support this archive");
  else if (res == SZ_ERROR_MEM)
    PrintError("can not allocate memory");
  else if (res == SZ_ERROR_CRC)
    PrintError("CRC error");
  else
  {
    char s[32];
    UInt64ToStr(res, s, 0);
    PrintError(s);
  }
  
  return 1;
}
예제 #19
0
static int
op_removesl(ops_t *ops, void *data, const char *src, const char *dst)
{
	const char *const delete_prg = (ops == NULL)
	                             ? cfg.delete_prg
	                             : ops->delete_prg;
	if(delete_prg[0] != '\0')
	{
#ifndef _WIN32
		char *escaped;
		char cmd[2*PATH_MAX + 1];
		const int cancellable = (data == NULL);

		escaped = shell_like_escape(src, 0);
		if(escaped == NULL)
		{
			return -1;
		}

		snprintf(cmd, sizeof(cmd), "%s %s", delete_prg, escaped);
		free(escaped);

		LOG_INFO_MSG("Running trash command: \"%s\"", cmd);
		return run_operation_command(ops, cmd, cancellable);
#else
		char cmd[PATH_MAX*2 + 1];
		snprintf(cmd, sizeof(cmd), "%s \"%s\"", delete_prg, src);
		to_back_slash(cmd);

		return os_system(cmd);
#endif
	}

	if(!ops_uses_syscalls(ops))
	{
#ifndef _WIN32
		char *escaped;
		char cmd[16 + PATH_MAX];
		int result;
		const int cancellable = data == NULL;

		escaped = shell_like_escape(src, 0);
		if(escaped == NULL)
			return -1;

		snprintf(cmd, sizeof(cmd), "rm -rf %s", escaped);
		LOG_INFO_MSG("Running rm command: \"%s\"", cmd);
		result = run_operation_command(ops, cmd, cancellable);

		free(escaped);
		return result;
#else
		if(is_dir(src))
		{
			char path[PATH_MAX];
			int err;

			copy_str(path, sizeof(path), src);
			to_back_slash(path);

			wchar_t *utf16_path = utf8_to_utf16(path);

			/* SHFileOperationW requires pFrom to be double-nul terminated. */
			const size_t len = wcslen(utf16_path);
			utf16_path = reallocarray(utf16_path, len + 1U + 1U, sizeof(*utf16_path));
			utf16_path[len + 1U] = L'\0';

			SHFILEOPSTRUCTW fo = {
				.hwnd = NULL,
				.wFunc = FO_DELETE,
				.pFrom = utf16_path,
				.pTo = NULL,
				.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI,
			};
			err = SHFileOperationW(&fo);

			log_msg("Error: %d", err);
			free(utf16_path);

			return err;
		}
		else
		{
			int ok;
			wchar_t *const utf16_path = utf8_to_utf16(src);
			DWORD attributes = GetFileAttributesW(utf16_path);
			if(attributes & FILE_ATTRIBUTE_READONLY)
			{
				SetFileAttributesW(utf16_path, attributes & ~FILE_ATTRIBUTE_READONLY);
			}

			ok = DeleteFileW(utf16_path);
			if(!ok)
			{
				LOG_WERROR(GetLastError());
			}

			free(utf16_path);
			return !ok;
		}
#endif
	}