Esempio n. 1
0
// Returns file path including the trailing path separator symbol.
void GetFilePath(const wchar *FullName,wchar *Path,size_t MaxLength)
{
  if (MaxLength==0)
    return;
  size_t PathLength=Min(MaxLength-1,size_t(PointToName(FullName)-FullName));
  wcsncpy(Path,FullName,PathLength);
  Path[PathLength]=0;
}
Esempio n. 2
0
bool ScanTree::PrepareMasks()
{
  if (!FileMasks->GetString(CurMask,CurMaskW,sizeof(CurMask)))
    return(false);
#ifdef _WIN_32
  UnixSlashToDos(CurMask);
#endif
  char *Name=PointToName(CurMask);
  if (*Name==0)
    strcat(CurMask,MASKALL);
  if (Name[0]=='.' && (Name[1]==0 || Name[1]=='.' && Name[2]==0))
  {
    AddEndSlash(CurMask);
    strcat(CurMask,MASKALL);
  }
  SpecPathLength=Name-CurMask;
//  if (SpecPathLength>1)
//    SpecPathLength--;

  bool WideName=(*CurMaskW!=0);

  if (WideName)
  {
    wchar *NameW=PointToName(CurMaskW);
    if (*NameW==0)
      strcatw(CurMaskW,MASKALLW);
    if (NameW[0]=='.' && (NameW[1]==0 || NameW[1]=='.' && NameW[2]==0))
    {
      AddEndSlash(CurMaskW);
      strcatw(CurMaskW,MASKALLW);
    }
    SpecPathLengthW=NameW-CurMaskW;
  }
  else
  {
    wchar WideMask[NM];
    CharToWide(CurMask,WideMask);
    SpecPathLengthW=PointToName(WideMask)-WideMask;
  }
  Depth=0;

  strcpy(OrigCurMask,CurMask);
  strcpyw(OrigCurMaskW,CurMaskW);

  return(true);
}
Esempio n. 3
0
// Возвращает ".ext" или NULL в случае ошибки
const wchar_t* PointToExt(const wchar_t* asFullPath)
{
	const wchar_t* pszName = PointToName(asFullPath);
	if (!pszName)
		return NULL; // _ASSERTE уже был
	const wchar_t* pszExt = wcsrchr(pszName, L'.');
	return pszExt;
}
Esempio n. 4
0
	UINT DownloadFile(LPCWSTR asSource, LPCWSTR asTarget, DWORD& crc, DWORD& size, BOOL abShowAllErrors = FALSE)
	{
		UINT iRc = E_UNEXPECTED;
		UINT nWait;
		wchar_t* pszCommand = NULL;
		wchar_t* szCmdDirectory = NULL; // Destination directory for file creation

		MCHKHEAP;

		// Split target into directory and file-name
		LPCWSTR pszName = PointToName(asTarget);
		if (pszName > asTarget)
		{
			szCmdDirectory = lstrdup(asTarget);
			if (!szCmdDirectory)
			{
				iRc = E_OUTOFMEMORY;
				goto wrap;
			}
			szCmdDirectory[pszName-asTarget] = 0;
		}

		// Prepare command line for downloader tool
		pszCommand = CreateCommand(asSource, pszName, iRc);
		if (!pszCommand)
		{
			_ASSERTE(iRc!=0);
			goto wrap;
		}

		_ASSERTE(m_PI.hProcess==NULL);
		MCHKHEAP;

		nWait = ExecuteDownloader(pszCommand, szCmdDirectory);

		// Now check the result of downloader proc
		if (nWait != 0)
		{
			iRc = nWait;
			goto wrap;
		}

		if (!CalcFileHash(asTarget, size, crc))
		{
			iRc = GetLastError();
			if (!iRc)
				iRc = E_UNEXPECTED;
			goto wrap;
		}

		iRc = 0; // OK
	wrap:
		MCHKHEAP;
		SafeFree(pszCommand);
		SafeFree(szCmdDirectory);
		CloseHandles();
		return iRc;
	};
Esempio n. 5
0
void CSetPgFeatures::UpdateLogLocation()
{
	// Cut log file to directory only
	CEStr lsLogPath(gpSet->GetLogFileName());
	LPCWSTR pszName = lsLogPath.IsEmpty() ? NULL : PointToName(lsLogPath.ms_Val);
	if (pszName)
		*(wchar_t*)pszName = 0;
	SetDlgItemText(gpSetCls->GetPage(thi_Features), tDebugLogDir, lsLogPath);
}
Esempio n. 6
0
// IS: функция для внешнего мира, использовать ее
int CmpName(const wchar_t *pattern,const wchar_t *str, bool skippath, bool CmpNameSearchMode)
{
	if (!pattern || !str)
		return FALSE;

	if (skippath)
		str=PointToName(str);

	return CmpName_Body(pattern,str,CmpNameSearchMode);
}
Esempio n. 7
0
// Additionally to handling user input, it analyzes and sets command options.
// Returns only 'replace', 'skip' and 'cancel' codes.
UIASKREP_RESULT uiAskReplaceEx(RAROptions *Cmd,wchar *Name,size_t MaxNameSize,int64 FileSize,RarTime *FileTime,uint Flags)
{
  if (Cmd->Overwrite==OVERWRITE_NONE)
    return UIASKREP_R_SKIP;

#if !defined(SFX_MODULE) && !defined(SILENT)
  // Must be before Cmd->AllYes check or -y switch would override -or.
  if (Cmd->Overwrite==OVERWRITE_AUTORENAME && GetAutoRenamedName(Name,MaxNameSize))
    return UIASKREP_R_REPLACE;
#endif

  // This check must be after OVERWRITE_AUTORENAME processing or -y switch
  // would override -or.
  if (Cmd->AllYes || Cmd->Overwrite==OVERWRITE_ALL)
  {
    PrepareToDelete(Name);
    return UIASKREP_R_REPLACE;
  }

  wchar NewName[NM];
  wcsncpyz(NewName,Name,ASIZE(NewName));
  UIASKREP_RESULT Choice=uiAskReplace(NewName,ASIZE(NewName),FileSize,FileTime,Flags);

  if (Choice==UIASKREP_R_REPLACE || Choice==UIASKREP_R_REPLACEALL)
    PrepareToDelete(Name);

  if (Choice==UIASKREP_R_REPLACEALL)
  {
    Cmd->Overwrite=OVERWRITE_ALL;
    return UIASKREP_R_REPLACE;
  }
  if (Choice==UIASKREP_R_SKIPALL)
  {
    Cmd->Overwrite=OVERWRITE_NONE;
    return UIASKREP_R_SKIP;
  }
  if (Choice==UIASKREP_R_RENAME)
  {
    if (PointToName(NewName)==NewName)
      SetName(Name,NewName,MaxNameSize);
    else
      wcsncpyz(Name,NewName,MaxNameSize);
    if (FileExist(Name))
      return uiAskReplaceEx(Cmd,Name,MaxNameSize,FileSize,FileTime,Flags);
    return UIASKREP_R_REPLACE;
  }
#if !defined(SFX_MODULE) && !defined(SILENT)
  if (Choice==UIASKREP_R_RENAMEAUTO && GetAutoRenamedName(Name,MaxNameSize))
  {
    Cmd->Overwrite=OVERWRITE_AUTORENAME;
    return UIASKREP_R_REPLACE;
  }
#endif
  return Choice;
}
Esempio n. 8
0
void RemoveOldComSpecC()
{
	wchar_t szComSpec[MAX_PATH], szComSpecC[MAX_PATH], szRealComSpec[MAX_PATH];
	//110202 - comspec более не переопределяется, поэтому вернем "cmd",
	// если был переопреден и унаследован от старой версии conemu
	if (GetEnvironmentVariable(L"ComSpecC", szComSpecC, countof(szComSpecC)) && szComSpecC[0] != 0)
	{
		szRealComSpec[0] = 0;

		if (!GetEnvironmentVariable(L"ComSpec", szComSpec, countof(szComSpec)))
			szComSpec[0] = 0;

		#ifndef __GNUC__
		#pragma warning( push )
		#pragma warning(disable : 6400)
		#endif

		LPCWSTR pwszName = PointToName(szComSpec);

		if (lstrcmpiW(pwszName, L"ConEmuC.exe")==0 || lstrcmpiW(pwszName, L"ConEmuC64.exe")==0)
		{
			pwszName = PointToName(szComSpecC);
			if (lstrcmpiW(pwszName, L"ConEmuC.exe")!=0 && lstrcmpiW(pwszName, L"ConEmuC64.exe")!=0)
			{
				wcscpy_c(szRealComSpec, szComSpecC);
			}
		}
		#ifndef __GNUC__
		#pragma warning( pop )
		#endif

		if (szRealComSpec[0] == 0)
		{
			//\system32\cmd.exe
			GetComspecFromEnvVar(szRealComSpec, countof(szRealComSpec));
		}

		SetEnvironmentVariable(L"ComSpec", szRealComSpec);
		SetEnvironmentVariable(L"ComSpecC", NULL);
	}
}
Esempio n. 9
0
CDefTermHk::CDefTermHk()
	: CDefTermBase(false)
{
	mh_StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	wchar_t szSelfName[MAX_PATH+1] = L"";
	GetModuleFileName(NULL, szSelfName, countof(szSelfName));
	lstrcpyn(ms_ExeName, PointToName(szSelfName), countof(ms_ExeName));

	mn_LastCheck = 0;
	ReloadSettings();
}
Esempio n. 10
0
bool IsFarExe(LPCWSTR asModuleName)
{
	if (asModuleName && *asModuleName)
	{
		LPCWSTR pszName = PointToName(asModuleName);
		if (lstrcmpi(pszName, L"far.exe") == 0 || lstrcmpi(pszName, L"far") == 0
			|| lstrcmpi(pszName, L"far64.exe") == 0 || lstrcmpi(pszName, L"far64") == 0)
		{
			return true;
		}
	}
	return false;
}
Esempio n. 11
0
bool UpdateExistingShortName(char *Name,wchar *NameW)
{
  FindData fd;
  if (!FindFile::FastFind(Name,NameW,&fd))
    return(false);
  if (*fd.Name==0 || *fd.ShortName==0)
    return(false);
  if (stricomp(PointToName(fd.Name),fd.ShortName)==0 ||
      stricomp(PointToName(Name),fd.ShortName)!=0)
    return(false);

  char NewName[NM];
  for (int I=0;I<10000;I+=123)
  {
    strncpyz(NewName,Name,ASIZE(NewName));
    sprintf(PointToName(NewName),"rtmp%d",I);
    if (!FileExist(NewName))
      break;
  }
  if (FileExist(NewName))
    return(false);
  char FullName[NM];
  strncpyz(FullName,Name,ASIZE(FullName));
  strcpy(PointToName(FullName),PointToName(fd.Name));
  if (!MoveFile(FullName,NewName))
    return(false);
  File KeepShortFile;
  bool Created=false;
  if (!FileExist(Name))
    Created=KeepShortFile.Create(Name);
  MoveFile(NewName,FullName);
  if (Created)
  {
    KeepShortFile.Close();
    KeepShortFile.Delete();
  }
  return(true);
}
Esempio n. 12
0
void MakeNameUsable(char *Name, bool bKeepExtension, bool IsFATX)
{
  // Changed to be compatible with xbmc's MakeLegalFileName function
  // (xbox only)

  if ( Name == NULL) return;
  char cIllegalChars[] = "<>=?;\"*+,/|";
  unsigned int iIllegalCharSize = strlen(cIllegalChars);
  bool isIllegalChar;
  unsigned int iSize = strlen(Name);
  unsigned int iNewStringSize = 0;
  char* strNewString = new char[iSize + 1];

  // only copy the legal characters to the new filename
  for (unsigned int i = 0; i < iSize; i++)
  {
    isIllegalChar = false;
    // check for illigal chars
    for (unsigned j = 0; j < iIllegalCharSize; j++)
      if (Name[i] == cIllegalChars[j]) isIllegalChar = true;
    // FATX only allows chars from 32 till 127
    if (isIllegalChar == false &&
        Name[i] > 31 && Name[i] < 127) strNewString[iNewStringSize++] = Name[i];
  }
  strNewString[iNewStringSize] = '\0';

  if (IsFATX)
  {
    // since we can only write to samba shares and hd, we assume this has to be a fatx filename
    // thus we have to strip it down to 42 chars (samba doesn't have this limitation)
  
    char* FileName = PointToName(strNewString);
    int iFileNameSize = strlen(FileName);
    // no need to keep the extension, just strip it down to 42 characters
    if (iFileNameSize > 42 && bKeepExtension == false) FileName[42] = '\0';

    // we want to keep the extension
    else if (iFileNameSize > 42 && bKeepExtension == true)
    {
      char strExtension[42];
      unsigned int iExtensionLength = iFileNameSize - (strrchr(FileName, '.') - FileName);
      strcpy(strExtension, (FileName + iFileNameSize - iExtensionLength));

      strcpy(FileName + (42 - iExtensionLength), strExtension);
    }
  }

  strcpy(Name, strNewString);
  delete[] strNewString;
}
Esempio n. 13
0
bool CmpName(char *Wildcard,char *Name,int CmpPath)
{
  if (CmpPath!=MATCH_NAMES)
  {
    int WildLength=strlen(Wildcard);
    if (CmpPath!=MATCH_EXACTPATH && strnicompc(Wildcard,Name,WildLength)==0)
    {
      char NextCh=Name[WildLength];
      if (NextCh=='\\' || NextCh=='/' || NextCh==0)
        return(true);
    }
    char Path1[NM],Path2[NM];
    GetFilePath(Wildcard,Path1);
    GetFilePath(Name,Path2);
    if (stricompc(Wildcard,Path2)==0)
      return(true);
    if ((CmpPath==MATCH_PATH || CmpPath==MATCH_EXACTPATH) && stricompc(Path1,Path2)!=0)
      return(false);
    if (CmpPath==MATCH_SUBPATH || CmpPath==MATCH_WILDSUBPATH)
      if (IsWildcard(Path1))
        return(match(Wildcard,Name));
      else
        if (CmpPath==MATCH_SUBPATH || IsWildcard(Wildcard))
        {
          if (*Path1 && strnicompc(Path1,Path2,strlen(Path1))!=0)
            return(false);
        }
        else
          if (stricompc(Path1,Path2)!=0)
            return(false);
  }
  char *Name1=PointToName(Wildcard);
  char *Name2=PointToName(Name);
  if (strnicompc("__rar_",Name2,6)==0)
    return(false);
  return(match(Name1,Name2));
}
Esempio n. 14
0
void Panel::DragMessage(int X,int Y,int Move)
{
	const auto SelCount = SrcDragPanel->GetSelCount();

	if (!SelCount)
		return;

	string strSelName;

	if (SelCount == 1)
	{
		os::fs::find_data Data;
		if (!SrcDragPanel->get_first_selected(Data))
			return;

		assign(strSelName, PointToName(Data.FileName));
		QuoteSpace(strSelName);
	}
	else
	{
		strSelName = format(msg(lng::MDragFiles), SelCount);
	}

	auto strDragMsg = format(msg(Move? lng::MDragMove : lng::MDragCopy), strSelName);

	auto Length = static_cast<int>(strDragMsg.size());
	int MsgX = X;

	if (Length + X > ScrX)
	{
		MsgX=ScrX-Length;

		if (MsgX<0)
		{
			MsgX=0;
			TruncStrFromEnd(strDragMsg,ScrX);
			Length=(int)strDragMsg.size();
		}
	}

	SCOPED_ACTION(ChangePriority)(THREAD_PRIORITY_NORMAL);
	// Important - the old one must be deleted before creating a new one, not after
	DragSaveScr.reset();
	DragSaveScr = std::make_unique<SaveScreen>(MsgX, Y, MsgX + Length - 1, Y);
	GotoXY(MsgX,Y);
	SetColor(COL_PANELDRAGTEXT);
	Text(strDragMsg);
}
Esempio n. 15
0
bool GetProcessInfo(LPCWSTR asExeName, PROCESSENTRY32W* Info)
{
	struct cmp
	{
		static bool compare(PROCESSENTRY32W* p, LPARAM lParam)
		{
			LPCWSTR pszName1 = PointToName(p->szExeFile);
			LPCWSTR pszName2 = (LPCWSTR)lParam;
			int iCmp = lstrcmpi(pszName1, pszName2);
			return (iCmp == 0);
		};
	};
	LPCWSTR pszName = PointToName(asExeName);
	if (!pszName || !*pszName)
		return false;
	return GetProcessInfo(cmp::compare, (LPARAM)pszName, Info);
}
Esempio n. 16
0
void FilePanels::GoToFile(const wchar_t *FileName)
{
	if (FirstSlash(FileName))
	{
		string ADir,PDir;
		Panel *PassivePanel = GetAnotherPanel(ActivePanel);
		int PassiveMode = PassivePanel->GetMode();

		if (PassiveMode == NORMAL_PANEL)
		{
			PassivePanel->GetCurDir(PDir);
			AddEndSlash(PDir);
		}

		int ActiveMode = ActivePanel->GetMode();

		if (ActiveMode==NORMAL_PANEL)
		{
			ActivePanel->GetCurDir(ADir);
			AddEndSlash(ADir);
		}

		string strNameFile = PointToName(FileName);
		string strNameDir = FileName;
		CutToSlash(strNameDir);
		/* $ 10.04.2001 IS
		     Не делаем SetCurDir, если нужный путь уже есть на открытых
		     панелях, тем самым добиваемся того, что выделение с элементов
		     панелей не сбрасывается.
		*/
		BOOL AExist=(ActiveMode==NORMAL_PANEL) && !StrCmpI(ADir,strNameDir);
		BOOL PExist=(PassiveMode==NORMAL_PANEL) && !StrCmpI(PDir,strNameDir);

		// если нужный путь есть на пассивной панели
		if (!AExist && PExist)
			ProcessKey(KEY_TAB);

		if (!AExist && !PExist)
			ActivePanel->SetCurDir(strNameDir,TRUE);

		ActivePanel->GoToFile(strNameFile);
		// всегда обновим заголовок панели, чтобы дать обратную связь, что
		// Ctrl-F10 обработан
		ActivePanel->SetTitle();
	}
}
Esempio n. 17
0
// For masks like dir1\dir2*\*.ext in non-recursive mode.
bool ScanTree::ExpandFolderMask()
{
  bool WildcardFound=false;
  uint SlashPos=0;
  for (int I=0;CurMask[I]!=0;I++)
  {
    if (CurMask[I]=='?' || CurMask[I]=='*')
      WildcardFound=true;
    if (WildcardFound && IsPathDiv(CurMask[I]))
    {
      // First path separator position after folder wildcard mask.
      // In case of dir1\dir2*\dir3\name.ext mask it may point not to file
      // name, so we cannot use PointToName() here.
      SlashPos=I; 
      break;
    }
  }

  wchar Mask[NM];
  wcsncpyz(Mask,CurMask,ASIZE(Mask));
  Mask[SlashPos]=0;

  // Prepare the list of all folders matching the wildcard mask.
  ExpandedFolderList.Reset();
  FindFile Find;
  Find.SetMask(Mask);
  FindData FD;
  while (Find.Next(&FD))
    if (FD.IsDir)
    {
      wcsncatz(FD.Name,CurMask+SlashPos,ASIZE(FD.Name));

      // Treat dir*\* or dir*\*.* as dir, so empty 'dir' is also matched
      // by such mask. Skipping empty dir with dir*\*.* confused some users.
      wchar *LastMask=PointToName(FD.Name);
      if (wcscmp(LastMask,L"*")==0 || wcscmp(LastMask,L"*.*")==0)
        RemoveNameFromPath(FD.Name);

      ExpandedFolderList.AddString(FD.Name);
    }
  if (ExpandedFolderList.ItemsCount()==0)
    return false;
  // Return the first matching folder name now.
  ExpandedFolderList.GetString(CurMask,ASIZE(CurMask));
  return true;
}
Esempio n. 18
0
void ScanTree::ScanError(bool &Error)
{
#ifdef _WIN_ALL
  if (Error)
  {
    // Get attributes of parent folder and do not display an error
    // if it is reparse point. We cannot scan contents of standard
    // Windows reparse points like "C:\Documents and Settings"
    // and we do not want to issue numerous useless errors for them.
    // We cannot just check FD->FileAttr here, it can be undefined
    // if we process "folder\*" mask or if we process "folder" mask,
    // but "folder" is inaccessible.
    wchar *Slash=PointToName(CurMask);
    if (Slash>CurMask)
    {
      *(Slash-1)=0;
      DWORD Attr=GetFileAttributes(CurMask);
      *(Slash-1)=CPATHDIVIDER;
      if (Attr!=0xffffffff && (Attr & FILE_ATTRIBUTE_REPARSE_POINT)!=0)
        Error=false;
    }

    // Do not display an error if we cannot scan contents of
    // "System Volume Information" folder. Normally it is not accessible.
    if (wcsstr(CurMask,L"System Volume Information\\")!=NULL)
      Error=false;
  }
#endif

  if (Error && Cmd!=NULL && Cmd->ExclCheck(CurMask,false,true,true))
    Error=false;

  if (Error)
  {
    if (ErrDirList!=NULL)
      ErrDirList->AddString(CurMask);
    if (ErrDirSpecPathLength!=NULL)
      ErrDirSpecPathLength->Push((uint)SpecPathLength);
    wchar FullName[NM];
    // This conversion works for wildcard masks too.
    ConvertNameToFull(CurMask,FullName,ASIZE(FullName));
    uiMsg(UIERROR_DIRSCAN,FullName);
    ErrHandler.SysErrMsg();
  }
}
Esempio n. 19
0
void CSetPgDebug::debugLogCommand(CESERVER_REQ* pInfo, BOOL abInput, DWORD anTick, DWORD anDur, LPCWSTR asPipe, CESERVER_REQ* pResult/*=NULL*/)
{
	CSetPgDebug* pDbgPg = (CSetPgDebug*)gpSetCls->GetPageObj(thi_Debug);
	if (!pDbgPg)
		return;
	if (pDbgPg->GetActivityLoggingType() != glt_Commands)
		return;

	_ASSERTE(abInput==TRUE || pResult!=NULL || (pInfo->hdr.nCmd==CECMD_LANGCHANGE || pInfo->hdr.nCmd==CECMD_GUICHANGED || pInfo->hdr.nCmd==CMD_FARSETCHANGED || pInfo->hdr.nCmd==CECMD_ONACTIVATION));

	LogCommandsData* pData = (LogCommandsData*)calloc(1,sizeof(LogCommandsData));

	if (!pData)
		return;

	pData->bInput = abInput;
	pData->bMainThread = (abInput == FALSE) && isMainThread();
	pData->nTick = anTick - pDbgPg->mn_ActivityCmdStartTick;
	pData->nDur = anDur;
	pData->nCmd = pInfo->hdr.nCmd;
	pData->nSize = pInfo->hdr.cbSize;
	pData->nPID = abInput ? pInfo->hdr.nSrcPID : pResult ? pResult->hdr.nSrcPID : 0;
	LPCWSTR pszName = asPipe ? PointToName(asPipe) : NULL;
	lstrcpyn(pData->szPipe, pszName ? pszName : L"", countof(pData->szPipe));
	switch (pInfo->hdr.nCmd)
	{
	case CECMD_POSTCONMSG:
		_wsprintf(pData->szExtra, SKIPLEN(countof(pData->szExtra))
			L"HWND=x%08X, Msg=%u, wParam=" WIN3264TEST(L"x%08X",L"x%08X%08X") L", lParam=" WIN3264TEST(L"x%08X",L"x%08X%08X") L": ",
			pInfo->Msg.hWnd, pInfo->Msg.nMsg, WIN3264WSPRINT(pInfo->Msg.wParam), WIN3264WSPRINT(pInfo->Msg.lParam));
		GetClassName(pInfo->Msg.hWnd, pData->szExtra+lstrlen(pData->szExtra), countof(pData->szExtra)-lstrlen(pData->szExtra));
		break;
	case CECMD_NEWCMD:
		lstrcpyn(pData->szExtra, pInfo->NewCmd.GetCommand(), countof(pData->szExtra));
		break;
	case CECMD_GUIMACRO:
		lstrcpyn(pData->szExtra, pInfo->GuiMacro.sMacro, countof(pData->szExtra));
		break;
	case CMD_POSTMACRO:
		lstrcpyn(pData->szExtra, (LPCWSTR)pInfo->wData, countof(pData->szExtra));
		break;
	}

	PostMessage(pDbgPg->Dlg(), DBGMSG_LOG_ID, DBGMSG_LOG_CMD_MAGIC, (LPARAM)pData);
}
Esempio n. 20
0
bool GetPassword(PASSWORD_TYPE Type,const char *FileName,char *Password,int MaxLength)
{
  Alarm();
  while (true)
  {
    char PromptStr[256];
#if defined(_EMX) || defined(_BEOS)
    strcpy(PromptStr,St(MAskPswEcho));
#else
    strcpy(PromptStr,St(MAskPsw));
#endif
    if (Type!=PASSWORD_GLOBAL)
    {
      strcat(PromptStr,St(MFor));
      strcat(PromptStr,PointToName(FileName));
    }
    eprintf("\n%s: ",PromptStr);
    GetPasswordText(Password,MaxLength);
    if (*Password==0 && Type==PASSWORD_GLOBAL)
      return(false);
    if (Type==PASSWORD_GLOBAL)
    {
      strcpy(PromptStr,St(MReAskPsw));
      eprintf(PromptStr);
      char CmpStr[256];
      GetPasswordText(CmpStr,sizeof(CmpStr));
      if (*CmpStr==0 || strcmp(Password,CmpStr)!=0)
      {
        strcpy(PromptStr,St(MNotMatchPsw));
/*
#ifdef _WIN_32
        CharToOem(PromptStr,PromptStr);
#endif
*/
        eprintf(PromptStr);
        memset(Password,0,MaxLength);
        memset(CmpStr,0,sizeof(CmpStr));
        continue;
      }
      memset(CmpStr,0,sizeof(CmpStr));
    }
    break;
  }
  return(true);
}
Esempio n. 21
0
/*
	DefaultName - имя элемента на которое позиционируемся.
	Closed - панель закрывается, если в PrevDataList что-то есть - восстанавливаемчся оттуда.
	UsePrev - если востанавливаемся из PrevDataList, элемент для позиционирования брать оттуда же.
	Position - надо ли вообще устанавливать текущий элемент.
*/
void FileList::PopPrevData(const string& DefaultName,bool Closed,bool UsePrev,bool Position,bool SetDirectorySuccess)
{
    string strName(DefaultName);
	if (Closed && !PrevDataList.Empty())
	{
		PrevDataItem* Item=*PrevDataList.Last();
		PrevDataList.Delete(PrevDataList.Last());
		if (Item->PrevFileCount>0)
		{
			MoveSelection(ListData,FileCount,Item->PrevListData,Item->PrevFileCount);
			UpperFolderTopFile = Item->PrevTopFile;

			if (UsePrev)
				strName = Item->strPrevName;

			DeleteListData(Item->PrevListData,Item->PrevFileCount);
			delete Item;

			if (SelectedFirst)
				SortFileList(FALSE);
			else if (FileCount>0)
				SortFileList(TRUE);
		}
	}
	if (Position)
	{
		long Pos=FindFile(PointToName(strName));

		if (Pos!=-1)
			CurFile=Pos;
		else
			GoToFile(strName);

		CurTopFile=UpperFolderTopFile;
		UpperFolderTopFile=0;
		CorrectPosition();
	}
	/* $ 26.04.2001 DJ
	   доделка про несброс выделения при неудаче SetDirectory
	*/
	else if (SetDirectorySuccess)
		CurFile=CurTopFile=0;
}
Esempio n. 22
0
wchar_t* GetParentPath(LPCWSTR asPath)
{
	if (!asPath || !*asPath)
		return NULL;
	LPCWSTR pszName = PointToName(asPath);
	if (!pszName)
		return NULL;
	while ((pszName > asPath) && (*(pszName-1) == L'\\' || *(pszName-1) == L'/'))
		--pszName;
	if (pszName <= asPath)
		return NULL;

	size_t cch = pszName - asPath;
	wchar_t* parent = (wchar_t*)malloc((cch + 1) * sizeof(*parent));
	if (!parent)
		return NULL;
	wcsncpy_s(parent, cch+1, asPath, cch);
	parent[cch] = 0;
	return parent;
}
Esempio n. 23
0
char* GetVolNumPart(char *ArcName)
{
  char *ChPtr=ArcName+strlen(ArcName)-1;
  while (!isdigit(*ChPtr) && ChPtr>ArcName)
    ChPtr--;
  char *NumPtr=ChPtr;
  while (isdigit(*NumPtr) && NumPtr>ArcName)
    NumPtr--;
  while (NumPtr>ArcName && *NumPtr!='.')
  {
    if (isdigit(*NumPtr))
    {
      char *Dot=strchrd(PointToName(ArcName),'.');
      if (Dot!=NULL && Dot<NumPtr)
        ChPtr=NumPtr;
      break;
    }
    NumPtr--;
  }
  return(ChPtr);
}
Esempio n. 24
0
bool CheckProcessName(LPCWSTR pszProcessName, LPCWSTR* lsNames)
{
	LPCWSTR pszName1 = PointToName(pszProcessName);
	if (!pszName1 || !*pszName1 || !lsNames)
		return false;

	LPCWSTR pszExt1 = wcsrchr(pszName1, L'.');

	CEStr lsName1;
	if (!pszExt1)
	{
		lsName1.Attach(lstrmerge(pszName1, L".exe"));
		pszName1 = lsName1;
		if (!pszName1)
			return false;
	}

	for (size_t i = 0; lsNames[i]; i++)
	{
		LPCWSTR pszName2 = lsNames[i];

		_ASSERTE(wcsrchr(pszName2, L'.') != NULL);
		#if 0
		CEStr lsName2;
		LPCWSTR pszExt2 = wcsrchr(pszName2, L'.');
		if (!pszExt2)
		{
			lsName2 = lstrmerge(pszName2, L".exe");
			pszName2 = lsName2;
			if (!pszName2)
				return false;
		}
		#endif

		if (lstrcmpi(pszName1, pszName2) == 0)
			return true;
	}

	return false;
}
Esempio n. 25
0
bool GetPassword(PASSWORD_TYPE Type,const char *FileName,char *Password,int MaxLength)
{
  Alarm();
  while (true)
  {
    char PromptStr[NM+256];
#if defined(_EMX) || defined(_BEOS)
    strcpy(PromptStr,St(MAskPswEcho));
#else
    strcpy(PromptStr,St(MAskPsw));
#endif
    if (Type!=PASSWORD_GLOBAL)
    {
      strcat(PromptStr,St(MFor));
      char *NameOnly=PointToName(FileName);
      if (strlen(PromptStr)+strlen(NameOnly)<ASIZE(PromptStr))
        strcat(PromptStr,NameOnly);
    }
    eprintf("\n%s: ",PromptStr);
    GetPasswordText(Password,MaxLength);
    if (*Password==0 && Type==PASSWORD_GLOBAL)
      return(false);
    if (Type==PASSWORD_GLOBAL)
    {
      eprintf(St(MReAskPsw));
      char CmpStr[MAXPASSWORD];
      GetPasswordText(CmpStr,ASIZE(CmpStr));
      if (*CmpStr==0 || strcmp(Password,CmpStr)!=0)
      {
        eprintf(St(MNotMatchPsw));
        memset(Password,0,MaxLength);
        memset(CmpStr,0,sizeof(CmpStr));
        continue;
      }
      memset(CmpStr,0,sizeof(CmpStr));
    }
    break;
  }
  return(true);
}
Esempio n. 26
0
void * __cdecl xf_calloc
(
		size_t _Count, size_t _Size
#ifdef TRACK_MEMORY_ALLOCATIONS
		, LPCSTR lpszFileName, int nLine
#endif
)
{
	_ASSERTE(ghHeap);
	_ASSERTE((_Count*_Size)>0);
#ifdef TRACK_MEMORY_ALLOCATIONS
	xf_mem_block* p = (xf_mem_block*)HeapAlloc(ghHeap, HEAP_ZERO_MEMORY, _Count*_Size+sizeof(xf_mem_block)+8);
	p->bBlockUsed = TRUE;
	p->nBlockSize = _Count*_Size;
	wsprintfA(p->sCreatedFrom, "%s:%i", PointToName(lpszFileName), nLine);
	memset(((LPBYTE)(p+1))+_Count*_Size, 0xCC, 8);
	return p?(p+1):p;
#else
	void* p = HeapAlloc(ghHeap, HEAP_ZERO_MEMORY, _Count*_Size);
	return p;
#endif
}
Esempio n. 27
0
void __cdecl xf_free
(
		void * _Memory
#ifdef TRACK_MEMORY_ALLOCATIONS
		, LPCSTR lpszFileName, int nLine
#endif
)
{
	_ASSERTE(ghHeap && _Memory);

#ifdef TRACK_MEMORY_ALLOCATIONS
	xf_mem_block* p = ((xf_mem_block*)_Memory)-1;
	if (p->bBlockUsed == TRUE)
	{
		int nCCcmp = memcmp(((LPBYTE)_Memory)+p->nBlockSize, "\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC", 8);
		_ASSERTE(nCCcmp == 0);
		memset(_Memory, 0xFD, p->nBlockSize);
	} else {
		_ASSERTE(p->bBlockUsed == TRUE);
	}
	p->bBlockUsed = FALSE;
	wsprintfA(p->sCreatedFrom, "-- %s:%i", PointToName(lpszFileName), nLine);
	_Memory = (void*)p;
#endif

	#ifdef _DEBUG
	__int64 _Size1 = HeapSize(ghHeap, 0, _Memory);
	_ASSERTE(_Size1 > 0);
	#endif
	
	HeapFree(ghHeap, 0, _Memory);
	
	//#ifdef _DEBUG
	//SIZE_T _Size2 = HeapSize(ghHeap, 0, _Memory);
	//if (_Size1 == _Size2) {
	//	_ASSERTE(_Size1 != _Size2);
	//}
	//#endif
}
Esempio n. 28
0
File: main.cpp Progetto: elfmz/far2l
static void SetupFarPath(int argc, char **argv)
{
	InitCurrentDirectory();
	char buf[PATH_MAX + 1] = {};
	ssize_t buf_sz = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
	if (buf_sz <= 0 || buf_sz >= (ssize_t)sizeof(buf) - 1 || buf[0] != GOOD_SLASH) {
		if (argv[0][0]!=GOOD_SLASH) {
			apiGetCurrentDirectory(g_strFarModuleName);
			if (argv[0][0]=='.') {
				g_strFarModuleName+= argv[0] + 1;
			} else {
				g_strFarModuleName+= GOOD_SLASH;
				g_strFarModuleName+= argv[0];
			}
		} else
			g_strFarModuleName = argv[0];			
	} else {
		buf[buf_sz] = 0;
		g_strFarModuleName = buf;
	}
			
	

	FARString dir = g_strFarModuleName;
	CutToSlash(dir, true);
	const wchar_t *last_element = PointToName(dir);
	if (last_element && wcscmp(last_element, L"bin") == 0) {
		CutToSlash(dir, false);
		SetPathTranslationPrefix(dir);
	}

	fprintf(stderr, "argv[0]='%s' g_strFarModuleName='%ls' translation_prefix='%ls'\n", 
		argv[0], g_strFarModuleName.CPtr(), GetPathTranslationPrefix());

	PrepareDiskPath(g_strFarModuleName);
}
Esempio n. 29
0
SCAN_CODE ScanTree::FindProc(FindData *FD)
{
  if (*CurMask==0)
    return SCAN_NEXT;
  bool FastFindFile=false;
  
  if (FindStack[Depth]==NULL) // No FindFile object for this depth yet.
  {
    bool Wildcards=IsWildcard(CurMask);

    // If we have a file name without wildcards, we can try to use
    // FastFind to optimize speed. For example, in Unix it results in
    // stat call instead of opendir/readdir/closedir.
    bool FindCode=!Wildcards && FindFile::FastFind(CurMask,FD,GetLinks);

    // Link check is important for NTFS, where links can have "Directory"
    // attribute, but we do not want to recurse to them in "get links" mode.
    bool IsDir=FindCode && FD->IsDir && (!GetLinks || !FD->IsLink);

    // SearchAll means that we'll use "*" mask for search, so we'll find
    // subdirectories and will be able to recurse into them.
    // We do not use "*" for directories at any level or for files
    // at top level in recursion mode. We always comrpess the entire directory
    // if folder wildcard is specified.
    bool SearchAll=!IsDir && (Depth>0 || Recurse==RECURSE_ALWAYS ||
                   FolderWildcards && Recurse!=RECURSE_DISABLE || 
                   Wildcards && Recurse==RECURSE_WILDCARDS || 
                   ScanEntireDisk && Recurse!=RECURSE_DISABLE);
    if (Depth==0)
      SearchAllInRoot=SearchAll;
    if (SearchAll || Wildcards)
    {
      // Create the new FindFile object for wildcard based search.
      FindStack[Depth]=new FindFile;

      wchar SearchMask[NM];
      wcsncpyz(SearchMask,CurMask,ASIZE(SearchMask));
      if (SearchAll)
        SetName(SearchMask,MASKALL,ASIZE(SearchMask));
      FindStack[Depth]->SetMask(SearchMask);
    }
    else
    {
      // Either we failed to fast find or we found a file or we found
      // a directory in RECURSE_DISABLE mode, so we do not need to scan it.
      // We can return here and do not need to process further.
      // We need to process further only if we fast found a directory.
      if (!FindCode || !IsDir || Recurse==RECURSE_DISABLE)
      {
         // Return SCAN_SUCCESS if we found a file.
        SCAN_CODE RetCode=SCAN_SUCCESS;

        if (!FindCode)
        {
          // Return SCAN_ERROR if problem is more serious than just
          // "file not found".
          RetCode=FD->Error ? SCAN_ERROR:SCAN_NEXT;

          // If we failed to find an object, but our current mask is excluded,
          // we skip this object and avoid indicating an error.
          if (Cmd!=NULL && Cmd->ExclCheck(CurMask,false,true,true))
            RetCode=SCAN_NEXT;
          else
          {
            ErrHandler.OpenErrorMsg(ErrArcName,CurMask);
            // User asked to return RARX_NOFILES and not RARX_OPEN here.
            ErrHandler.SetErrorCode(RARX_NOFILES);
          }
        }

        // If we searched only for one file or directory in "fast find" 
        // (without a wildcard) mode, let's set masks to zero, 
        // so calling function will know that current mask is used 
        // and next one must be read from mask list for next call.
        // It is not necessary for directories, because even in "fast find"
        // mode, directory recursing will quit by (Depth < 0) condition,
        // which returns SCAN_DONE to calling function.
        *CurMask=0;

        return RetCode;
      }

      // We found a directory using only FindFile::FastFind function.
      FastFindFile=true;
    }
  }

  if (!FastFindFile && !FindStack[Depth]->Next(FD,GetLinks))
  {
    // We cannot find anything more in directory either because of
    // some error or just as result of all directory entries already read.

    bool Error=FD->Error;
    if (Error)
      ScanError(Error);

    wchar DirName[NM];
    *DirName=0;

    // Going to at least one directory level higher.
    delete FindStack[Depth];
    FindStack[Depth--]=NULL;
    while (Depth>=0 && FindStack[Depth]==NULL)
      Depth--;
    if (Depth < 0)
    {
      // Directories scanned both in normal and FastFindFile mode,
      // finally exit from scan here, by (Depth < 0) condition.

      if (Error)
        Errors++;
      return SCAN_DONE;
    }

    wchar *Slash=wcsrchr(CurMask,CPATHDIVIDER);
    if (Slash!=NULL)
    {
      wchar Mask[NM];
      wcsncpyz(Mask,Slash,ASIZE(Mask));
      if (Depth<SetAllMaskDepth)
        wcsncpyz(Mask+1,PointToName(OrigCurMask),ASIZE(Mask)-1);
      *Slash=0;
      wcsncpyz(DirName,CurMask,ASIZE(DirName));
      wchar *PrevSlash=wcsrchr(CurMask,CPATHDIVIDER);
      if (PrevSlash==NULL)
        wcsncpyz(CurMask,Mask+1,ASIZE(CurMask));
      else
      {
        *(PrevSlash+1)=0;
        wcsncatz(CurMask,Mask,ASIZE(CurMask));
      }
    }
    if (GetDirs==SCAN_GETDIRSTWICE &&
        FindFile::FastFind(DirName,FD,GetLinks) && FD->IsDir)
    {
      FD->Flags|=FDDF_SECONDDIR;
      return Error ? SCAN_ERROR:SCAN_SUCCESS;
    }
    return Error ? SCAN_ERROR:SCAN_NEXT;
  }

  // Link check is required for NTFS links, not for Unix.
  if (FD->IsDir && (!GetLinks || !FD->IsLink))
  {
    // If we found the directory in top (Depth==0) directory
    // and if we are not in "fast find" (directory name only as argument)
    // or in recurse (SearchAll was set when opening the top directory) mode,
    // we do not recurse into this directory. We either return it by itself
    // or skip it.
    if (!FastFindFile && Depth==0 && !SearchAllInRoot)
      return GetDirs==SCAN_GETCURDIRS ? SCAN_SUCCESS:SCAN_NEXT;

    // Let's check if directory name is excluded, so we do not waste
    // time searching in directory, which will be excluded anyway.
    if (Cmd!=NULL && (Cmd->ExclCheck(FD->Name,true,false,false) ||
        Cmd->ExclDirByAttr(FD->FileAttr)))
    {
      // If we are here in "fast find" mode, it means that entire directory
      // specified in command line is excluded. Then we need to return
      // SCAN_DONE to go to next mask and avoid the infinite loop
      // in GetNext() function. Such loop would be possible in case of
      // SCAN_NEXT code and "rar a arc dir -xdir" command.

      return FastFindFile ? SCAN_DONE:SCAN_NEXT;
    }
    
    wchar Mask[NM];

    wcsncpyz(Mask,FastFindFile ? MASKALL:PointToName(CurMask),ASIZE(Mask));
    wcsncpyz(CurMask,FD->Name,ASIZE(CurMask));

    if (wcslen(CurMask)+wcslen(Mask)+1>=NM || Depth>=MAXSCANDEPTH-1)
    {
      uiMsg(UIERROR_PATHTOOLONG,CurMask,SPATHDIVIDER,Mask);
      return SCAN_ERROR;
    }

    AddEndSlash(CurMask,ASIZE(CurMask));
    wcsncatz(CurMask,Mask,ASIZE(CurMask));

    Depth++;

    // We need to use OrigCurMask for depths less than SetAllMaskDepth
    // and "*" for depths equal or larger than SetAllMaskDepth.
    // It is important when "fast finding" directories at Depth > 0.
    // For example, if current directory is RootFolder and we compress
    // the following directories structure:
    //   RootFolder
    //     +--Folder1
    //     |  +--Folder2
    //     |  +--Folder3
    //     +--Folder4
    // with 'rar a -r arcname Folder2' command, rar could add not only
    // Folder1\Folder2 contents, but also Folder1\Folder3 if we were using
    // "*" mask at all levels. We need to use "*" mask inside of Folder2,
    // but return to "Folder2" mask when completing scanning Folder2.
    // We can rewrite SearchAll expression above to avoid fast finding
    // directories at Depth > 0, but then 'rar a -r arcname Folder2'
    // will add the empty Folder2 and do not add its contents.

    if (FastFindFile)
      SetAllMaskDepth=Depth;
  }
  if (!FastFindFile && !CmpName(CurMask,FD->Name,MATCH_NAMES))
    return SCAN_NEXT;

  return SCAN_SUCCESS;
}
Esempio n. 30
0
// For masks like dir1\dir2*\file.ext this function sets 'dir1' recursive mask
// and '*\dir2*\file.ext' filter. Masks without folder wildcards are
// returned as is.
bool ScanTree::GetFilteredMask()
{
  // If we have some matching folders left for non-recursive folder wildcard
  // mask, we return it here.
  if (ExpandedFolderList.ItemsCount()>0 && ExpandedFolderList.GetString(CurMask,ASIZE(CurMask)))
    return true;

  FolderWildcards=false;
  FilterList.Reset();
  if (!FileMasks->GetString(CurMask,ASIZE(CurMask)))
    return false;

  // Check if folder wildcards present.
  bool WildcardFound=false;
  uint FolderWildcardCount=0;
  uint SlashPos=0;
  for (int I=0;CurMask[I]!=0;I++)
  {
    if (CurMask[I]=='?' || CurMask[I]=='*')
      WildcardFound=true;
    if (IsPathDiv(CurMask[I]) || IsDriveDiv(CurMask[I]))
    {
      if (WildcardFound)
      {
        // Calculate a number of folder wildcards in current mask.
        FolderWildcardCount++;
        WildcardFound=false;
      }
      if (FolderWildcardCount==0)
        SlashPos=I; // Slash position before first folder wildcard mask.
    }
  }
  if (FolderWildcardCount==0)
    return true;
  FolderWildcards=true; // Global folder wildcards flag.

  // If we have only one folder wildcard component and -r is missing or -r-
  // is specified, prepare matching folders in non-recursive mode.
  // We assume -r for masks like dir1*\dir2*\file*, because it is complicated
  // to fast find them using OS file find API call.
  if ((Recurse==RECURSE_NONE || Recurse==RECURSE_DISABLE) && FolderWildcardCount==1)
    return ExpandFolderMask();

  wchar Filter[NM];
  // Convert path\dir*\ to *\dir filter to search for 'dir' in all 'path' subfolders.
  wcscpy(Filter,L"*");
  AddEndSlash(Filter,ASIZE(Filter));
  // SlashPos might point or not point to path separator for masks like 'dir*', '\dir*' or 'd:dir*'
  wchar *WildName=IsPathDiv(CurMask[SlashPos]) || IsDriveDiv(CurMask[SlashPos]) ? CurMask+SlashPos+1 : CurMask+SlashPos;
  wcsncatz(Filter,WildName,ASIZE(Filter));

  // Treat dir*\* or dir*\*.* as dir\, so empty 'dir' is also matched
  // by such mask. Skipping empty dir with dir*\*.* confused some users.
  wchar *LastMask=PointToName(Filter);
  if (wcscmp(LastMask,L"*")==0 || wcscmp(LastMask,L"*.*")==0)
    *LastMask=0;

  FilterList.AddString(Filter);

  bool RelativeDrive=IsDriveDiv(CurMask[SlashPos]);
  if (RelativeDrive)
    SlashPos++; // Use "d:" instead of "d" for d:* mask.

  CurMask[SlashPos]=0;

  if (!RelativeDrive) // Keep d: mask as is, not convert to d:\*
  {
    // We need to append "\*" both for -ep1 to work correctly and to
    // convert d:\* masks previously truncated to d: back to original form.
    AddEndSlash(CurMask,ASIZE(CurMask));
    wcsncatz(CurMask,MASKALL,ASIZE(CurMask));
  }
  return true;
}