posix_wrapper.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2026 Marek Küthe <m.k@mk16.de> 2 // 3 // SPDX-License-Identifier: GPL-3.0-or-later 4 5 #include "posix_wrapper.hpp" 6 7 int PosixWrapper::dup(const int oldfd) 8 { 9 const int result = ::dup(oldfd); 10 if (result < 0) 11 { 12 throw std::system_error(errno, 13 std::generic_category(), 14 "Failed to duplicate file descriptor."); 15 } 16 return result; 17 } 18 19 #ifdef HAVE_SETUGID 20 void PosixWrapper::set_uid(const uid_t uid) 21 { 22 const int result = ::setuid(uid); 23 if (result != 0) 24 { 25 throw std::system_error( 26 errno, std::generic_category(), "Failed to set uid."); 27 } 28 } 29 30 void PosixWrapper::set_gid(const gid_t uid) 31 { 32 const int result = ::setgid(uid); 33 if (result != 0) 34 { 35 throw std::system_error( 36 errno, std::generic_category(), "Failed to set gid."); 37 } 38 } 39 40 uid_t PosixWrapper::username_to_uid(const std::string& username) 41 { 42 // This function is called in a single-threaded manner in crazytrace. 43 // Therefore, it may be thread-unsafe. 44 struct passwd * entry = 45 ::getpwnam(username.c_str()); // NOLINT(concurrency-mt-unsafe) 46 if (entry == nullptr) 47 { 48 throw std::system_error( 49 errno, std::generic_category(), "Failed to get uid for username."); 50 } 51 return entry->pw_uid; 52 } 53 54 gid_t PosixWrapper::groupname_to_gid(const std::string& groupname) 55 { 56 // This function is called in a single-threaded manner in crazytrace. 57 // Therefore, it may be thread-unsafe. 58 struct group * entry = 59 ::getgrnam(groupname.c_str()); // NOLINT(concurrency-mt-unsafe) 60 if (entry == nullptr) 61 { 62 throw std::system_error( 63 errno, std::generic_category(), "Failed to get gid for groupname."); 64 } 65 return entry->gr_gid; 66 } 67 #endif