blob: 1435075dfc05cb8ac549f25f5bf688b245f89ef3 [file] [log] [blame]
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file contains SELinux file context helpers."""
import os
import stat
# Supported file type annotation mapping.
FILE_TYPE_ALL = 'ALL'
FILE_TYPE_FILE = 'FILE'
FILE_TYPE_DIR = 'DIR'
FILE_TYPE_BLOCK = 'BLOCK'
FILE_TYPE_SYMLINK = 'SYMLINK'
FILE_TYPE_CHARDEV = 'CHARDEV'
FILE_TYPE_PIPE = 'PIPE'
FILE_TYPE_SOCKET = 'SOCKET'
FILE_TYPE = {
FILE_TYPE_ALL: '',
FILE_TYPE_DIR: '-d',
FILE_TYPE_FILE: '--',
FILE_TYPE_BLOCK: '-b',
FILE_TYPE_SYMLINK: '-l',
FILE_TYPE_CHARDEV: '-c',
FILE_TYPE_PIPE: '-p',
FILE_TYPE_SOCKET: '-s',
}
def get_file_type(path):
return mode_to_file_type(os.lstat(path).st_mode)
def mode_to_file_type(st_mode):
"""Returns the key to FILE_TYPE for the output of os.stat(path)."""
if stat.S_ISDIR(st_mode):
return FILE_TYPE_DIR
if stat.S_ISCHR(st_mode):
return FILE_TYPE_CHARDEV
if stat.S_ISFIFO(st_mode):
return FILE_TYPE_PIPE
if stat.S_ISLNK(st_mode):
return FILE_TYPE_SYMLINK
if stat.S_ISSOCK(st_mode):
return FILE_TYPE_SOCKET
if stat.S_ISBLK(st_mode):
return FILE_TYPE_BLOCK
if stat.S_ISREG(st_mode):
return FILE_TYPE_FILE
# Match ALL for lack of a more specific match.
return FILE_TYPE_ALL