int Unseven(const char *filename, STRING **list) { CFileInStream archiveStream; CLookToRead lookStream; CSzArEx db; SRes res; ISzAlloc allocImp; ISzAlloc allocTempImp; UInt16 *temp = NULL; size_t tempSize = 0; Bool do_save = (globaldata.gd_inidata->archive_dir && *(globaldata.gd_inidata->archive_dir))? False : True; char *subdir = NULL; // UInt32 parents[NUM_PARENTS_MAX]; // printf("\n7z ANSI-C Decoder " MY_VERSION_COPYRIGHT_DATE "\n\n"); if (!filename || !*filename) return -1; // error #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE) g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; #endif allocImp.Alloc = SzAlloc; allocImp.Free = SzFree; allocTempImp.Alloc = SzAllocTemp; allocTempImp.Free = SzFreeTemp; #ifdef UNDER_CE if (InFile_OpenW(&archiveStream.file, L"\test.7z")) #else if (InFile_Open(&archiveStream.file, filename)) #endif { PrintError("can not open input file"); return -1; } FileInStream_CreateVTable(&archiveStream); LookToRead_CreateVTable(&lookStream, False); lookStream.realStream = &archiveStream.s; LookToRead_Init(&lookStream); CrcGenerateTable(); SzArEx_Init(&db); res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp); if (res == SZ_OK) { UInt32 i; /* if you need cache, use these 3 variables. if you use external function, you can make these variable as static. */ UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */ size_t outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ for (i = 0; i < db.NumFiles; i++) { size_t offset = 0; size_t outSizeProcessed = 0; // const CSzFileItem *f = db.Files + i; size_t len; unsigned isDir = SzArEx_IsDir(&db, i); len = SzArEx_GetFileNameUtf16(&db, i, NULL); // len = SzArEx_GetFullNameLen(&db, i); if (len > tempSize) { SzFree(NULL, temp); tempSize = len; temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0])); if (!temp) { res = SZ_ERROR_MEM; break; } } SzArEx_GetFileNameUtf16(&db, i, temp); /* { // progression output static char s[256]; snprintf(s, 255, _("Extracting (%d%%)"), ((i + 1) * 100) / db.NumFiles); HandleSemaphoreText(s, list, !i ? 1 : 0); }*/ if (isDir) ;//printf("/"); else { res = SzArEx_Extract(&db, &lookStream.s, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp); if (res != SZ_OK) break; } // write data to disk { CSzFile outFile; size_t processedSize; size_t j; UInt16 *name = (UInt16 *)temp; const UInt16 *destPath = (const UInt16 *)name; WRes wres; for (j = 0; name[j] != 0; j++) if (name[j] == '/') { name[j] = 0; MyCreateDir(name, &subdir, &do_save); name[j] = CHAR_PATH_SEPARATOR; } if (isDir) { MyCreateDir(destPath, &subdir, &do_save); //printf("\n"); continue; } if (do_save == False) continue; wres = OutFile_OpenUtf16(&outFile, destPath, &subdir, &do_save); if (wres == -1) continue; if (wres) { PrintError("can not open output file"); res = SZ_ERROR_FAIL; break; } processedSize = outSizeProcessed; if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed) { PrintError(_("can not write output file")); res = SZ_ERROR_FAIL; break; } if (File_Close(&outFile)) { PrintError(_("can not close output file")); res = SZ_ERROR_FAIL; break; } #ifdef USE_WINDOWS_FILE if (SzBitWithVals_Check(&db.Attribs, i)) SetFileAttributesW(destPath, db.Attribs.Vals[i]); #endif } //printf("\n"); } IAlloc_Free(&allocImp, outBuffer); } SzArEx_Free(&db, &allocImp); SzFree(NULL, temp); File_Close(&archiveStream.file); if (res == SZ_OK) { //printf("\nEverything is Ok\n"); return 0; } if (res == SZ_ERROR_UNSUPPORTED) PrintError(_("decoder doesn't support this archive")); else if (res == SZ_ERROR_MEM) PrintError(_("can not allocate memory")); else if (res == SZ_ERROR_CRC) PrintError(_("CRC error")); else printf("<br />ERROR #%d\n", res); return -1; }
BOOL My_AreFileApisANSI() { BOOL returnVal_Real = NULL; BOOL returnVal_Intercepted = NULL; DWORD error_Real = 0; DWORD error_Intercepted = 0; disableInterception(); returnVal_Real = AreFileApisANSI (); error_Real = GetLastError(); enableInterception(); returnVal_Intercepted = AreFileApisANSI (); error_Intercepted = GetLastError(); return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted)); }
U2EG_NAMESPACE_USING bool widePathToOgreString(String& dest, const WCHAR* wpath) { // need to convert to narrow (OEM or ANSI) codepage so that fstream can use it // properly on international systems. char npath[MAX_PATH]; #if U2_PLATFORM == U2_PLATFORM_WIN32 // Note, that on legacy CRT versions codepage for narrow CRT file functions can be changed using // SetFileApisANSI/OEM, but on modern runtimes narrow pathes are always widened using ANSI codepage. // We suppose that on such runtimes file APIs codepage is left in default, ANSI state. UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; #elif U2_PLATFORM == U2_PLATFORM_WINRT // Runtime is modern, narrow calls are widened inside CRT using CP_ACP codepage. UINT codepage = CP_ACP; #endif if (0 == WideCharToMultiByte(codepage, 0 /* Use default flags */, wpath, -1, npath, sizeof(npath), NULL, NULL)) { dest.clear(); return false; } // success dest = npath; return true; }
static inline UINT GetCurrentFileCodePage() { #ifdef UNDER_CE return CP_ACP; #else return AreFileApisANSI() ? CP_ACP : CP_OEMCP; #endif }
BOOL My_AreFileApisANSI() { BOOL returnVal_Real = NULL; BOOL returnVal_Intercepted = NULL; DWORD error_Real = 0; DWORD error_Intercepted = 0; __try{ disableInterception(); returnVal_Real = AreFileApisANSI (); error_Real = GetLastError(); enableInterception(); returnVal_Intercepted = AreFileApisANSI (); error_Intercepted = GetLastError(); }__except(puts("in filter"), 1){puts("exception caught");} return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted)); }
static BOOL cmpStrAW(const char* a, const WCHAR* b, DWORD lenA, DWORD lenB) { WCHAR aw[1024]; DWORD len = MultiByteToWideChar( AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, a, lenA, aw, sizeof(aw) / sizeof(aw[0]) ); if (len != lenB) return FALSE; return memcmp(aw, b, len * sizeof(WCHAR)) == 0; }
STDMETHODIMP CAVIFileRemote::Load(LPCOLESTR lpszFileName, DWORD grfMode) { char filename[MAX_PATH]; _RPT1(0,"%p->CAVIFileRemote::Load()\n", this); WideCharToMultiByte(AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, lpszFileName, -1, filename, sizeof filename, NULL, NULL); return Open(filename, grfMode, lpszFileName); }
int __cdecl rename( const char *oldname, const char *newname ) { /* We want to use MoveFileExW but not MoveFileExA (or MoveFile). So convert the strings to Unicode representation and call _wrename. Note that minwin does not support OEM CP for conversion via the FileAPIs APIs. So we unconditionally use the ACP for conversion */ int oldnamelen; int newnamelen; wchar_t *widenamesbuffer = NULL; wchar_t *oldnamew = NULL; wchar_t *newnamew = NULL; int retval; UINT codePage = CP_ACP; #if !(defined (_CORESYS) || defined (_CRT_APP) || defined (_KERNELX)) if (!__crtIsPackagedApp() && !AreFileApisANSI()) codePage = CP_OEMCP; #endif /* !(defined (_CORESYS) || defined (_CRT_APP) || defined (_KERNELX)) */ if ( ( (oldnamelen = MultiByteToWideChar(codePage, 0, oldname, -1, 0, 0) ) == 0 ) || ( (newnamelen = MultiByteToWideChar(codePage, 0, newname, -1, 0, 0) ) == 0 ) ) { _dosmaperr(GetLastError()); return -1; } /* allocate enough space for both */ if ( (widenamesbuffer = (wchar_t*)_malloc_crt( (oldnamelen+newnamelen) * sizeof(wchar_t) ) ) == NULL ) { /* errno is set by _malloc */ return -1; } /* now do the conversion */ oldnamew = widenamesbuffer; newnamew = widenamesbuffer + oldnamelen; if ( ( MultiByteToWideChar(codePage, 0, oldname, -1, oldnamew, oldnamelen) == 0 ) || ( MultiByteToWideChar(codePage, 0, newname, -1, newnamew, newnamelen) == 0 ) ) { _free_crt(widenamesbuffer); _dosmaperr(GetLastError()); return -1; } /* and event call the wide-character variant */ retval = _wrename(oldnamew,newnamew); _free_crt(widenamesbuffer); /* _free_crt leaves errno alone if everything completes as expected */ return retval; }
int Init_enc_set_filesystem_encoding(void) { int idx; #if defined NO_LOCALE_CHARMAP # error NO_LOCALE_CHARMAP defined #elif defined _WIN32 || defined __CYGWIN__ char cp[SIZEOF_CP_NAME]; CP_FORMAT(cp, AreFileApisANSI() ? GetACP() : GetOEMCP()); idx = rb_enc_find_index(cp); if (idx < 0) idx = ENCINDEX_ASCII; #else idx = rb_enc_to_index(rb_default_external_encoding()); #endif return idx; }
/* ** Convert an ansi string to microsoft unicode, based on the ** current codepage settings for file apis. ** ** Space to hold the returned string is obtained ** from sqliteMalloc. */ static WCHAR *mbcsToUnicode(const char *zFilename){ int nByte; WCHAR *zMbcsFilename; int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR); zMbcsFilename = sqliteMalloc( nByte*sizeof(zMbcsFilename[0]) ); if( zMbcsFilename==0 ){ return 0; } nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte); if( nByte==0 ){ sqliteFree(zMbcsFilename); zMbcsFilename = 0; } return zMbcsFilename; }
static int enc_set_filesystem_encoding(void) { int idx; #if defined NO_LOCALE_CHARMAP idx = rb_enc_to_index(rb_default_external_encoding()); #elif defined _WIN32 || defined __CYGWIN__ char cp[sizeof(int) * 8 / 3 + 4]; snprintf(cp, sizeof cp, "CP%d", AreFileApisANSI() ? GetACP() : GetOEMCP()); idx = rb_enc_find_index(cp); if (idx < 0) idx = rb_ascii8bit_encindex(); #else idx = rb_enc_to_index(rb_default_external_encoding()); #endif enc_alias_internal("filesystem", idx); return idx; }
char* Util::String::UnicodeToMbcs(const wchar_t* pUnicode) { int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; int nChar = WideCharToMultiByte(codepage, 0, pUnicode, -1, 0, 0, 0, 0); int nSize = nChar * sizeof(char) + 1; char* pchBuffer = new char[nSize]; nChar = WideCharToMultiByte(codepage, 0, pUnicode, -1, pchBuffer, nSize, 0, 0); if( nChar == 0 ) { delete[] pchBuffer; return NULL; } pchBuffer[nChar]= 0; return pchBuffer; }
/* ** Convert microsoft unicode to multibyte character string, based on the ** user's Ansi codepage. ** ** Space to hold the returned string is obtained from ** sqliteMalloc(). */ static char *unicodeToMbcs(const WCHAR *zWideFilename){ int nByte; char *zFilename; int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0); zFilename = sqliteMalloc( nByte ); if( zFilename==0 ){ return 0; } nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte, 0, 0); if( nByte == 0 ){ sqliteFree(zFilename); zFilename = 0; } return zFilename; }
std::codecvt_base::result windows_file_codecvt::do_out( std::mbstate_t &, const wchar_t* from, const wchar_t* from_end, const wchar_t* & from_next, char* to, char* to_end, char* & to_next) const { UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; int count; if ((count = ::WideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, from, from_end - from, to, to_end - to, 0, 0)) == 0) { return error; // conversion failed } from_next = from_end; to_next = to + count; *to_next = '\0'; return ok; }
std::codecvt_base::result windows_file_codecvt::do_in( std::mbstate_t &, const char* from, const char* from_end, const char*& from_next, wchar_t* to, wchar_t* to_end, wchar_t*& to_next) const { UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; int count; if ((count = ::MultiByteToWideChar(codepage, MB_PRECOMPOSED, from, from_end - from, to, to_end - to)) == 0) { return error; // conversion failed } from_next = from_end; to_next = to + count; *to_next = L'\0'; return ok; }
wchar_t* Util::String::MbcsToUnicode(const char* pMbcs) { int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; int nChar = MultiByteToWideChar(codepage, 0, pMbcs, -1, NULL,0); int nSize = nChar * sizeof(wchar_t) + 1; wchar_t* pwchBuffer = new wchar_t[nSize]; nChar = MultiByteToWideChar(codepage, 0, pMbcs, -1, pwchBuffer, nSize); if(nChar == 0) { delete[] pwchBuffer; return NULL; } pwchBuffer[nChar]=0; return pwchBuffer; }
int __cdecl main(int argc, char *argv[]) { BOOL bRc = FALSE; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } bRc = AreFileApisANSI(); if (bRc == FALSE) { Fail("AreFileApisANSI: ERROR: Function returned FALSE whereas only TRUE " "is acceptable.\n"); } PAL_Terminate(); return PASS; }
// // Process Auto Config options: // #1 search for '/noconfig' // if not present and csc.cfg exists in EXE dir, inject after env var stuff // void ConsoleArgs::ProcessAutoConfig() { bool fFoundNoConfig = false; // Scan the argument list for the "/noconfig" options. If present, just kill it and bail. for (WStrList * listArgCur = m_listArgs; listArgCur; listArgCur = listArgCur->next) { // Skip everything except options WCHAR * szArg = listArgCur->arg; if (szArg == NULL || (szArg[0] != '/' && szArg[0] != '-')) continue; if (_wcsicmp(szArg + 1, L"noconfig") == 0) { listArgCur->arg = NULL; VSFree(szArg); // We found it, empty it but keep checking in case they specified it twice fFoundNoConfig = true; } } if (fFoundNoConfig) return; // If we got here it means there was no '/noconfig' WCHAR szPath[MAX_PATH]; if (W_IsUnicodeSystem()) { if(!GetModuleFileNameW(NULL, szPath, lengthof(szPath))) szPath[0] = 0; } else { CHAR szTemp[MAX_PATH]; if (!GetModuleFileNameA(NULL, szTemp, lengthof(szTemp)) || !MultiByteToWideChar( AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, szTemp, -1, szPath, lengthof(szPath))) szPath[0] = 0; } if (*szPath && PathRemoveFileSpecW(szPath) && PathAppendW(szPath, L"csc.rsp")) { if (W_Access( szPath, 4) == 0) { // We know the file exists and that we have read access // so add into the list size_t cchLen = wcslen(szPath) + 2; // +2 for @ and terminator WCHAR * szPathCopy = (WCHAR*)VSAlloc( sizeof(WCHAR) * cchLen); if (!szPathCopy || FAILED(StringCchCopyW(szPathCopy + 1, cchLen, szPath))) { VSFAIL("The string changed size, or our pointers got messed up"); m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL); return; } szPathCopy[0] = L'@'; WStrList * listArgNew = new WStrList( szPathCopy, m_listArgs); if (!listArgNew) { VSFree(szPathCopy); m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL); return; } m_listArgs = listArgNew; } } }
HRESULT CreateLink(LPCSTR lpszPathObj, LPSTR lpszPathLink, LPSTR lpszDesc) { HRESULT hres; IShellLink* psl; IPersistFile* ppf; WORD wsz[MAX_PATH]; char *ObjWorkingDir; char *tmp; #ifdef TEST fprintf(stderr, "CreateLink\n"); fprintf(stderr, " lpszPathObj: %s\n", lpszPathObj); fprintf(stderr, " lpszPathLink: %s\n", lpszPathLink); fprintf(stderr, " lpszDesc: %s\n", lpszDesc); #endif hres = OleInitialize (NULL); if (hres != S_FALSE && hres != S_OK) { set_werrno; // fprintf (stderr, "%s: Could not initialize OLE interface\n", prog_name); CoUninitialize(); return (-1); } // Get a pointer to the IShellLink interface. hres = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink,(LPVOID *) &psl); if (!SUCCEEDED(hres)) { set_werrno; // fprintf (stderr, "%s: CoCreateInstance failed\n", prog_name); CoUninitialize(); return (-1); } // Set the path to the shortcut target, and add the // description. psl->lpVtbl->SetPath(psl, lpszPathObj); psl->lpVtbl->SetDescription(psl, lpszDesc); ObjWorkingDir = strdup(lpszPathObj); #ifdef TEST fprintf(stderr, " ObjWDir: %s\n", ObjWorkingDir); #endif if (ObjWorkingDir) { tmp = strrchr(ObjWorkingDir, '\\'); tmp[0] = '\0'; #ifdef TEST fprintf(stderr, " ObjWDir: %s\n", ObjWorkingDir); #endif psl->lpVtbl->SetWorkingDirectory (psl, ObjWorkingDir); } // Query IShellLink for the IPersistFile interface for saving the // shortcut in persistent storage. hres = psl->lpVtbl->QueryInterface(psl, &IID_IPersistFile, (void **) &ppf); if (!SUCCEEDED(hres)) { set_werrno; // fprintf (stderr, "%s: QueryInterface failed\n", prog_name); CoUninitialize(); return (-1); } // Ensure that the string is ANSI. hres = MultiByteToWideChar( AreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, lpszPathLink, -1, wsz, MAX_PATH); if (!SUCCEEDED (hres)) { set_werrno; // fprintf (stderr, "%s: Unicode translation failed%ld\n", prog_name, hres); CoUninitialize(); return (-1); } // Save the link by calling IPersistFile::Save. hres = ppf->lpVtbl->Save(ppf, wsz, TRUE); ppf->lpVtbl->Release(ppf); psl->lpVtbl->Release(psl); CoUninitialize(); return hres; }
static inline UINT filecp(void) { UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP; return cp; }
static inline UINT GetCurrentFileCodePage() { return AreFileApisANSI() ? CP_ACP : CP_OEMCP; }
int MY_CDECL main(int numargs, char *args[]) { ISzAlloc allocImp; ISzAlloc allocTempImp; CFileInStream archiveStream; CLookToRead2 lookStream; CSzArEx db; SRes res; UInt16 *temp = NULL; size_t tempSize = 0; // UInt32 parents[NUM_PARENTS_MAX]; Print("\n7z Decoder " MY_VERSION_CPU " : " MY_COPYRIGHT_DATE "\n\n"); if (numargs == 1) { Print( "Usage: 7zDec <command> <archive_name>\n\n" "<Commands>\n" " e: Extract files from archive (without using directory names)\n" " l: List contents of archive\n" " t: Test integrity of archive\n" " x: eXtract files with full paths\n"); return 0; } if (numargs < 3) { PrintError("incorrect command"); return 1; } #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE) g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; #endif allocImp = g_Alloc; allocTempImp = g_Alloc; #ifdef UNDER_CE if (InFile_OpenW(&archiveStream.file, L"\test.7z")) #else if (InFile_Open(&archiveStream.file, args[2])) #endif { PrintError("can not open input file"); return 1; } FileInStream_CreateVTable(&archiveStream); LookToRead2_CreateVTable(&lookStream, False); lookStream.buf = NULL; res = SZ_OK; { lookStream.buf = (Byte *)ISzAlloc_Alloc(&allocImp, kInputBufSize); if (!lookStream.buf) res = SZ_ERROR_MEM; else { lookStream.bufSize = kInputBufSize; lookStream.realStream = &archiveStream.vt; LookToRead2_Init(&lookStream); } } CrcGenerateTable(); SzArEx_Init(&db); if (res == SZ_OK) { res = SzArEx_Open(&db, &lookStream.vt, &allocImp, &allocTempImp); } if (res == SZ_OK) { char *command = args[1]; int listCommand = 0, testCommand = 0, fullPaths = 0; if (strcmp(command, "l") == 0) listCommand = 1; else if (strcmp(command, "t") == 0) testCommand = 1; else if (strcmp(command, "e") == 0) { } else if (strcmp(command, "x") == 0) { fullPaths = 1; } else { PrintError("incorrect command"); res = SZ_ERROR_FAIL; } if (res == SZ_OK) { UInt32 i; /* if you need cache, use these 3 variables. if you use external function, you can make these variable as static. */ UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */ size_t outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ for (i = 0; i < db.NumFiles; i++) { size_t offset = 0; size_t outSizeProcessed = 0; // const CSzFileItem *f = db.Files + i; size_t len; unsigned isDir = SzArEx_IsDir(&db, i); if (listCommand == 0 && isDir && !fullPaths) continue; len = SzArEx_GetFileNameUtf16(&db, i, NULL); // len = SzArEx_GetFullNameLen(&db, i); if (len > tempSize) { SzFree(NULL, temp); tempSize = len; temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0])); if (!temp) { res = SZ_ERROR_MEM; break; } } SzArEx_GetFileNameUtf16(&db, i, temp); /* if (SzArEx_GetFullNameUtf16_Back(&db, i, temp + len) != temp) { res = SZ_ERROR_FAIL; break; } */ if (listCommand) { char attr[8], s[32], t[32]; UInt64 fileSize; GetAttribString(SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0, isDir, attr); fileSize = SzArEx_GetFileSize(&db, i); UInt64ToStr(fileSize, s, 10); if (SzBitWithVals_Check(&db.MTime, i)) ConvertFileTimeToString(&db.MTime.Vals[i], t); else { size_t j; for (j = 0; j < 19; j++) t[j] = ' '; t[j] = '\0'; } Print(t); Print(" "); Print(attr); Print(" "); Print(s); Print(" "); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) Print("/"); PrintLF(); continue; } Print(testCommand ? "Testing ": "Extracting "); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) Print("/"); else { res = SzArEx_Extract(&db, &lookStream.vt, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp); if (res != SZ_OK) break; } if (!testCommand) { CSzFile outFile; size_t processedSize; size_t j; UInt16 *name = (UInt16 *)temp; const UInt16 *destPath = (const UInt16 *)name; for (j = 0; name[j] != 0; j++) if (name[j] == '/') { if (fullPaths) { name[j] = 0; MyCreateDir(name); name[j] = CHAR_PATH_SEPARATOR; } else destPath = name + j + 1; } if (isDir) { MyCreateDir(destPath); PrintLF(); continue; } else if (OutFile_OpenUtf16(&outFile, destPath)) { PrintError("can not open output file"); res = SZ_ERROR_FAIL; break; } processedSize = outSizeProcessed; if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed) { PrintError("can not write output file"); res = SZ_ERROR_FAIL; break; } #ifdef USE_WINDOWS_FILE { FILETIME mtime, ctime; FILETIME *mtimePtr = NULL; FILETIME *ctimePtr = NULL; if (SzBitWithVals_Check(&db.MTime, i)) { const CNtfsFileTime *t = &db.MTime.Vals[i]; mtime.dwLowDateTime = (DWORD)(t->Low); mtime.dwHighDateTime = (DWORD)(t->High); mtimePtr = &mtime; } if (SzBitWithVals_Check(&db.CTime, i)) { const CNtfsFileTime *t = &db.CTime.Vals[i]; ctime.dwLowDateTime = (DWORD)(t->Low); ctime.dwHighDateTime = (DWORD)(t->High); ctimePtr = &ctime; } if (mtimePtr || ctimePtr) SetFileTime(outFile.handle, ctimePtr, NULL, mtimePtr); } #endif if (File_Close(&outFile)) { PrintError("can not close output file"); res = SZ_ERROR_FAIL; break; } #ifdef USE_WINDOWS_FILE if (SzBitWithVals_Check(&db.Attribs, i)) { UInt32 attrib = db.Attribs.Vals[i]; /* p7zip stores posix attributes in high 16 bits and adds 0x8000 as marker. We remove posix bits, if we detect posix mode field */ if ((attrib & 0xF0000000) != 0) attrib &= 0x7FFF; SetFileAttributesW((LPCWSTR)destPath, attrib); } #endif } PrintLF(); } ISzAlloc_Free(&allocImp, outBuffer); } } SzFree(NULL, temp); SzArEx_Free(&db, &allocImp); ISzAlloc_Free(&allocImp, lookStream.buf); File_Close(&archiveStream.file); if (res == SZ_OK) { Print("\nEverything is Ok\n"); return 0; } if (res == SZ_ERROR_UNSUPPORTED) PrintError("decoder doesn't support this archive"); else if (res == SZ_ERROR_MEM) PrintError("can not allocate memory"); else if (res == SZ_ERROR_CRC) PrintError("CRC error"); else { char s[32]; UInt64ToStr(res, s, 0); PrintError(s); } return 1; }
/* Return system code page. */ static inline UINT system_code_page() { return AreFileApisANSI() ? CP_ACP : CP_OEMCP; }
HANDLE PASCAL RAROpenArchiveEx(struct RAROpenArchiveDataEx *r) { DataSet *Data=NULL; try { r->OpenResult=0; Data=new DataSet; Data->Cmd.DllError=0; Data->OpenMode=r->OpenMode; Data->Cmd.FileArgs.AddString(L"*"); char AnsiArcName[NM]; *AnsiArcName=0; if (r->ArcName!=NULL) { strncpyz(AnsiArcName,r->ArcName,ASIZE(AnsiArcName)); #ifdef _WIN_ALL if (!AreFileApisANSI()) { OemToCharBuffA(r->ArcName,AnsiArcName,ASIZE(AnsiArcName)); AnsiArcName[ASIZE(AnsiArcName)-1]=0; } #endif } wchar ArcName[NM]; GetWideName(AnsiArcName,r->ArcNameW,ArcName,ASIZE(ArcName)); Data->Cmd.AddArcName(ArcName); Data->Cmd.Overwrite=OVERWRITE_ALL; Data->Cmd.VersionControl=1; Data->Cmd.Callback=r->Callback; Data->Cmd.UserData=r->UserData; // Open shared mode is added by request of dll users, who need to // browse and unpack archives while downloading. Data->Cmd.OpenShared = true; if (!Data->Arc.Open(ArcName,FMF_OPENSHARED)) { r->OpenResult=ERAR_EOPEN; delete Data; return NULL; } if (!Data->Arc.IsArchive(false)) { if (Data->Cmd.DllError!=0) r->OpenResult=Data->Cmd.DllError; else { RAR_EXIT ErrCode=ErrHandler.GetErrorCode(); if (ErrCode!=RARX_SUCCESS && ErrCode!=RARX_WARNING) r->OpenResult=RarErrorToDll(ErrCode); else r->OpenResult=ERAR_BAD_ARCHIVE; } delete Data; return NULL; } r->Flags=0; if (Data->Arc.Volume) r->Flags|=0x01; if (Data->Arc.Locked) r->Flags|=0x04; if (Data->Arc.Solid) r->Flags|=0x08; if (Data->Arc.NewNumbering) r->Flags|=0x10; if (Data->Arc.Signed) r->Flags|=0x20; if (Data->Arc.Protected) r->Flags|=0x40; if (Data->Arc.Encrypted) r->Flags|=0x80; if (Data->Arc.FirstVolume) r->Flags|=0x100; Array<wchar> CmtDataW; if (r->CmtBufSize!=0 && Data->Arc.GetComment(&CmtDataW)) { Array<char> CmtData(CmtDataW.Size()*4+1); memset(&CmtData[0],0,CmtData.Size()); WideToChar(&CmtDataW[0],&CmtData[0],CmtData.Size()-1); size_t Size=strlen(&CmtData[0])+1; r->Flags|=2; r->CmtState=Size>r->CmtBufSize ? ERAR_SMALL_BUF:1; r->CmtSize=(uint)Min(Size,r->CmtBufSize); memcpy(r->CmtBuf,&CmtData[0],r->CmtSize-1); if (Size<=r->CmtBufSize) r->CmtBuf[r->CmtSize-1]=0; } else r->CmtState=r->CmtSize=0; Data->Extract.ExtractArchiveInit(Data->Arc); return (HANDLE)Data; } catch (RAR_EXIT ErrCode) { if (Data!=NULL && Data->Cmd.DllError!=0) r->OpenResult=Data->Cmd.DllError; else r->OpenResult=RarErrorToDll(ErrCode); if (Data != NULL) delete Data; return NULL; } catch (std::bad_alloc&) // Catch 'new' exception. { r->OpenResult=ERAR_NO_MEMORY; if (Data != NULL) delete Data; } return NULL; // To make compilers happy. }
int MY_CDECL main(int numargs, char *args[]) { CFileInStream archiveStream; CLookToRead lookStream; CSzArEx db; SRes res; ISzAlloc allocImp; ISzAlloc allocTempImp; UInt16 *temp = NULL; size_t tempSize = 0; // UInt32 parents[NUM_PARENTS_MAX]; printf("\n7z ANSI-C Decoder " MY_VERSION_COPYRIGHT_DATE "\n\n"); if (numargs == 1) { printf( "Usage: 7zDec <command> <archive_name>\n\n" "<Commands>\n" " e: Extract files from archive (without using directory names)\n" " l: List contents of archive\n" " t: Test integrity of archive\n" " x: eXtract files with full paths\n"); return 0; } if (numargs < 3) { PrintError("incorrect command"); return 1; } #if defined(_WIN32) && !defined(USE_WINDOWS_FILE) && !defined(UNDER_CE) g_FileCodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; #endif allocImp.Alloc = SzAlloc; allocImp.Free = SzFree; allocTempImp.Alloc = SzAllocTemp; allocTempImp.Free = SzFreeTemp; #ifdef UNDER_CE if (InFile_OpenW(&archiveStream.file, L"\test.7z")) #else if (InFile_Open(&archiveStream.file, args[2])) #endif { PrintError("can not open input file"); return 1; } FileInStream_CreateVTable(&archiveStream); LookToRead_CreateVTable(&lookStream, False); lookStream.realStream = &archiveStream.s; LookToRead_Init(&lookStream); CrcGenerateTable(); SzArEx_Init(&db); res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp); if (res == SZ_OK) { char *command = args[1]; int listCommand = 0, testCommand = 0, fullPaths = 0; if (strcmp(command, "l") == 0) listCommand = 1; else if (strcmp(command, "t") == 0) testCommand = 1; else if (strcmp(command, "e") == 0) { } else if (strcmp(command, "x") == 0) { fullPaths = 1; } else { PrintError("incorrect command"); res = SZ_ERROR_FAIL; } if (res == SZ_OK) { UInt32 i; /* if you need cache, use these 3 variables. if you use external function, you can make these variable as static. */ UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */ size_t outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ for (i = 0; i < db.NumFiles; i++) { size_t offset = 0; size_t outSizeProcessed = 0; // const CSzFileItem *f = db.Files + i; size_t len; unsigned isDir = SzArEx_IsDir(&db, i); if (listCommand == 0 && isDir && !fullPaths) continue; len = SzArEx_GetFileNameUtf16(&db, i, NULL); // len = SzArEx_GetFullNameLen(&db, i); if (len > tempSize) { SzFree(NULL, temp); tempSize = len; temp = (UInt16 *)SzAlloc(NULL, tempSize * sizeof(temp[0])); if (!temp) { res = SZ_ERROR_MEM; break; } } SzArEx_GetFileNameUtf16(&db, i, temp); /* if (SzArEx_GetFullNameUtf16_Back(&db, i, temp + len) != temp) { res = SZ_ERROR_FAIL; break; } */ if (listCommand) { char attr[8], s[32], t[32]; UInt64 fileSize; GetAttribString(SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0, isDir, attr); fileSize = SzArEx_GetFileSize(&db, i); UInt64ToStr(fileSize, s); if (SzBitWithVals_Check(&db.MTime, i)) ConvertFileTimeToString(&db.MTime.Vals[i], t); else { size_t j; for (j = 0; j < 19; j++) t[j] = ' '; t[j] = '\0'; } printf("%s %s %10s ", t, attr, s); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) printf("/"); printf("\n"); continue; } fputs(testCommand ? "Testing ": "Extracting ", stdout); res = PrintString(temp); if (res != SZ_OK) break; if (isDir) printf("/"); else { res = SzArEx_Extract(&db, &lookStream.s, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp); if (res != SZ_OK) break; } if (!testCommand) { CSzFile outFile; size_t processedSize; size_t j; UInt16 *name = (UInt16 *)temp; const UInt16 *destPath = (const UInt16 *)name; for (j = 0; name[j] != 0; j++) if (name[j] == '/') { if (fullPaths) { name[j] = 0; MyCreateDir(name); name[j] = CHAR_PATH_SEPARATOR; } else destPath = name + j + 1; } if (isDir) { MyCreateDir(destPath); printf("\n"); continue; } else if (OutFile_OpenUtf16(&outFile, destPath)) { PrintError("can not open output file"); res = SZ_ERROR_FAIL; break; } processedSize = outSizeProcessed; if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed) { PrintError("can not write output file"); res = SZ_ERROR_FAIL; break; } if (File_Close(&outFile)) { PrintError("can not close output file"); res = SZ_ERROR_FAIL; break; } #ifdef USE_WINDOWS_FILE if (SzBitWithVals_Check(&db.Attribs, i)) SetFileAttributesW(destPath, db.Attribs.Vals[i]); #endif } printf("\n"); } IAlloc_Free(&allocImp, outBuffer); } } SzArEx_Free(&db, &allocImp); SzFree(NULL, temp); File_Close(&archiveStream.file); if (res == SZ_OK) { printf("\nEverything is Ok\n"); return 0; } if (res == SZ_ERROR_UNSUPPORTED) PrintError("decoder doesn't support this archive"); else if (res == SZ_ERROR_MEM) PrintError("can not allocate memory"); else if (res == SZ_ERROR_CRC) PrintError("CRC error"); else printf("\nERROR #%d\n", res); return 1; }
// TODO: can we fail allocating memory? static VALUE fenix_file_expand_path_plain(int argc, VALUE *argv) { size_t size = 0, wpath_len = 0, wdir_len = 0, whome_len = 0; size_t buffer_len = 0; char *fullpath = NULL; wchar_t *wfullpath = NULL, *wpath = NULL, *wpath_pos = NULL, *wdir = NULL; wchar_t *whome = NULL, *buffer = NULL, *buffer_pos = NULL; UINT cp; VALUE result = Qnil, path = Qnil, dir = Qnil; // retrieve path and dir from argv rb_scan_args(argc, argv, "11", &path, &dir); // coerce them to string path = fenix_coerce_to_path(path); if (!NIL_P(dir)) dir = fenix_coerce_to_path(dir); // convert char * to wchar_t // path if (!NIL_P(path)) { size = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(path), -1, NULL, 0) + 1; wpath = wpath_pos = (wchar_t *)malloc(size * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(path), -1, wpath, size); wpath_len = wcslen(wpath); // wprintf(L"wpath: '%s' with (%i) characters long.\n", wpath, wpath_len); } // dir if (!NIL_P(dir)) { size = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(dir), -1, NULL, 0) + 1; wdir = (wchar_t *)malloc(size * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(dir), -1, wdir, size); wdir_len = wcslen(wdir); // wprintf(L"wdir: '%s' with (%i) characters long.\n", wdir, wdir_len); } /* determine if we need the user's home directory */ if ((wpath_len == 1 && wpath_pos[0] == L'~') || (wpath_len >= 2 && wpath_pos[0] == L'~' && IS_DIR_SEPARATOR_P(wpath_pos[1]))) { // wprintf(L"wpath requires expansion.\n"); whome = fenix_home_dir(); whome_len = wcslen(whome); // wprintf(L"whome: '%s' with (%i) characters long.\n", whome, whome_len); /* ignores dir since we are expading home */ wdir_len = 0; /* exclude ~ from the result */ wpath_pos++; wpath_len--; /* exclude separator if present */ if (wpath_len && IS_DIR_SEPARATOR_P(wpath_pos[0])) { // wprintf(L"excluding expansion character and separator\n"); wpath_pos++; wpath_len--; } } else if (wpath_len >= 2 && wpath_pos[1] == L':') { /* ignore dir since path contains a drive letter */ // wprintf(L"Ignore dir since we have drive letter\n"); wdir_len = 0; } // wprintf(L"wpath_len: %i\n", wpath_len); // wprintf(L"wdir_len: %i\n", wdir_len); // wprintf(L"whome_len: %i\n", whome_len); buffer_len = wpath_len + 1 + wdir_len + 1 + whome_len + 1; // wprintf(L"buffer_len: %i\n", buffer_len + 1); buffer = buffer_pos = (wchar_t *)malloc((buffer_len + 1) * sizeof(wchar_t)); /* add home */ if (whome_len) { // wprintf(L"Copying whome...\n"); wcsncpy(buffer_pos, whome, whome_len); buffer_pos += whome_len; } /* Add separator if required */ if (whome_len && wcsrchr(L"\\/:", buffer_pos[-1]) == NULL) { // wprintf(L"Adding separator after whome\n"); buffer_pos[0] = L'\\'; buffer_pos++; } if (wdir_len) { // wprintf(L"Copying wdir...\n"); wcsncpy(buffer_pos, wdir, wdir_len); buffer_pos += wdir_len; } /* add separator if required */ if (wdir_len && wcsrchr(L"\\/:", buffer_pos[-1]) == NULL) { // wprintf(L"Adding separator after wdir\n"); buffer_pos[0] = L'\\'; buffer_pos++; } /* now deal with path */ if (wpath_len) { // wprintf(L"Copying wpath...\n"); wcsncpy(buffer_pos, wpath_pos, wpath_len); buffer_pos += wpath_len; } /* GetFullPathNameW requires at least "." to determine current directory */ if (wpath_len == 0) { // wprintf(L"Adding '.' to buffer\n"); buffer_pos[0] = L'.'; buffer_pos++; } /* Ensure buffer is NULL terminated */ buffer_pos[0] = L'\0'; // wprintf(L"buffer: '%s'\n", buffer); // FIXME: Make this more robust // Determine require buffer size size = GetFullPathNameW(buffer, 0, NULL, NULL); if (size) { // allocate enough memory to contain the response wfullpath = (wchar_t *)malloc(size * sizeof(wchar_t)); GetFullPathNameW(buffer, size, wfullpath, NULL); /* Calculate the new size and leave the garbage out */ size = wcslen(wfullpath); /* Remove any trailing slashes */ if (IS_DIR_SEPARATOR_P(wfullpath[size - 1]) && wfullpath[size - 2] != L':') { // wprintf(L"Removing trailing slash\n"); wfullpath[size - 1] = L'\0'; } // sanitize backslashes with forwardslashes fenix_replace_wchar(wfullpath, L'\\', L'/'); // wprintf(L"wfullpath: '%s'\n", wfullpath); // What CodePage should we use? cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP; // convert to char * size = WideCharToMultiByte(cp, 0, wfullpath, -1, NULL, 0, NULL, NULL) + 1; fullpath = (char *)malloc(size * sizeof(char)); WideCharToMultiByte(cp, 0, wfullpath, -1, fullpath, size, NULL, NULL); // convert to VALUE and set the filesystem encoding result = rb_filesystem_str_new_cstr(fullpath); } // TODO: better cleanup if (buffer) free(buffer); if (wpath) free(wpath); if (wdir) free(wdir); if (whome) free(whome); if (wfullpath) free(wfullpath); if (fullpath) free(fullpath); return result; }
void showhelppp(const char *anchor = 0) //Alone Coder 0.36.6 { if (!hMSHTML) hMSHTML = LoadLibrary("MSHTML.DLL"); if (!hURLMON) hURLMON = LoadLibrary("URLMON.DLL"); tShowHTMLDialog Show = hMSHTML? (tShowHTMLDialog)GetProcAddress(hMSHTML, "ShowHTMLDialog") : 0; tCreateURLMoniker CreateMoniker = hURLMON? (tCreateURLMoniker)GetProcAddress(hURLMON, "CreateURLMoniker") : 0; HWND fgwin = GetForegroundWindow(); if (!Show || !CreateMoniker) { MessageBox(fgwin, "Install IE4.0 or higher to view help", 0, MB_ICONERROR); return; } char dst[0x200]; GetTempPath(sizeof dst, dst); strcat(dst, "us_help.htm"); FILE *ff = fopen(helpname, "rb"), *gg = fopen(dst, "wb"); if (!ff || !gg) return; for (;;) { int x = getc(ff); if (x == EOF) break; if (x == '{') { char tag[0x100]; int r = 0; while (r < sizeof(tag)-1 && !feof(ff) && (x = getc(ff)) != '}') tag[r++] = x; tag[r] = 0; if (tag[0] == '?') { RECT rc; GetWindowRect(fgwin, &rc); if (tag[1] == 'x') fprintf(gg, "%d", rc.right-rc.left-20); if (tag[1] == 'y') fprintf(gg, "%d", rc.bottom-rc.top-20); } else { char res[0x100]; GetPrivateProfileString("SYSTEM.KEYS", tag, "not defined", res, sizeof res, ininame); char *comment = strchr(res, ';'); if (comment) *comment = 0; int len; //Alone Coder 0.36.7 for (/*int*/ len = strlen(res); len && res[len-1] == ' '; res[--len] = 0); for (len = 0; res[len]; len++) if (res[len] == ' ') res[len] = '-'; fprintf(gg, "%s", res); } } else putc(x, gg); } fclose(ff), fclose(gg); char url[0x200]; sprintf(url, "file://%s%s%s", dst, anchor?"#":nil, anchor?anchor:nil); WCHAR urlw[0x200]; MultiByteToWideChar(AreFileApisANSI()? CP_ACP : CP_OEMCP, MB_USEGLYPHCHARS, url, -1, urlw, _countof(urlw)); IMoniker *pmk = 0; CreateMoniker(0, urlw, &pmk); if (pmk) { bool restore_video = false; if (!(temp.rflags & (RF_GDI | RF_CLIP | RF_OVR | RF_16 | RF_32))) { temp.rflags = temp.rflags | RF_GDI; set_video(); restore_video = true; } Show(fgwin, pmk, 0,0,0); pmk->Release(); #if 0 if (dbgbreak) { temp.rflags = RF_MONITOR; set_video(); } else #endif { if (restore_video) apply_video(); } } DeleteFile(dst); }