Solved

How to  Cross-verify path ....using  C ++ function

Posted on 2004-04-07
10
247 Views
Last Modified: 2012-05-04
Hi

I have this question w r t C++......

I have set a particular directory for my executables........
say C:\Ruff\exec

My requirement is that when a user ie UNIX based is in a particular path and wants to execute one of my exe's ...... i need the system to corss-verify whether the user is in the same path as that defined by me...............

How do i do this in C++. are there any C++ functions for doing this ....P S : its a unix based environment where im deploying the C++ Code....



Thank You

In Advance

RonCOde
0
Comment
Question by:RonCode
  • 3
  • 2
  • 2
10 Comments
 
LVL 12

Expert Comment

by:stefan73
ID: 10773242
Hi RonCode,
You can use the getcwd() function:

#include <unistd.h>
#include <stdio.h>

main(){
    char dirbuf[1024];

    if(getcwd(dirbuf,sizeof(dirbuf))){
        printf("Your current directory is: %s\n",dirbuf);

}

The prototype is:
extern char *getcwd(char *buf, size_t size);


Cheers,
Stefan
0
 

Author Comment

by:RonCode
ID: 10775381
Hi

I would like to cross verify the current working directory with the path i have set

How do i????
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10775496
RonCode,
Just to understand you fully - you want to check if the current directory is part of $PATH?
Or do you want to add the current directory to $PATH?

Or is it that you want to check that the user called exactly the binary stored in a particular path?

Stefan
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10776063
GetModulFileName() gives the path of the executable.

GetCurrentDirectory() gives the current working directory.

You may compare both paths and the directory should be identical to the directory part of the executable path.

    char szExePath[512];
    int lenExe = GetModuleFileName( NULL,  szExePath,   sizeof(szExePath));
    char szWorkingDir[512];
    int lenDir = GetCurrentDirectory(sizeof(szWorkingDir), szWorkingDir);
    if (lenDir < lenExe && strstr(szExePath, szWorkingDir) == szExePath)
    {
         // ok, check it isn't a sub directory
         int pos = strrchr(szExePath, '\\');
         if (pos == lenDir)
         {
             // all ok now, the executable has been started from the current working directory    
         }
    }
 
Regards, Alex
0
 

Author Comment

by:RonCode
ID: 10781058
Yeah check if the current directory is part of $PATH?

RonCode
0
 
LVL 12

Accepted Solution

by:
stefan73 earned 63 total points
ID: 10782551
RonCode,
> Yeah check if the current directory is part of $PATH?

That is tricky. You could have tons of possibilities:

1. Full path.
2. "."
3. :: (empty means current dir)
4. Via soft link
5. Any combinations of 1,2,4 and additional ../current_dir

Probably the easiest way is to check if your binary was found in the current directory with the "which" command.

Stefan
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 62 total points
ID: 10785662
Try this:

#include <windows.h>

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(int nArg, char* pszArgs[])
{
    // Get write access to the directory 'file'

    char szWorkingDir[1024];
    int lenDir = GetCurrentDirectory(sizeof(szWorkingDir), szWorkingDir);
    szWorkingDir[lenDir] = '\0';

    char szPath[1024];
    int lenPath = GetEnvironmentVariable("PATH", szPath, sizeof(szPath));

    HANDLE hdlDir = CreateFile (szWorkingDir,
                                GENERIC_READ,
                                FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
                                NULL,
                                OPEN_EXISTING,
                                FILE_FLAG_BACKUP_SEMANTICS,
                                NULL
                             );

    if (hdlDir == INVALID_HANDLE_VALUE)
    {
       cout << "Current directory " << szWorkingDir << " couldn't be opened. Error = " << GetLastError() << endl;
       return 2;
    }

    BY_HANDLE_FILE_INFORMATION fileInfo;
    if (!GetFileInformationByHandle(hdlDir, &fileInfo))
    {
       cout << "Current directory " << szWorkingDir << " couldn't get file info. Error = " << GetLastError() << endl;
       return 3;
    }
    CloseHandle(hdlDir);


    string        strDir(szWorkingDir);
    int           pos = strDir.find_last_of("\\/");
    if (pos != string::npos)
        strDir.erase(0, pos+1);
    string        strPath(szPath);
    stringstream  ssPath(strPath);

    while (!ssPath.eof())
    {
        getline(ssPath, strPath, ';');
        if (strPath.empty())
            continue;
        HANDLE hdl = CreateFile(strPath.c_str(), GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ, NULL,
                                    OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        if (hdl == INVALID_HANDLE_VALUE)
            continue;

        BY_HANDLE_FILE_INFORMATION info;
        if (!GetFileInformationByHandle(hdl, &info))
        {
           cout << "Current directory " << strPath << " couldn't get file info. Error = " << GetLastError() << endl;
           CloseHandle(hdl);
           continue;  // ignore error
        }
       
        if (fileInfo.dwVolumeSerialNumber == info.dwVolumeSerialNumber &&
            fileInfo.nFileIndexLow  == info.nFileIndexLow &&
            fileInfo.nFileIndexHigh == info.nFileIndexHigh)
        {
            cout << "Current directory " << szWorkingDir << " is part of %PATH% as " << strPath << endl << endl;
            CloseHandle(hdl);
            return 0;
        }
        CloseHandle(hdl);

    }

    cout << "current directory " << szWorkingDir << " is not part of %PATH%: " << endl << szPath << endl << endl;
    return 1;

}


There might be an easier way using SearchPath function of Windows API. However, i did find it after i had written that working code.

Regards, Alex
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now