安全的跨平台功能,获取标准化路径

发布于 2024-11-30 22:03:34 字数 201 浏览 2 评论 0原文

我想要一个标准函数,将相对路径转换为绝对路径,如果可能的话,我希望使其尽可能跨平台(所以我想避免调用外部库函数)。这样做的目的是为了可以防止路径利用。

我知道这样的函数无法检测符号链接,但对于我的应用程序来说我对此表示同意。

我可以推出自己的代码,但可能存在一些问题,例如平台如何处理编码或“../”模式的变体。

是否已经实施了类似的措施?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嘿哥们儿 2024-12-07 22:03:34

没有一个可以调用的通用函数,因为 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 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.

吹泡泡o 2024-12-07 22:03:34

我认为最接近平台独立性的是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文