How does _stat() under Windows exactly work - c++

In my code I try to get the permissions for a file with _stat(). Currently I want to run it under Windows. The method is as follows:
bool CFile::Private::checkPermissions(std::string sFilename, CFile::EOpenmode iOpenmode)
{
std::string sErrMsg = "";
bool bResult = true;
struct _stat buf;
int iResult = 0;
// Get data associated with "crt_stat.c":
iResult = _stat( sFilename.c_str(), &buf );
// Check if statistics are valid:
if( iResult != 0 )
{
switch (errno)
{
case ENOENT:
sErrMsg = "File: " + sFilename + " not found.";
break;
case EINVAL:
sErrMsg = "Invalid parameter to _stat(filename, &buf).";
break;
default:
/* Should never be reached. */
sErrMsg = "Unexpected error in _stat(filename, &buf).";
}
throw std::runtime_error(sErrMsg);
}
else
{
if((iOpenmode & CFile::Read) && (!(buf.st_mode & S_IREAD)))
{
bResult = false;
}
if((iOpenmode & CFile::Write) && (!(buf.st_mode & S_IWRITE)))
{
bResult = false;
}
}
return bResult;
}
The only way to get 'false' for permission is to set the file's attribute 'read only'. Instead of this, set the security properties of the user (reject writing and reading) will get 'true' for checkPermissions(...). How to check both, the attributes and the user permissions for Windows?
Rumo

_stat is a function that is not native to Windows. It's a helper function to ease the porting of UNIX programs to Windows. But the UNIX file model just doesn't apply to Windows, so not all fields make sense. For instance, Windows has real ACL's, not rwx bits. There's just no way to fit all the ACL information in st_mode.
If you want to test ACL permissions, the proper way is to just try: call CreateFile() and check GetLastError(). Trying to get file permissions up front is not reliable as they can change at any time.

If we're talking about the same _stat() it's pretty clear from this MSDN article exactly what it does. Basically, you supply it a path to a file in question and a pointer to a _stat struct and it will dump the permissions to the struct if it returns 0.
The example C++ code in the article is pretty good.
As for testing user permissions, IsUserAnAdmin() does the job pretty well. You may be able to use this MSDN article for a different approach.
I hope this helps!

Related

Windows: Check existence of named pipe

I am writing a C++ program that makes use of named pipes on Windows. I can create and work with them quite fine. The only piece missing to the puzzle is a function to check for a pipe's existence.
Coming from the Unix world I originally tried std::filesystem::exists("\\\\.\\pipe\\myPipe") but this is not reliable and often errors with ERROR_PIPE_BUSY.
While searching for an alternative way to check for a pipe's existence, I stumbled upon this issue on GitHub (Boost process) and from there I take it that Boos process circumvents the problem by using a special naming scheme and a counter and then keeping track of that internally (only seems to work for pipes created via Boost process though).
Furthermore according to How can I get a list of all open named pipes in Windows? it seems that there are ways to list the existing named pipes. These solutions are not using C++ though and I did not find a way to port that over.
After having read the documentation of CreateNamedPipe, I now assembled the following solution to my problem:
bool NamedPipe::exists(const std::filesystem::path &pipePath) {
if (pipePath.parent_path() != "\\\\.\\pipe") {
// This can't be a pipe, so it also can't exist
return false;
}
// Attempt to create a pipe with FILE_FLAG_FIRST_INSTANCE so that the creation will fail
// if the pipe already exists
HANDLE pipeHandle = CreateNamedPipe(pipePath.string().c_str(),
PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_WAIT,
1, // # of allowed pipe instances
0, // Size of outbound buffer
0, // Size of inbound buffer
0, // Use default wait time
NULL // Use default security attributes
);
if (pipeHandle == INVALID_HANDLE_VALUE) {
// Creation has failed
// It has failed (most likely) due to there alredy existing a pipe with
// that name
return true;
} else {
// The creation has succeeded
if(!CloseHandle(pipeHandle)) {
throw PipeException< DWORD >(GetLastError(), "CheckExistance");
}
return false;
}
}
However attempting to create a named pipe only to check whether there already exists one with that name already seems like a lot of unnecessary overhead. Furthermore I am unsure of whether this solution is universally applicable or only works if the pipe tested for was also created with FILE_FLAG_FIRST_PIPE_INSTANCE.
Therefore my question is: Is there a better way to check whether a named pipe with the given name already exists in Windows?
std::filesystem::exists("\\\\.\\pipe\\myPipe") returning ERROR_PIPE_BUSY means it is using CreateFile() to actually connect to the pipe. It is not unreasonable for an exists() implementation to attempt to open the requested file to check its existance.
Per the CreateFile() documentation:
If there is at least one active pipe instance but there are no available listener pipes on the server, which means all pipe instances are currently connected, CreateFile fails with ERROR_PIPE_BUSY.
Which means the pipe does technically exist, it is not ready to receive a new client at that moment.
In the link you provided, many of the solutions provided suggest using .NET's System.IO.Directory.GetFiles() method to iterate though the contents of "\\.\pipe\". This answer shows how that call translates into Win32 API calls using FindFirstFile() and FindNextFile(). You can easily do the same API calls in C++, eg:
bool NamedPipe::exists(const std::filesystem::path &pipePath)
{
std::string pipeName = pipePath.string();
if ((pipeName.size() < 10) ||
(pipeName.compare(0, 9, "\\\\.\\pipe\\") != 0) ||
(pipeName.find('\\', 9) != std::string::npos))
{
// This can't be a pipe, so it also can't exist
return false;
}
pipeName.erase(0, 9);
WIN32_FIND_DATA fd;
DWORD dwErrCode;
HANDLE hFind = FindFirstFileA("\\\\.\\pipe\\*", &fd);
if (hFind == INVALID_HANDLE_VALUE)
{
dwErrCode = GetLastError();
}
else
{
do
{
if (pipeName == fd.cFileName)
{
FindClose(hFind);
return true;
}
}
while (FindNextFileA(hFind, &fd));
dwErrCode = GetLastError();
FindClose(hFind);
}
if ((dwErrCode != ERROR_FILE_NOT_FOUND) &&
(dwErrCode != ERROR_NO_MORE_FILES))
{
throw PipeException< DWORD >(dwErrCode, "CheckExistance");
}
return false;
}
UPDATE: or, using std::wstring with Unicode APIs instead, since the filesystem is natively Unicode on Windows:
bool NamedPipe::exists(const std::filesystem::path &pipePath)
{
std::wstring pipeName = pipePath;
if ((pipeName.size() < 10) ||
(pipeName.compare(0, 9, L"\\\\.\\pipe\\") != 0) ||
(pipeName.find(L'\\', 9) != std::string::npos))
{
// This can't be a pipe, so it also can't exist
return false;
}
pipeName.erase(0, 9);
WIN32_FIND_DATAW fd;
DWORD dwErrCode;
HANDLE hFind = FindFirstFileW(L"\\\\.\\pipe\\*", &fd);
if (hFind == INVALID_HANDLE_VALUE)
{
dwErrCode = GetLastError();
}
else
{
do
{
if (pipeName == fd.cFileName)
{
FindClose(hFind);
return true;
}
}
while (FindNextFileW(hFind, &fd));
dwErrCode = GetLastError();
FindClose(hFind);
}
if ((dwErrCode != ERROR_FILE_NOT_FOUND) &&
(dwErrCode != ERROR_NO_MORE_FILES))
{
throw PipeException< DWORD >(dwErrCode, "CheckExistance");
}
return false;
}

electron: ui and backend processes accessing the same log file on Windows

Goal
My electron-based app uses a C++ backend, which keeps a log file. I'd love to show the file content on a page of my Electron frontend.
The macOS version works as expected. I simply use node.js fs and readline libraries and to read the file on the fly, and then insert the parsed text into innerHTML.
Problem
However, on Windows, the log file seems to be locked by the backend while the CRT fopen calls use appending mode "a". So node.js keeps getting exception
EBUSY: resource busy or locked open '/path/to/my.log'
To make it worse, I use a thirdparty lib for logging and it's internal is not that easy to hack.
Code
Here is the Electron-side of code
function OnLoad() {
let logFile = Path.join(__dirname, 'logs', platformDirs[process.platform], 'my.log');
let logElem = document.querySelector('.log');
processLineByLine(logFile, logElem);
}
//
// helpers
//
async function processLineByLine(txtFile, outElement) {
const fileStream = fs.createReadStream(txtFile);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
outElement.innerHTML += line + '<br>';
}
}
Here is the backend side of code
inline bool OpenLogFile(FILE** ppLogFile) {
TCHAR logPath[MAX_PATH];
DWORD length = GetModuleFileName(NULL, logPath, MAX_PATH);
bool isPathValid = false;
#if (NTDDI_VERSION >= NTDDI_WIN8)
PathCchRemoveFileSpec(logPath, MAX_PATH);
HRESULT resPath = PathCchCombine(logPath, MAX_PATH, logPath, TEXT("my.log"));
isPathValid = (resPath == S_OK);
#else
PathRemoveFileSpec(logPath);
LPWSTR resPath = PathCombine(logPath, logPath, TEXT("my.log"));
isPathValid = (resPath != NULL)
#endif
if (!isPathValid)
return false;
errno_t res = _wfopen_s(ppLogFile, logPath, L"a");
if (res != 0) {
wprintf(TEXT("Error: Failed to open log file: %s"), GetOSErrStr().c_str());
}
return res == 0;
}
Question
Is this an inherent problem with my architecture?
Should I forget about accessing the log file from frontend/backend processes at the same time?
I thought about using a message queue for sharing logs between the frontend and backend processes, but that'd make logging more complex and bug prone.
Is there an easy way to have the same logging experience as with macOS?
Solved it myself.
I must use another Win32 API _wfsopen that provides more sharing options.
In my case, the following change is sufficient
*ppLogFile = _wfsopen(logPath, L"a+", _SH_DENYWR);
This answer helped.

What is the preferred way to get a device path for CreateFile() in a UWP C++ App?

I am converting a project to a UWP App, and thus have been following guidelines outlined in the MSDN post here. The existing project heavily relies on CreateFile() to communicate with connected devices.
There are many posts in SO that show us how to get a CreateFile()-accepted device path using SetupAPI's SetupDiGetDeviceInterfaceDetail() Is there an alternative way to do this using the PnP Configuration Manager API? Or an alternative, user-mode way at all?
I had some hope when I saw this example in Windows Driver Samples github, but quickly became dismayed when I saw that the function they used in the sample is ironically not intended for developer use, as noted in this MSDN page.
function GetDevicePath in general correct and can be used as is. about difference between CM_*(..) and CM_*_Ex(.., HMACHINE hMachine) - the CM_*(..) simply call CM_*_Ex(.., NULL) - so for local computer versions with and without _Ex suffix the same.
about concrete GetDevicePath code - call CM_Get_Device_Interface_List_Size and than CM_Get_Device_Interface_List only once not 100% correct - because between this two calls new device with this interface can be arrived to system and buffer size returned by CM_Get_Device_Interface_List_Size can be already not enough for CM_Get_Device_Interface_List. of course possibility of this very low, and you can ignore this. but i prefer make code maximum theoretical correct and call this in loop, until we not receive error other than CR_BUFFER_SMALL. also need understand that CM_Get_Device_Interface_List return multiple, NULL-terminated Unicode strings - so we need iterate here. in [example] always used only first returned symbolic link name of an interface instance. but it can be more than 1 or at all - 0 (empty). so better name function - GetDevicePaths - note s at the end. i be use code like this:
ULONG GetDevicePaths(LPGUID InterfaceClassGuid, PWSTR* pbuf)
{
CONFIGRET err;
ULONG len = 1024;//first try with some reasonable buffer size, without call *_List_SizeW
for(PWSTR buf;;)
{
if (!(buf = (PWSTR)LocalAlloc(0, len * sizeof(WCHAR))))
{
return ERROR_NO_SYSTEM_RESOURCES;
}
switch (err = CM_Get_Device_Interface_ListW(InterfaceClassGuid, 0, buf, len, CM_GET_DEVICE_INTERFACE_LIST_PRESENT))
{
case CR_BUFFER_SMALL:
err = CM_Get_Device_Interface_List_SizeW(&len, InterfaceClassGuid, 0, CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
default:
LocalFree(buf);
if (err)
{
return CM_MapCrToWin32Err(err, ERROR_UNIDENTIFIED_ERROR);
}
continue;
case CR_SUCCESS:
*pbuf = buf;
return NOERROR;
}
}
}
and usage example:
void example()
{
PWSTR buf, sz;
if (NOERROR == GetDevicePaths((GUID*)&GUID_DEVINTERFACE_VOLUME, &buf))
{
sz = buf;
while (*sz)
{
DbgPrint("%S\n", sz);
HANDLE hFile = CreateFile(sz, FILE_GENERIC_READ, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, 0, 0);
if (hFile != INVALID_HANDLE_VALUE)
{
// do something
CloseHandle(hFile);
}
sz += 1 + wcslen(sz);
}
LocalFree(buf);
}
}
so we must not simply use in returned DevicePathS (sz) only first string, but iterate it
while (*sz)
{
// use sz
sz += 1 + wcslen(sz);
}
I got a valid Device Path to a USB Hub Device, and used it successfully to get various device descriptors by sending some IOCTLs, by using the function I posted in my own answer to another question
I'm reporting the same function below:
This function returns a list of NULL-terminated Device Paths (that's what we get from CM_Get_Device_Interface_List())
You need to pass it the DEVINST, and the wanted interface GUID.
Since both the DEVINST and interface GUID are specified, it is highly likely that CM_Get_Device_Interface_List() will return a single Device Path for that interface, but technically you should be prepared to get more than one result.
It is responsibility of the caller to delete[] the returned list if the function returns successfully (return code 0)
int GetDevInstInterfaces(DEVINST dev, LPGUID interfaceGUID, wchar_t**outIfaces, ULONG* outIfacesLen)
{
CONFIGRET cres;
if (!outIfaces)
return -1;
if (!outIfacesLen)
return -2;
// Get System Device ID
WCHAR sysDeviceID[256];
cres = CM_Get_Device_ID(dev, sysDeviceID, sizeof(sysDeviceID) / sizeof(sysDeviceID[0]), 0);
if (cres != CR_SUCCESS)
return -11;
// Get list size
ULONG ifaceListSize = 0;
cres = CM_Get_Device_Interface_List_Size(&ifaceListSize, interfaceGUID, sysDeviceID, CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
if (cres != CR_SUCCESS)
return -12;
// Allocate memory for the list
wchar_t* ifaceList = new wchar_t[ifaceListSize];
// Populate the list
cres = CM_Get_Device_Interface_List(interfaceGUID, sysDeviceID, ifaceList, ifaceListSize, CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
if (cres != CR_SUCCESS) {
delete[] ifaceList;
return -13;
}
// Return list
*outIfaces = ifaceList;
*outIfacesLen = ifaceListSize;
return 0;
}
Please note that, as RbMm already said in his answer, you may get a CR_BUFFER_SMALL error from the last CM_Get_Device_Interface_List() call, since the device list may have been changed in the time between the CM_Get_Device_Interface_List_Size() and CM_Get_Device_Interface_List() calls.

How come GetDefaultCommConfig fails on windows 10

I use the following code to verify that a serial port name is valid on the computer:
typedef std::pair<StrAsc const, bool> port_pair_type;
typedef std::list<port_pair_type> port_pairs_type;
port_pairs_type pairs;
StrBin config_buffer;
config_buffer.fill(0,sizeof(COMMCONFIG));
while(!pairs.empty())
{
port_pair_type pair(pairs.front());
pairs.pop_front();
if(!pair.second)
{
// we need to get the default configuration for the port. This may
// require some fudging on the buffer size. That is why two calls
// are being made.
uint4 config_size = config_buffer.length();
StrUni temp(pair.first);
COMMCONFIG *config(reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable()));
config->dwSize = sizeof(COMMCONFIG);
rcd = GetDefaultCommConfigW(
temp.c_str(), config, &config_size);
if(!rcd && config_buffer.length() < config_size)
{
config_buffer.fill(0, config_size);
config = reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable());
config->dwSize = sizeof(COMMCONFIG);
rcd = GetDefaultCommConfigW(
temp.c_str(),
reinterpret_cast<COMMCONFIG *>(config_buffer.getContents_writable()),
&config_size);
}
// if the call succeeded, we can go ahead and look at the
// configuration structure.
if(rcd)
{
COMMCONFIG const *config = reinterpret_cast<COMMCONFIG const *>(
config_buffer.getContents());
if(config->dwProviderSubType == PST_RS232)
port_names.push_back(pair.first);
}
else
{
OsException error("GetDefaultCommConfig Failed");
trace("\"%s\"", error.what());
}
}
else
port_names.push_back(pair.first);
}
On windows 10, when trying to confirm a serial port that uses usbser.sys, the call to GetDefaultCommConfig() is failing and the error code returned by GetLastError() is 87 (invalid parameter). As I am aware, the usbser.sys driver has been rewritten on windows 10 and I suspect that this is a problem with that driver. Does anyone else have an idea of what might be going wrong?
This had been a bug in usbser.sys and was fixed with the Windows 10 Update KB3124262 from 27.01.2016.
The Microsoft employee explained:
The COM port name in the HKLM\HARDWARE\DEVICEMAP\SERIALCOMM registry is not NULL terminated.
Related discussion on MSDN
Because of Windows 10's update policies this issue should not appear in the future anymore.
When you call GetDefaultCommConfigW the second time you probably need to config->dwSize to the new size the structure. Eg:
config->dwSize = config_size;

Why WNetAddConnection2 still returns 1219 after successfully calling WNetCancelConnection2?

I wrote some code to connect with some share on a remote server. If WNetAddConnection2 returns ERROR_SESSION_CREDENTIAL_CONFLICT (1219), I will first cancel the connection by WNetCancelConnection2 (return NO_ERROR). And then reconnect. But WNetAddConnection2 still returns 1219.
Why this and how to fix it?
Here's my code
BOOL ADDirectorySearch::IPCConnect(CString strServerName, CString strDomainName, CString strUserName, CString strPassWord)
{
CString strServerNameWithSlash = _T("\\\\") + strServerName; //actually is \\klbnt
CString strFullUserName = strDomainName + _T("\\") + strUserName; //is domaintest\administrator
_bstr_t bstrServerNameWithSlash = strServerNameWithSlash;
_bstr_t bstrFullUserName = strFullUserName;
_bstr_t bstrPassWord = strPassWord;
DWORD dwResult;
NETRESOURCEW netResource;
memset(&netResource, 0, sizeof(netResource));
netResource.dwScope = RESOURCE_GLOBALNET;
netResource.dwType = RESOURCETYPE_DISK;
netResource.dwDisplayType = RESOURCEDISPLAYTYPE_GENERIC;
netResource.dwUsage = RESOURCEUSAGE_CONNECTABLE;
netResource.lpProvider = L"";
netResource.lpRemoteName = bstrServerNameWithSlash;//Remote IP like:\\192.168.1.11
dwResult = WNetAddConnection2W(&netResource, bstrPassWord, bstrFullUserName, CONNECT_INTERACTIVE);
if (dwResult == ERROR_SESSION_CREDENTIAL_CONFLICT)
{
dwResult = WNetCancelConnection2W(bstrServerNameWithSlash, CONNECT_UPDATE_PROFILE, TRUE);
if (dwResult == NO_ERROR)
{
dwResult = WNetAddConnection2W(&netResource, bstrPassWord, bstrFullUserName, CONNECT_INTERACTIVE);
}
else
{
//MyMessageBox_Error(_T("IPCConnect Error."), _T("Error"));
return FALSE;
}
}
if (dwResult == NO_ERROR)
{
return TRUE;
}
else
{
//MyMessageBox_Error(_T("IPCConnect Error."), _T("Error"));
return FALSE;
}
}
FYI: After typing "net use" in cmd, I got this, I feel there's something with error:
Status Local Remote Network
-------------------------------------------------------------------------------
OK \\klbnt\NRDC1001 Microsoft Windows Network
The command completed successfully.
I was just having this problem now, and basically it seemed that it was due to another process still having file open, even though I specified "true" as the last parameter of WNetCancelConnection2() to force close the connection. Once I shut-down that other process, I was able to use successfully switch between credentials connecting and re-connecting to the same share. This is on Windows 2012 (64-bit), and the share was local (referenced by the machinename).
BUT...it's still a problem if you want to connect to different shares on the same machine. If I try to connect to \\mymachine\share1 as user1 then to \\mymachine\share2 as user2, I get the 1219 error (even if it's in a completely different process). I have to explicitly call WNetCancelConnnection on \\mymachine\share1 before I can connect to share2, which means at the point you connect to a share on a particular machine, you may have to first enumerate existing connections and close each one.
Rather frustrating, and I can't understand the design principle here. It seems the flags to create temporary connections etc. have no effect on this behaviour either. Really what I want to be able to do is say "for this thread, connect to this share on this machine and as this user, such that all attempts to access files on the share are done with that user's credentials". That way what other processes/threads are doing can't cause issues with the current one.