Read/Write files with UNC path - in c++ - c++

I wrote a bit of code that reads/writes stuff...
I would like to add an option to read/write to UNC paths.
A bit of code:
if (boost::filesystem::exists (file_name))
{
std::ifstream in_file(file_name.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
if(in_file.is_open())
{
in_file.read(...);
in_file.close();
}
}
If the network share I am trying to use has been used before, this works.
But if I try with a share from a computer that I have not seen before, I get error:
boost::filesystem::status: Logon failure: unknown user name or bad password: "\\xx\test.txt"
I'd like to avoid the exception, check the boost::filesystem::status for... what ? Looking in documentation, it seems that it can tell me if I have a regular file, or a directory... but how can I check if I have the correct permissions ?
Is there a way to actually send in the user name and password ?
Edit: found that I could call
Net Use \\yourUNC\path /user:uname password
also:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa375187(v=vs.85).aspx
I think either of these would make the code platform dependent ?
Also, if I do log in every time - in a sequence of 10000 calls, this would result in serious slowing down ?
Is there any way to check if the user is logged in ?
Note: I am using boost 1.47 - mostly windows but I'd like to be platform independent.
Thank you.

The only way I found that I can check rights was to try... catch surrounding a check for file exist call.
If the try fails, it means I don't have rights and can call system("Net Use...")
This way, I only have to log in once even if I read/write 10,000 files...
I don't like the fact that I have to use try... catch, if there is a better way, and I'll find it, I'll update - if anyone knows of a better way, please let me know.

Related

Detect authentication attempts from ssh/console from an application for linux

There is a task to detect successful and unsuccessful login attempts from a linux C++ application.
What is the best way to do it?
I've only found 2 ways:
1) Check /var/logs/secure by timeout
2) Use inotify on /var/logs/secure
But there is an issue, that two or more unsuccessful login attemts in /var/logs/secure look like "PAM 2 more authentication failures" and this string is not appeared in a moment of unsuccessful login.
On a decent system, /var/log/wtmp and /var/log/btmp are a best locations to check. Glibc provide functions to make its access easier: getutxent, getutxid, getutxline, etc...
Also check behaviour of utmpdump -f /var/log/wtmp, it very close of what you want (decode wtmp and follow new events).
None of the above. It's actually much simpler:
1) Open the file
2) call read() in non-blocking mode over and over to read the data.
3) If you get -EWOULDBLOCK, then do a select(). If data is ready to read, go back to step 2.
4) If the select times out (let's say 1 second timeout), check if the file has been rotated. (Simple way: Check the ctime on the new file. But there's probably a better way. Take a look at tail -F sources..) If a new file has been created, call close() and go to 1. Otherwise, go to 3.
Also, take a look at fail2ban.

Identifying a Programming Language

So I have a software program that for reasons that are beyond this post, I will not include but to put it simply, I'd like to "MOD" the original software. The program is launched from a Windows Application named ViaNet.exe with accompanying DLL files such as ViaNetDll.dll. The Application is given an argument such as ./Statup.cat. There is also a WatchDog process that uses the argument ./App.cat instead of the former.
I was able to locate a log file buried in my Windows/Temp folder for the ViaNet.exe Application. Looking at the log it identifies files such as:
./Utility/base32.atc:_Encode32 line 67
./Utilities.atc:MemFun_:Invoke line 347
./Utilities.atc:_ForEachProperty line 380
./Cluster/ClusterManager.atc:ClusterManager:GetClusterUpdates line 1286
./Cluster/ClusterManager.atc:ClusterManager:StopSync line 505
./Cluster/ClusterManager.atc:ConfigSynchronizer:Update line 1824
Going to those file locations reveal files by those names, but not ending with .atc but instead .cat. The log also indicates some sort of Class, Method and Line # but .cat files are in binary form.
Searching the program folder for any files with the extension .atc reveals three -- What I can assume are uncompiled .cat files -- files. Low and behold, once opened it's obviously some sort of source code -- with copyright headers, lol.
global ConfigFolder, WriteConfigFile, App, ReadConfigFile, CreateAssocArray;
local mgrs = null;
local email = CreateAssocArray( null);
local publicConfig = ReadConfigFile( App.configPath + "\\publicConfig.dat" );
if ( publicConfig != null )
{
mgrs = publicConfig.cluster.shared.clusterGroup[1].managers[1];
local emailInfo = publicConfig.cluster.shared.emailServer;
if (emailInfo != null)
{
if (emailInfo.serverName != "")
{
email.serverName = emailInfo.serverName;
}
if (emailInfo.serverEmailAddress != "")
{
email.serverEmailAddress = emailInfo.serverEmailAddress;
}
if (emailInfo.adminEmailAddress != null)
{
email.adminEmailAddress = emailInfo.adminEmailAddress;
}
}
}
if (mgrs != null)
{
WriteConfigFile( ConfigFolder + "ZoneInfo.dat", mgrs);
}
WriteConfigFile( ConfigFolder + "EmailInfo.dat", email);
So to end this as simply as possible, I'm trying to find out two things. #1 What Programming Language is this? and #2 Can the .cat be decompiled back to .atc. files? -- and vice versa. Looking at the log it would appear that the Application is decoding/decompiling the .cat files already to interpret them verses running them as bytecode/natively. Searching for .atc on Google results in AutoCAD. But looking at the results, shows it to be some sort of palette files, nothing source code related.
It would seem to me that if I can program in this unknown language, let alone, decompile the existing stuff, I might get lucky with modding the software. Thanks in advance for any help and I really really hope someone has an answer for me.
EDIT
So huge news people, I've made quite an interesting discovery. I downloaded a patch from the vendor, it contained a batch file that was executing ViaNet.exe Execute [Patch Script].atc. I quickly discovered that you can use Execute to run both .atc and .cat files equally, same as with no argument. Once knowing this I assumed that there must be various arguments you can try, well after a random stroke of luck, there is one. That being Compile [Script].atc. This argument will compile also any .atc file to .cat. I've compiled the above script for comparison: http://pastebin.com/rg2YM8Q9
So I guess the goal now is to determine if it's possible to decompile said script. So I took a step further and was successful at obtaining C++ pseudo code from the ViaNet.exe and ViaNetDll.dll binaries, this has shed tons of understanding on the proprietary language and it's API they use. From what I can tell each execution is decompiled first then ran thru the interpreter. They also have nicknamed their language ATCL, still no idea what it stands for. While searching the API, I found several debug methods with names like ExecuteFile, ExecuteString, CompileFile, CompileString, InspectFunction and finally DumpObjCode. With the DumpObjCode method I'm able to perform some sort of dump of script files. Dump file for above script: http://pastebin.com/PuCCVMPf
I hope someone can help me find a pattern with the progress I made. I'm trying my best to go over the pseudo code but I don't know C++, so I'm having a really hard time understanding the code. I've tried to seperate what I can identify as being the compile script subroutines but I'm not certain: http://pastebin.com/pwfFCDQa
If someone can give me an idea of what this code snippet is doing and if it looks like I'm on the right path, I'd appreciate it. Thank you in advanced.

Diagnosing QDir::rmdir failure

I’m using the following code to delete an empty folder on Linux:
bool removeFolder (const QString& path)
{
QDir dir(path);
assert(dir.exists());
return dir.rmdir(".");
}
For some reason it sometimes returns false (for specific folders, but those folders don’t seem to be wrong in any way). If I subsequently use ::rmdir from <unistd.h> to remove the same folder, it succeeds.
How can I tell why QDir::rmdir is failing?
This never happened on Windows so far, QDir::rmdir just works.
Confirming: works on windown, fails on linux.
Reading the "rmdir" doc in <unistd>, here https://pubs.opengroup.org/onlinepubs/007904875/functions/rmdir.html, it says there that "If the path argument refers to a path whose final component is either dot or dot-dot, rmdir() shall fail." So what's probably happening is that QDir::rmdir() is calling the unistd rmdir() function in linux, and this one fails with ".".
I tried to just use the full absolute path ( QDir::rmdir(absolutePath) ) and it worked; however, i see basically no point in using QDir::rmdir() over unistd's rmdir(), so i''ll stick w/ the unistd rmdir() from now on.
note: QDir::removeRecursively() is a different story: it seems to work okay, and it's way more convenient than going through opendir() and then successive readdir()'s (or the nftw(...FTW_DEPTH...) thingie).
I had the same problem but on Windows, I could not delete an empty directory with QDir().rmdir(path);. This happened on some older hard drive so may be the ancient file system was to blame. But I found a hack:
QFile(path).setPermissions(QFile::WriteOther); // this works even for dirs
bool success = QDir().rmdir(path);
Of course, you should revert the permissions back to original values if the deletion was unsuccessful anyway, but that's a different story.
Try to use this one:
dir.rmdir(dir.absolutePath())

Why are my files smaller after I FTP them using this Python program?

I'm trying to send some files (a zip and a Word doc) to a directory on a server using ftplib. I have the broad strokes sorted out:
session = ftplib.FTP(ftp.server, 'user','pass')
filewpt = open(file, mode)
readfile = open(file, mode)
session.cwd(new/work/directory)
session.storbinary('STOR filename.zip', filewpt)
session.storbinary('STOR readme.doc', readfile)
print "filename.zip and readme.doc were sent to the folder on ftp"
readfile.close()
filewpt.close()
session.quit()
This may provide someone else what they are after but not me. I have been using FileZilla as a check to make sure the files were transferred. When I see they have made it to the server, I see that they are both way smaller or even zero K for the readme.doc file. Now I'm guessing this has something to do with the fact that I stored the file in 'binary transfer mode' <--- whatever that means.
This is where my problems lie. I have no idea at all (yet) what is meant by binary transfer mode. Is it simply that I have to use retrbinary to return the files to their original state?
Could someone please explain to me like I'm a two year old what has happened to my files? If there's any more info required, please let me know.
This is a fantastic resource. Solved most of my problems. Still trying to work out the intricacies of FTPs, but I guess I will save that for another day. The link below builds a function to effortlessly upload files to an FTP without the partial upload problem that I've seen experienced by more than one Stack Exchanger.
http://effbot.org/librarybook/ftplib.htm

Win32 C/C++ checking if two instances of the same program use the same arguments

I have an application and I want to be able to check if (for instance) two instances of it used the same arguments on execution. To make it clearer:
myapp 1 2
myapp 1 3
This isn't a Singleton design pattern problem as I can have more than one instance running. I though about checking the running processes, but it seems that I can only get the process name and that doesn't help me.
Writing a file on startup and then having other instances check if that file exists isn't viable due to abnormal program termination which would leave me hanging.
In Linux I solved this by checking /proc/pid/cmdline and parsing the information there.
Does anyone have any idea if I can do something similar on windows?
Cheers
You can do this via WMI's Win32_Process class.
You want wmic.exe. Try something like:
wmic.exe process list | findstr myapp.exe
Then sort it / parse it / whatever you need to do.
wmic is really a great tool to have.
I ended up using this script instead of filling up my code with WMI calls:
wmic process where "name='cmd.exe'" get CommandLine > list.txt
works great!
cheers and thanks you Seth and Reed
After some thinking I decided to do things a bit simpler...
Implementing a mutex and checking it's existence is. As I needed to check if the instances started with the same parameters and not if the same application was started, I just needed to decide on the mutex name in runtime!
so...
sprintf(cmdstr,"myapp_%i_%i",arg1,arg2);
DWORD m_dwLastError;
m_hMutex = CreateMutex(NULL, FALSE, cmdstr);
m_dwLastError = GetLastError();
if(ERROR_ALREADY_EXISTS == m_dwLastError)
{
found_other = true;
}
and that's it! no parsing, no wmi, no windows development sdk...
Cheers to you all!