Skip to content

Commit

Permalink
memory/pci: Explicitly check for root access when needed
Browse files Browse the repository at this point in the history
Use ljsyscall's geteuid() via a new library function:

    lib.root_check()
  • Loading branch information
lukego committed Mar 23, 2015
1 parent 25f97c6 commit 51519c5
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
3 changes: 0 additions & 3 deletions src/core/clib.h
Expand Up @@ -61,6 +61,3 @@ uint16_t ntohs(uint16_t);
uint32_t htonl(uint32_t);
uint32_t ntohl(uint32_t);

// geteuid(2) - get effective user identity
int geteuid();

9 changes: 9 additions & 0 deletions src/core/lib.lua
Expand Up @@ -3,6 +3,7 @@ module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local getopt = require("lib.lua.alt_getopt")
local syscall = require("syscall")
require("core.clib_h")

-- Returns true if x and y are structurally similar (isomorphic).
Expand Down Expand Up @@ -419,6 +420,14 @@ function have_module (name)
end
end

-- Exit with an error if we are not running as root.
function root_check (message)
if syscall.geteuid() ~= 0 then
print(message or "error: must run as root")
main.exit(1)
end
end

function selftest ()
print("selftest: lib")
print("Testing equal")
Expand Down
1 change: 1 addition & 0 deletions src/core/memory.lua
Expand Up @@ -61,6 +61,7 @@ function allocate_hugetlb_chunk ()
end

function reserve_new_page ()
lib.root_check("error: must run as root to allocate memory for DMA")
set_hugepages(get_hugepages() + 1)
end

Expand Down
7 changes: 7 additions & 0 deletions src/lib/hardware/pci.lua
Expand Up @@ -71,6 +71,7 @@ end
--- Force Linux to release the device with `pciaddress`.
--- The corresponding network interface (e.g. `eth0`) will disappear.
function unbind_device_from_linux (pciaddress)
root_check()
local p = path(pciaddress).."/driver/unbind"
if lib.can_write(p) then
lib.writefile(path(pciaddress).."/driver/unbind", pciaddress)
Expand All @@ -82,6 +83,7 @@ end
-- Pointer for memory-mapped access.
-- File descriptor for the open sysfs resource file.
function map_pci_memory (device, n)
root_check()
local filepath = path(device).."/resource"..n
local fd = C.open_pci_resource(filepath)
assert(fd >= 0)
Expand All @@ -98,6 +100,7 @@ end
--- Enable or disable PCI bus mastering. DMA only works when bus
--- mastering is enabled.
function set_bus_master (device, enable)
root_check()
local fd = C.open_pcie_config(path(device).."/config")
local value = ffi.new("uint16_t[1]")
assert(C.pread(fd, value, 2, 0x4) == 2)
Expand All @@ -110,6 +113,10 @@ function set_bus_master (device, enable)
C.close(fd)
end

function root_check ()
lib.root_check("error: must run as root to access PCI devices")
end

--- ### Selftest
---
--- PCI selftest scans for available devices and performs our driver's
Expand Down

0 comments on commit 51519c5

Please sign in to comment.