Why does system() complain that cwd is not known? - c++

I am using system() to run some Unix commands from my application with code like the following:
std::stringstream command;
command << "rm -rf /some/directory";
int rmResult = system(command.str().c_str());
if (rmResult != 0) {
clog << "Error: Failed to remove old output directory '" << command.str()
<< "' (" << errno << ") " << strerror(errno) << ".\n";
throw;
}
However, while rmResult is zero and the rm works, I get this error in the console:
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
What am I doing wrong, and how can I get this message to go away?

Apparently, this was due to having a directory that is now gone on my pushd stack, even though it was not the current working directory. Cleaning out my stack of the now gone directory, caused the messages to go away.

Related

writing a c++ linux program that should run as root

i am trying to write a linux program that uses the c++ mount function (code below),
however, the mount operation requires permmissions, and running the program throws the errno 'Operation not permitted' (printed using perror)
tried some SO solutions but non was helpful, the alternative is to use the system("sudo mount..") but i prefer the c++ function.
is ther a way to use this function with permmissions?
IDE: Clion 2020.2.4
relevant code below
int returnValue = mount(sourcePath,targetPath,"", MS_SHARED, ""); //mounting the device
if (returnValue==0){
//mount completed
//somecode
}else{
//mount failed
std::cout<<"mount failed\n";
perror("");
}
output
mount failed
Operation not permitted
After you compile the code, change the ownership of the file to the superuser with chown root filename and add "set user or group ID on execution" to the mode of the executable file with chmod u+s filename.
Some options I see:
Just run the binary as root or under sudo;
Use setcap cap_sys_admin+ep on your binary to grant it the CAP_SYS_ADMIN capability;
If the set of possible targetPaths is fixed, edit /etc/fstab to give these paths the userflag.
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[]){
std::ifstream tmpfile;
std::string tmpfile_name = ".mytempfile.tmp";
std::string command = "groups>";
std::string searchv[] = {"disk", "sudo", "root"};
int searchc = sizeof(searchv)/sizeof(searchv[0]);
int search_matches = 0;
char data_buffer[128];
if(!system(NULL)) goto ERROR;
command += tmpfile_name;
if(system(command.c_str()) != 0) goto ERROR;
std::cout << "executed external command: \"" << command << "\"" << std::endl;
tmpfile.open(tmpfile_name, std::ios::in);
if(!tmpfile.is_open()) goto ERROR;
std::cout << tmpfile_name << " opened" << std::endl;
do{
tmpfile >> data_buffer;
if(tmpfile.eof()) break;
if(tmpfile.fail()) goto ERROR;
for(int i = 0; i < searchc; i++){
if(!searchv[i].compare(data_buffer)){
search_matches++;
std::cout << "found group " << searchv[i] << std::endl;
}
}
}
while(tmpfile.good());
tmpfile.close();
std::cout << "found " << search_matches << " groups" << std::endl;
return EXIT_SUCCESS;
ERROR:
std::cerr << "something bad happened" << std::endl;
return EXIT_FAILURE;
}
This answer may be off-topic, sorry for that.
This program calls the external Linux program "groups" and searches for keywords "disk", "sudo", "root", which indicating user access rights for mounting a disk.
accessing an os function implies complying with that os's security model.
so short answer, no. you can't override security models in your user-run code

GetPrivateProfileStringA is returning "The system cannot find the file specified." eventhough the file exists

in CPP Visual studio 2010. I need to read some configurations from ini file. the below code is not working. can someone help me fix it.
char * path = "C:\\NotBackedUp\\Workspaces\\LDAP-DLL\\LDAPTestApp\\bin\\Debug\\conf\\ldap.ini";
std::wcout << "path: " << path << std::endl;
if(!ATLPath::FileExists(path))
{
HRESULT hr = ATL::AtlHresultFromLastError();
ATLTRACE("%x\n",hr);//system could not find the file specified!
std::cout << "File not found " << std::endl;
return 0;
}
else
{
std::cout << "File found " << std::endl;
}
char valueRead[320];
int a = GetPrivateProfileStringA("ldap", "url", "error", valueRead, 320, path);
std::cout << "Value Read " << valueRead << std::endl;
std::cout << "Error String " << GetLastErrorAsString();
the above code is generating below log, you can see ATLPath::FileExists is returning true, but still getLastError is stating the System cannot find the file specified
path: C:\NotBackedUp\Workspaces\LDAP-DLL\LDAPTestApp\bin\Debug\conf\ldap.ini
File found
Value Read error
Error String The system cannot find the file specified.
My ldap.ini file has following lines and is available in the above path
[ldap]
url=ldap://testserver
any help is highly appreciated
thanks
The ERROR_FILE_NOT_FOUND error code you’re getting is also set when GetPrivateProfileString is unable to find a section or value.
Your code works fine on my Win10 with your ini file.
Use a hex viewer/editor to verify your ldap.ini is actually ASCII, and that it doesn't contain BOM.

Double Clicked Compiled C++ Unix Executable Doesn't Open Existing File to Read Information From

I've been searching online to solve the above issue with no
success so far. I will describe the issue in more details below.
My program contains only one .cpp file. The program should display text from "test.txt" if this file is opened. Otherwise, it should display the "Failed to open ..." message. The issue follows:
I open terminal, go to the directory containing my file, compile and run with the usual commands: "g++ main.cpp" and "./a.out". When I run my program in this way, using terminal directly, the program works correctly. It displays text when the text file exists and outputs error when it doesn't exist. When I double click the unix executable "a.out", even though the text file exists and is put side by side with the executable, the program displays "Failed to open ..." message. I don't know what to think at that point. Should code contain anything else besides what is below?
Operating system: OS X 10.9.5
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_CHAR_READ = 100;
int main(int argc, const char * argv[])
{
ifstream read_file;
cout << endl << endl;
//Allocate dynamic memory
char * file = new char[strlen("test.txt") + 1];
char * text_line = new char[MAX_CHAR_READ + 1];
strcpy(file, "test.txt");
//Attempt to open a file for reading
read_file.open(file);
if(read_file.is_open() == true)
{
cout << "File: " << file << " is open!" << endl;
read_file.get(text_line, MAX_CHAR_READ, ';');
cout << text_line << endl;
read_file.close();
}
else
cout << "Failed to open: " << file << endl;
cout << endl << endl;
//Deallocate dynamic memory
delete [] file;
delete [] text_line;
return 0;
}
Program execution example using terminal manually:
$ cd Desktop/Other/Test
$ g++ main.cpp
$ ./a.out
File: test.txt is open!
Hello World!
$
Program execution example double clicking the same executable:
$/Users/vladimirmeshcheryakov/Desktop/Other/Test/a.out ; exit;
Failed to open: test.txt
logout
[Process completed]
one of the possible things to cause it could be the case of running the terminal as superuser, in a folder with access restriction to the regular user. (superuser doesn't have that restriction)
solution: give current user the right to Read/Write in this folder.
Now I need to find a solution of obtaining the path to executable.
Check whether argv[0] contains it.

Execute the script owned by root from C++ code

I am trying to run a script from my c++ code owned by root.
But it throws me an error permission denied to run the script.
Permissions on files are as follows:
-rwx------ 1 root mygame 39 Dec 24 19:11 script.sh
-rwsr-xr-x 1 gag5kor mygame 7999 Dec 26 12:23 a.out
C++ code:
int err = system("./script.sh");
cout << "Before err: " << err << endl;
cout << "setuid: " << seteuid(0) << endl;
err = system("./script.sh");
cout << "After err: " << err << endl;
getuid() and geteuid() function returns me same value (say 1234) even after I call setuid(0) to get the root permissions.
What I am doing wrong here?
I read the other answers on stackoverflow but not able to understand properly.
chmod 0555 script.sh should fix this
EDIT
chown root script.sh
chmod 0500 script.sh
Should fulfill your requirements

Error opening existing directory using opendir in c++

I am making use of opendir() as below to access a directory.
DIR *dp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
However, I keep getting the error below, even though the directory exists.
Error(2) opening /path/to/folder/
I am able to get a list of file names when I do ls /path/to/folder
Be aware that /path/to/folder is different from /path/to/folder/
errno value 2 means ENOENT (it's an abbreviaton for Error NO ENTry) that is "Directory does not exist, or name is an empty string".
How do you define dir in your code?
std::string dir = "/path/to/folder/";
DIR* dp = opendir(dir.c_str());
if (dp == NULL)
{
std::cout << "Error(" << errno << ") opening " << dir << std::endl;
perror("opendir");
return errno;
}
closedir(dp);
Update #1:
Try to call you shell script:
main.sh folder/ foldername
Where main.sh contains:
#!/bin/sh
path="$1$2"
echo "$path"
ls -l "$path"