Patchouli
帕秋莉的魔法筆記

Follow

帕秋莉的魔法筆記

Follow

一個 Group Write Permission 的坑

Linux Group Write Permission

Patchouli's photo
Patchouli
·Mar 25, 2022·

2 min read

Group Write Permission

Python open/Golang open 開新檔案時,並不是直接按照 user 給的權限。

例如:

package main

import (
    "os"
)

func main() {
    os.OpenFile("aa.lock", os.O_RDWR|os.O_CREATE, 0664)
}

沒特別設定是沒辦法生出權限為 0664 的檔案。

這主要是源於 os.OpenFile 使用的 linux open,而根據 man open:

The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask).

而 default umask 是 022 ,意思是預設把 group write / other write 關掉。

所以要解決的話有兩個方法:

當然還有土法煉鋼的方式:

  • 建立完檔案直接用 chmod 更動,但是這樣建立檔案/chmod會有時間差。

umask

在呼叫 open 前先設定 umask。 要注意這設定是 process 級別的,所以假如嘗試這樣處理

oldValue = umask(002)
// ...
umask(oldValue)

這段就不會是 thread-safe 。

當然,可以考慮讓整隻程式都 umask(002),但挺髒的。

Default folder ACL

設定該檔案的資料的預設 Auth Control List 算是一個比較健康的方法:

umasktest 是上面的 golang 程式

$ ../umasktest/umasktest 
$ ls -al
total 12
drwxrwxr-x 2 alice   myteam  4096 Feb 18 10:28 .
drwxr-xr-x 5 root    root    4096 Feb 18 10:26 ..
-rw-r--r-- 1 alice   myteam     2 Feb 18 10:26 1
-rw-r--r-- 1 alice   myteam     0 Feb 18 10:28 aa.lock 
# 設定前沒有 group write 權限
$ setfacl -d -m g:myteam:rwx .
$ getfacl .
# file: .
# owner: alice
# group: myteam
user::rwx
group::rwx
other::r-x
default:user::rwx
default:group::rwx
default:group:myteam:rwx
default:mask::rwx
default:other::r-x

$ rm aa.lock 
$ ../umasktest/umasktest 
$ ls -al
total 12
drwxrwxr-x+ 2 alice   myteam  4096 Feb 18 10:32 .
drwxr-xr-x  5 root    root    4096 Feb 18 10:26 ..
-rw-r--r--  1 alice   myteam     2 Feb 18 10:26 1
-rw-rw-r--+ 1 alice   myteam     0 Feb 18 10:32 aa.lock # 有了!
 
Share this