安全的跨平台功能,获取标准化路径
我想要一个标准函数,将相对路径转换为绝对路径,如果可能的话,我希望使其尽可能跨平台(所以我想避免调用外部库函数)。这样做的目的是为了可以防止路径利用。
我知道这样的函数无法检测符号链接,但对于我的应用程序来说我对此表示同意。
我可以推出自己的代码,但可能存在一些问题,例如平台如何处理编码或“../”模式的变体。
是否已经实施了类似的措施?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有一个可以调用的通用函数,因为 C 或 C++ 标准库中没有这样的函数。在 Windows 上,您可以使用
GetFullPathName
。在 Linux、Mac OS X 和其他基于 Unix 的系统上,您可以使用realpath(3)
函数,作为奖励,它还可以一路解析符号链接。注意:任何解决方案都只在单线程程序中可靠。如果您使用多个线程,另一个线程可能会意外地更改您下面的工作目录,从而更改路径名解析。
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 therealpath(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.
我认为最接近平台独立性的是 POSIX 库。特别是你会想看看 unistd.h 不幸的是我不相信它有“标准化”路径概念。如果我没记错的话,标准本身甚至对目录了解不多,更不用说相关目录了。
为了变得更好,我认为你需要开辟自己的道路。
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.