curl在以root身份运行后,会重置cookie文件的所有者

编程语言 2026-07-08
<?php
$url = 'https://stackoverflow.com/questions/ask';
$file = '/home/www/.cookies2.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);

我从www运行这个脚本。并且拥有 664 www:www 的权限。
但是当我以root身份运行这个脚本时,它会将现有文件的权限重置为 600root:root
使用curl 7.29时按预期工作。使用curl 8.20时则出现了这个错误。

PHP 8.2.4,源码构建。

解决方案

当libcurl通过先在同一目录中写入一个临时文件,然后再将其重命名为给定的文件名来写入cookiejar文件时。

由于它总是创建一个新文件,这会导致该文件的所有权变为运行脚本的用户/组。即便root用户可以使用 chown(2) 将其改回原始所有者,但它不会这么做——通常让库的行为因用户而异是个坏主意。

如果所有者没有改变,权限将被复制到临时文件中。否则,该文件将获得默认权限600(可能会被用户的umask进一步修改)。与此相关的代码注释是

  /* If the existing file is not owned by the user, do not inherit
   * its permissions at the temp file created below. The permissions
   * might be unsuitable for holding user private data. */

这是为了解决问题 temp files: inherit permissions only for owner #21092 而做的。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章