1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
|
#include "rar.hpp"
MKDIR_CODE MakeDir(const std::wstring &Name,bool SetAttr,uint Attr)
{
#ifdef _WIN_ALL
// Windows automatically removes dots and spaces in the end of directory
// name. So we detect such names and process them with \\?\ prefix.
wchar LastChar=GetLastChar(Name);
bool Special=LastChar=='.' || LastChar==' ';
BOOL RetCode=Special ? FALSE : CreateDirectory(Name.c_str(),NULL);
if (RetCode==0 && !FileExist(Name))
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
RetCode=CreateDirectory(LongName.c_str(),NULL);
}
if (RetCode!=0) // Non-zero return code means success for CreateDirectory.
{
if (SetAttr)
SetFileAttr(Name,Attr);
return MKDIR_SUCCESS;
}
int ErrCode=GetLastError();
if (ErrCode==ERROR_FILE_NOT_FOUND || ErrCode==ERROR_PATH_NOT_FOUND)
return MKDIR_BADPATH;
return MKDIR_ERROR;
#elif defined(_UNIX)
std::string NameA;
WideToChar(Name,NameA);
mode_t uattr=SetAttr ? (mode_t)Attr:0777;
int ErrCode=mkdir(NameA.c_str(),uattr);
if (ErrCode==-1)
return errno==ENOENT ? MKDIR_BADPATH:MKDIR_ERROR;
return MKDIR_SUCCESS;
#else
return MKDIR_ERROR;
#endif
}
// Simplified version of MakeDir().
bool CreateDir(const std::wstring &Name)
{
return MakeDir(Name,false,0)==MKDIR_SUCCESS;
}
bool CreatePath(const std::wstring &Path,bool SkipLastName,bool Silent)
{
if (Path.empty())
return false;
#ifdef _WIN_ALL
uint DirAttr=0;
#else
uint DirAttr=0777;
#endif
bool Success=true;
for (size_t I=0;I<Path.size();I++)
{
// Process all kinds of path separators, so user can enter Unix style
// path in Windows or Windows in Unix. I>0 check avoids attempting
// creating an empty directory for paths starting from path separator.
if (IsPathDiv(Path[I]) && I>0)
{
#ifdef _WIN_ALL
// We must not attempt to create "D:" directory, because first
// CreateDirectory will fail, so we'll use \\?\D:, which forces Wine
// to create "D:" directory.
if (I==2 && Path[1]==':')
continue;
#endif
std::wstring DirName=Path.substr(0,I);
Success=MakeDir(DirName,true,DirAttr)==MKDIR_SUCCESS;
if (Success && !Silent)
{
mprintf(St(MCreatDir),DirName.c_str());
mprintf(L" %s",St(MOk));
}
}
}
if (!SkipLastName && !IsPathDiv(GetLastChar(Path)))
Success=MakeDir(Path,true,DirAttr)==MKDIR_SUCCESS;
return Success;
}
void SetDirTime(const std::wstring &Name,RarTime *ftm,RarTime *ftc,RarTime *fta)
{
#if defined(_WIN_ALL)
bool sm=ftm!=NULL && ftm->IsSet();
bool sc=ftc!=NULL && ftc->IsSet();
bool sa=fta!=NULL && fta->IsSet();
uint DirAttr=GetFileAttr(Name);
bool ResetAttr=(DirAttr!=0xffffffff && (DirAttr & FILE_ATTRIBUTE_READONLY)!=0);
if (ResetAttr)
SetFileAttr(Name,0);
HANDLE hFile=CreateFile(Name.c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
if (hFile==INVALID_HANDLE_VALUE)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
hFile=CreateFile(LongName.c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS,NULL);
}
if (hFile==INVALID_HANDLE_VALUE)
return;
FILETIME fm,fc,fa;
if (sm)
ftm->GetWinFT(&fm);
if (sc)
ftc->GetWinFT(&fc);
if (sa)
fta->GetWinFT(&fa);
SetFileTime(hFile,sc ? &fc:NULL,sa ? &fa:NULL,sm ? &fm:NULL);
CloseHandle(hFile);
if (ResetAttr)
SetFileAttr(Name,DirAttr);
#endif
#ifdef _UNIX
File::SetCloseFileTimeByName(Name,ftm,fta);
#endif
}
bool IsRemovable(const std::wstring &Name)
{
#if defined(_WIN_ALL)
std::wstring Root;
GetPathRoot(Name,Root);
int Type=GetDriveType(Root.empty() ? nullptr : Root.c_str());
return Type==DRIVE_REMOVABLE || Type==DRIVE_CDROM;
#else
return false;
#endif
}
#ifndef SFX_MODULE
int64 GetFreeDisk(const std::wstring &Name)
{
#ifdef _WIN_ALL
std::wstring Root;
GetPathWithSep(Name,Root);
ULARGE_INTEGER uiTotalSize,uiTotalFree,uiUserFree;
uiUserFree.u.LowPart=uiUserFree.u.HighPart=0;
if (GetDiskFreeSpaceEx(Root.empty() ? NULL:Root.c_str(),&uiUserFree,&uiTotalSize,&uiTotalFree) &&
uiUserFree.u.HighPart<=uiTotalFree.u.HighPart)
return INT32TO64(uiUserFree.u.HighPart,uiUserFree.u.LowPart);
return 0;
#elif defined(_UNIX)
std::wstring Root;
GetPathWithSep(Name,Root);
std::string RootA;
WideToChar(Root,RootA);
struct statvfs sfs;
if (statvfs(RootA.empty() ? ".":RootA.c_str(),&sfs)!=0)
return 0;
int64 FreeSize=sfs.f_bsize;
FreeSize=FreeSize*sfs.f_bavail;
return FreeSize;
#else
return 0;
#endif
}
#endif
#if defined(_WIN_ALL) && !defined(SFX_MODULE) && !defined(SILENT)
// Return 'true' for FAT and FAT32, so we can adjust the maximum supported
// file size to 4 GB for these file systems.
bool IsFAT(const std::wstring &Name)
{
std::wstring Root;
GetPathRoot(Name,Root);
wchar FileSystem[MAX_PATH+1];
// Root can be empty, when we create volumes with -v in the current folder.
if (GetVolumeInformation(Root.empty() ? NULL:Root.c_str(),NULL,0,NULL,NULL,NULL,FileSystem,ASIZE(FileSystem)))
return wcscmp(FileSystem,L"FAT")==0 || wcscmp(FileSystem,L"FAT32")==0;
return false;
}
#endif
bool FileExist(const std::wstring &Name)
{
#ifdef _WIN_ALL
return GetFileAttr(Name)!=0xffffffff;
#elif defined(ENABLE_ACCESS)
std::string NameA;
WideToChar(Name,NameA);
return access(NameA.c_str(),0)==0;
#else
FindData FD;
return FindFile::FastFind(Name,&FD);
#endif
}
bool WildFileExist(const std::wstring &Name)
{
if (IsWildcard(Name))
{
FindFile Find;
Find.SetMask(Name);
FindData fd;
return Find.Next(&fd);
}
return FileExist(Name);
}
bool IsDir(uint Attr)
{
#ifdef _WIN_ALL
return Attr!=0xffffffff && (Attr & FILE_ATTRIBUTE_DIRECTORY)!=0;
#endif
#if defined(_UNIX)
return (Attr & 0xF000)==0x4000;
#endif
}
bool IsUnreadable(uint Attr)
{
#if defined(_UNIX) && defined(S_ISFIFO) && defined(S_ISSOCK) && defined(S_ISCHR)
return S_ISFIFO(Attr) || S_ISSOCK(Attr) || S_ISCHR(Attr);
#else
return false;
#endif
}
bool IsLink(uint Attr)
{
#ifdef _UNIX
return (Attr & 0xF000)==0xA000;
#elif defined(_WIN_ALL)
return (Attr & FILE_ATTRIBUTE_REPARSE_POINT)!=0;
#else
return false;
#endif
}
bool IsDeleteAllowed(uint FileAttr)
{
#ifdef _WIN_ALL
return (FileAttr & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))==0;
#else
return (FileAttr & (S_IRUSR|S_IWUSR))==(S_IRUSR|S_IWUSR);
#endif
}
void PrepareToDelete(const std::wstring &Name)
{
#ifdef _WIN_ALL
SetFileAttr(Name,0);
#endif
#ifdef _UNIX
std::string NameA;
WideToChar(Name,NameA);
chmod(NameA.c_str(),S_IRUSR|S_IWUSR|S_IXUSR);
#endif
}
uint GetFileAttr(const std::wstring &Name)
{
#ifdef _WIN_ALL
DWORD Attr=GetFileAttributes(Name.c_str());
if (Attr==0xffffffff)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
Attr=GetFileAttributes(LongName.c_str());
}
return Attr;
#else
std::string NameA;
WideToChar(Name,NameA);
struct stat st;
if (stat(NameA.c_str(),&st)!=0)
return 0;
return st.st_mode;
#endif
}
bool SetFileAttr(const std::wstring &Name,uint Attr)
{
#ifdef _WIN_ALL
bool Success=SetFileAttributes(Name.c_str(),Attr)!=0;
if (!Success)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
Success=SetFileAttributes(LongName.c_str(),Attr)!=0;
}
return Success;
#elif defined(_UNIX)
std::string NameA;
WideToChar(Name,NameA);
return chmod(NameA.c_str(),(mode_t)Attr)==0;
#else
return false;
#endif
}
// Ext is the extension with the leading dot, like L".bat", or nullptr to use
// the default extension.
bool MkTemp(std::wstring &Name,const wchar *Ext)
{
RarTime CurTime;
CurTime.SetCurrentTime();
// We cannot use CurTime.GetWin() as is, because its lowest bits can
// have low informational value, like being a zero or few fixed numbers.
uint Random=(uint)(CurTime.GetWin()/100000);
// Using PID we guarantee that different RAR copies use different temp names
// even if started in exactly the same time.
uint PID=0;
#ifdef _WIN_ALL
PID=(uint)GetCurrentProcessId();
#elif defined(_UNIX)
PID=(uint)getpid();
#endif
for (uint Attempt=0;;Attempt++)
{
uint RandomExt=Random%50000+Attempt;
if (Attempt==1000)
return false;
// User asked to specify the single extension for all temporary files,
// so it can be added to server ransomware protection exceptions.
// He wrote, this protection blocks temporary files when adding
// a file to RAR archive with drag and drop. So unless a calling code
// requires a specific extension, like .bat file when uninstalling,
// we set the uniform extension here.
if (Ext==nullptr)
Ext=L".rartemp";
std::wstring NewName=Name + std::to_wstring(PID) + L"." + std::to_wstring(RandomExt) + Ext;
if (!FileExist(NewName))
{
Name=NewName;
break;
}
}
return true;
}
#if !defined(SFX_MODULE)
void CalcFileSum(File *SrcFile,uint *CRC32,byte *Blake2,uint Threads,int64 Size,uint Flags)
{
int64 SavePos=SrcFile->Tell();
#ifndef SILENT
int64 FileLength=Size==INT64NDF ? SrcFile->FileLength() : Size;
#endif
if ((Flags & (CALCFSUM_SHOWTEXT|CALCFSUM_SHOWPERCENT))!=0)
uiMsg(UIEVENT_FILESUMSTART);
if ((Flags & CALCFSUM_CURPOS)==0)
SrcFile->Seek(0,SEEK_SET);
const size_t BufSize=0x100000;
std::vector<byte> Data(BufSize);
DataHash HashCRC,HashBlake2;
HashCRC.Init(HASH_CRC32,Threads);
HashBlake2.Init(HASH_BLAKE2,Threads);
int64 BlockCount=0;
int64 TotalRead=0;
while (true)
{
size_t SizeToRead;
if (Size==INT64NDF) // If we process the entire file.
SizeToRead=BufSize; // Then always attempt to read the entire buffer.
else
SizeToRead=(size_t)Min((int64)BufSize,Size);
int ReadSize=SrcFile->Read(Data.data(),SizeToRead);
if (ReadSize==0)
break;
TotalRead+=ReadSize;
if ((++BlockCount & 0xf)==0)
{
#ifndef SILENT
if ((Flags & CALCFSUM_SHOWPROGRESS)!=0)
{
// Update only the current file progress in WinRAR, set the total to 0
// to keep it as is. It looks better for WinRAR.
uiExtractProgress(TotalRead,FileLength,0,0);
}
else
{
if ((Flags & CALCFSUM_SHOWPERCENT)!=0)
uiMsg(UIEVENT_FILESUMPROGRESS,ToPercent(TotalRead,FileLength));
}
#endif
Wait();
}
if (CRC32!=NULL)
HashCRC.Update(Data.data(),ReadSize);
if (Blake2!=NULL)
HashBlake2.Update(Data.data(),ReadSize);
if (Size!=INT64NDF)
Size-=ReadSize;
}
SrcFile->Seek(SavePos,SEEK_SET);
if ((Flags & CALCFSUM_SHOWPERCENT)!=0)
uiMsg(UIEVENT_FILESUMEND);
if (CRC32!=NULL)
*CRC32=HashCRC.GetCRC32();
if (Blake2!=NULL)
{
HashValue Result;
HashBlake2.Result(&Result);
memcpy(Blake2,Result.Digest,sizeof(Result.Digest));
}
}
#endif
bool RenameFile(const std::wstring &SrcName,const std::wstring &DestName)
{
#ifdef _WIN_ALL
bool Success=MoveFile(SrcName.c_str(),DestName.c_str())!=0;
if (!Success)
{
std::wstring LongName1,LongName2;
if (GetWinLongPath(SrcName,LongName1) && GetWinLongPath(DestName,LongName2))
Success=MoveFile(LongName1.c_str(),LongName2.c_str())!=0;
}
return Success;
#else
std::string SrcNameA,DestNameA;
WideToChar(SrcName,SrcNameA);
WideToChar(DestName,DestNameA);
bool Success=rename(SrcNameA.c_str(),DestNameA.c_str())==0;
return Success;
#endif
}
bool DelFile(const std::wstring &Name)
{
#ifdef _WIN_ALL
bool Success=DeleteFile(Name.c_str())!=0;
if (!Success)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
Success=DeleteFile(LongName.c_str())!=0;
}
return Success;
#else
std::string NameA;
WideToChar(Name,NameA);
bool Success=remove(NameA.c_str())==0;
return Success;
#endif
}
bool DelDir(const std::wstring &Name)
{
#ifdef _WIN_ALL
bool Success=RemoveDirectory(Name.c_str())!=0;
if (!Success)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
Success=RemoveDirectory(LongName.c_str())!=0;
}
return Success;
#else
std::string NameA;
WideToChar(Name,NameA);
bool Success=rmdir(NameA.c_str())==0;
return Success;
#endif
}
#if defined(_WIN_ALL) && !defined(SFX_MODULE)
bool SetFileCompression(const std::wstring &Name,bool State)
{
HANDLE hFile=CreateFile(Name.c_str(),FILE_READ_DATA|FILE_WRITE_DATA,
FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_SEQUENTIAL_SCAN,NULL);
if (hFile==INVALID_HANDLE_VALUE)
{
std::wstring LongName;
if (GetWinLongPath(Name,LongName))
hFile=CreateFile(LongName.c_str(),FILE_READ_DATA|FILE_WRITE_DATA,
FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_SEQUENTIAL_SCAN,NULL);
if (hFile==INVALID_HANDLE_VALUE)
return false;
}
bool Success=SetFileCompression(hFile,State);
CloseHandle(hFile);
return Success;
}
bool SetFileCompression(HANDLE hFile,bool State)
{
SHORT NewState=State ? COMPRESSION_FORMAT_DEFAULT:COMPRESSION_FORMAT_NONE;
DWORD Result;
int RetCode=DeviceIoControl(hFile,FSCTL_SET_COMPRESSION,&NewState,
sizeof(NewState),NULL,0,&Result,NULL);
return RetCode!=0;
}
void ResetFileCache(const std::wstring &Name)
{
// To reset file cache in Windows it is enough to open it with
// FILE_FLAG_NO_BUFFERING and then close it.
HANDLE hSrc=CreateFile(Name.c_str(),GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,OPEN_EXISTING,FILE_FLAG_NO_BUFFERING,NULL);
if (hSrc!=INVALID_HANDLE_VALUE)
CloseHandle(hSrc);
}
#endif
// Delete symbolic links in file path, if any, and replace them by directories.
// Prevents extracting files outside of destination folder with symlink chains.
bool LinksToDirs(const std::wstring &SrcName,const std::wstring &SkipPart,std::wstring &LastChecked)
{
// Unlike Unix, Windows doesn't expand lnk1 in symlink targets like
// "lnk1/../dir", but converts the path to "dir". In Unix we need to call
// this function to prevent placing unpacked files outside of destination
// folder if previously we unpacked "dir/lnk1" -> "..",
// "dir/lnk2" -> "lnk1/.." and "dir/lnk2/anypath/poc.txt".
// We may still need this function to prevent abusing symlink chains
// in link source path if we remove detection of such chains
// in IsRelativeSymlinkSafe. This function seems to make other symlink
// related safety checks redundant, but for now we prefer to keep them too.
//
// 2022.12.01: the performance impact is minimized after adding the check
// against the previous path and enabling this verification only after
// extracting a symlink with ".." in target. So we enabled it for Windows
// as well for extra safety.
//#ifdef _UNIX
std::wstring Path=SrcName;
size_t SkipLength=SkipPart.size();
if (SkipLength>0 && Path.rfind(SkipPart,0)!=0)
SkipLength=0; // Parameter validation, not really needed now.
// Do not check parts already checked in previous path to improve performance.
for (size_t I=0;I<Path.size() && I<LastChecked.size() && Path[I]==LastChecked[I];I++)
if (IsPathDiv(Path[I]) && I>SkipLength)
SkipLength=I;
// Avoid converting symlinks in destination path part specified by user.
while (SkipLength<Path.size() && IsPathDiv(Path[SkipLength]))
SkipLength++;
if (Path.size()>0)
for (size_t I=Path.size()-1;I>SkipLength;I--)
if (IsPathDiv(Path[I]))
{
Path.erase(I);
FindData FD;
if (FindFile::FastFind(Path,&FD,true) && FD.IsLink)
{
#ifdef _WIN_ALL
// Normally Windows symlinks to directory look like a directory
// and are deleted with DelDir(). It is possible to create
// a file-like symlink pointing at directory, which can be deleted
// only with && DelFile, but such symlink isn't really functional.
// Here we prefer to fail deleting such symlink and skip extracting
// a file.
if (!DelDir(Path))
#else
if (!DelFile(Path))
#endif
{
ErrHandler.CreateErrorMsg(SrcName); // Extraction command will skip this file or directory.
return false; // Couldn't delete the symlink to replace it with directory.
}
}
}
LastChecked=SrcName;
//#endif
return true;
}
|