diff --git a/frontend/device/generic/device.lua b/frontend/device/generic/device.lua index bc42d7d86..c8f4535e3 100644 --- a/frontend/device/generic/device.lua +++ b/frontend/device/generic/device.lua @@ -704,13 +704,16 @@ function Device:ping4(ip) -- NOTE: This is disabled by default, barring custom distro setup during init, c.f., sysctl net.ipv4.ping_group_range -- It also requires Linux 3.0+ (https://github.com/torvalds/linux/commit/c319b4d76b9e583a5d88d6bf190e079c4e43213d) local socket, socket_type - socket = C.socket(C.AF_INET, bit.bor(C.SOCK_DGRAM, C.SOCK_NONBLOCK, C.SOCK_CLOEXEC), C.IPPROTO_ICMP) + -- NOTE: We deliberately do NOT call socket() with SOCK_NONBLOCK/SOCK_CLOEXEC: + -- that form requires Linux 2.6.27+ and fails with EINVAL on older versions. + -- We set both flags via fcntl() below instead, which works on every kernel. + socket = C.socket(C.AF_INET, C.SOCK_DGRAM, C.IPPROTO_ICMP) if socket == -1 then local errno = ffi.errno() logger.dbg("Device:ping4: unprivileged ICMP socket:", ffi.string(C.strerror(errno))) -- Try a raw socket - socket = C.socket(C.AF_INET, bit.bor(C.SOCK_RAW, C.SOCK_NONBLOCK, C.SOCK_CLOEXEC), C.IPPROTO_ICMP) + socket = C.socket(C.AF_INET, C.SOCK_RAW, C.IPPROTO_ICMP) if socket == -1 then errno = ffi.errno() if errno == C.EPERM then @@ -719,12 +722,14 @@ function Device:ping4(ip) logger.dbg("Device:ping4: raw ICMP socket:", ffi.string(C.strerror(errno))) end --- Fall-back to the ping CLI tool, in the hope that it's setuid... - if self:isKindle() and self:hasDPad() then - -- NOTE: No -w flag available in the old busybox build used on Legacy Kindles (K4 included)... - return os.execute("ping -q -c1 " .. ip .. " > /dev/null") == 0 - else - return os.execute("ping -q -c1 -w2 " .. ip .. " > /dev/null") == 0 - end + -- NOTE: We can't rely on `ping -w`: it's not available in the old busybox build + -- used on Legacy Kindles (K4 included). Bound the runtime ourselves by + -- killing the ping after a timeout, which works with any ping implementation. + return os.execute(string.format([[ping -q -c1 %s >/dev/null & + pid=$! + (sleep 2; kill $pid 2>/dev/null) & + wait $pid 2>/dev/null + ]], ip)) == 0 else socket_type = C.SOCK_RAW end @@ -732,6 +737,10 @@ function Device:ping4(ip) socket_type = C.SOCK_DGRAM end + -- Apply FD_CLOEXEC + O_NONBLOCK now (see the socket() note above). + C.fcntl(socket, C.F_SETFD, C.FD_CLOEXEC) + C.fcntl(socket, C.F_SETFL, bit.bor(C.fcntl(socket, C.F_GETFL, 0), C.O_NONBLOCK)) + -- c.f., busybox's networking/ping.c local DEFDATALEN = 56 -- 64 - 8 local MAXIPLEN = 60