Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe cross-platform function to get normalized path

I'd like to have a standard function that will convert relative paths into absolute ones, and if possible I'd like to make it as cross-platform as possible (so I'd like to avoid calling external library functions). This is intended so it's possible to prevent path exploitations.

I am aware that such a function wouldn't be able to detect symbolic links, but I'm ok with that for my application.

I could roll my own code, but there might be some problems with e.g. how a platform handles encoding or variations of the "../" pattern.

Is there something like that already implemented?

like image 319
Waneck Avatar asked Aug 20 '11 01:08

Waneck


2 Answers

There's not a single, universal function you can call, since there's no such function in the C or C++ standard libraries. On Windows, you can use GetFullPathName. On Linux, Mac OS X, and other *Unix-based systems, you can use the realpath(3) function, which as a bonus also resolves symbolic links along the way.

Beware: Any solution to this is only reliable in a single-threaded program. If you're using multiple threads, another can go out and change the working directory out from under you unexpectedly, changing the path name resolution.

like image 147
Adam Rosenfield Avatar answered Sep 23 '22 17:09

Adam Rosenfield


I think the closest you're going to get to platform independence are the POSIX libraries. In particular you'll wanna check out unistd.h which unfortunately I don't believe has a 'normalized' path concept. If I remember correctly the standard itself doesn't even know much about directories much less relative ones.

To get better than that I think you'll need to roll your own path goodies.

like image 25
unclejamil Avatar answered Sep 23 '22 17:09

unclejamil