Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some code for working with /var/folders temp folders on macOS via ctypes
import glob, os.path, pwd, os
from ctypes import CDLL, byref, create_string_buffer, c_uint32
from ctypes.util import find_library
libsys = CDLL(find_library('C'))
def user_temp_dir(uid):
path_buffer = create_string_buffer(1024)
result = libsys.__user_local_dirname(c_uint32(uid), 0, byref(path_buffer), 1024)
return path_buffer.value.rsplit('/0/',1)[0]
def validate_var_folders():
# needs to be run as root
temp_folders = [x for x in glob.glob('/var/folders/*/*') if os.path.isdir(x)]
all_known_users = pwd.getpwall()
# calculate temp folder path for all known users
user_paths = dict()
uids = set()
for user in all_known_users:
uid = user.pw_uid
uids.add(uid)
gid = user.pw_gid
path = user_temp_dir(uid)
user_paths[path] = (uid, gid)
# loop over the folders we saw
calculated_folders = user_paths.keys()
for folder in temp_folders:
folder_info = os.stat(folder)
if not folder in calculated_folders:
print "Unknown user for temp folder:", folder
print "Current ownership: uid: %d, gid: %d" % (folder_info.st_uid, folder_info.st_gid)
if folder_info.st_uid in uids:
print "Diagnosis: User with uid %d exists, but wrong GeneratedUID (likely different user / not in use - check inside it?)\n" % folder_info.st_uid
else:
print "Diagnosis: No such user with uid %d, probably safe to delete\n" % folder_info.st_uid
else:
print "Known user for temp folder:", folder
print "Current ownership: uid: %d, gid: %d" % (folder_info.st_uid, folder_info.st_gid)
seen_uid, seen_gid = user_paths[folder]
if seen_uid != folder_info.st_uid:
print "Diagnosis: Ownership (uid) appears to be wrong! Should be: %d\n" % seen_uid
elif seen_gid != folder_info.st_gid:
print "Diagnosis: Group (gid) appears to be wrong! Should be: %d\n" % seen_gid
else:
print "Diagnosis: Looks good!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.