tabs are as useful as a hole in the head

This commit is contained in:
Kay Sievers
2012-01-10 01:34:15 +01:00
parent ebda27438b
commit 912541b024
74 changed files with 17677 additions and 17684 deletions
+7 -7
View File
@@ -1,12 +1,12 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@@ -56,7 +56,7 @@ patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
@@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
@@ -277,9 +277,9 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
+5 -7
View File
@@ -1,18 +1,16 @@
#!/bin/sh
set -e
#!/bin/sh -e
if [ -f .git/hooks/pre-commit.sample -a ! -f .git/hooks/pre-commit ] ; then
cp -p .git/hooks/pre-commit.sample .git/hooks/pre-commit && \
chmod +x .git/hooks/pre-commit && \
echo "Activated pre-commit hook."
cp -p .git/hooks/pre-commit.sample .git/hooks/pre-commit && \
chmod +x .git/hooks/pre-commit && \
echo "Activated pre-commit hook."
fi
gtkdocize
autoreconf --install --symlink
libdir() {
echo $(cd $1/$(gcc -print-multi-os-directory); pwd)
echo $(cd $1/$(gcc -print-multi-os-directory); pwd)
}
args="\
+119 -119
View File
@@ -1,9 +1,9 @@
AC_PREREQ(2.60)
AC_INIT([udev],
[175],
[linux-hotplug@vger.kernel.org],
[udev],
[http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html])
[175],
[linux-hotplug@vger.kernel.org],
[udev],
[http://www.kernel.org/pub/linux/utils/kernel/hotplug/udev.html])
AC_CONFIG_SRCDIR([src/udevd.c])
AC_CONFIG_AUX_DIR([build-aux])
AM_INIT_AUTOMAKE([check-news foreign 1.11 -Wall -Wno-portability silent-rules tar-pax no-dist-gzip dist-xz subdir-objects])
@@ -28,90 +28,90 @@ PKG_CHECK_MODULES(BLKID, blkid >= 2.20)
PKG_CHECK_MODULES(KMOD, libkmod >= 3)
if test "x$cross_compiling" = "xno" ; then
AC_CHECK_FILES([/usr/share/pci.ids], [pciids=/usr/share/pci.ids])
AC_CHECK_FILES([/usr/share/hwdata/pci.ids], [pciids=/usr/share/hwdata/pci.ids])
AC_CHECK_FILES([/usr/share/misc/pci.ids], [pciids=/usr/share/misc/pci.ids])
AC_CHECK_FILES([/usr/share/pci.ids], [pciids=/usr/share/pci.ids])
AC_CHECK_FILES([/usr/share/hwdata/pci.ids], [pciids=/usr/share/hwdata/pci.ids])
AC_CHECK_FILES([/usr/share/misc/pci.ids], [pciids=/usr/share/misc/pci.ids])
fi
AC_ARG_WITH(usb-ids-path,
[AS_HELP_STRING([--with-usb-ids-path=DIR], [Path to usb.ids file])],
[USB_DATABASE=${withval}],
[if test -n "$usbids" ; then
USB_DATABASE="$usbids"
else
PKG_CHECK_MODULES(USBUTILS, usbutils >= 0.82)
AC_SUBST([USB_DATABASE], [$($PKG_CONFIG --variable=usbids usbutils)])
fi])
[AS_HELP_STRING([--with-usb-ids-path=DIR], [Path to usb.ids file])],
[USB_DATABASE=${withval}],
[if test -n "$usbids" ; then
USB_DATABASE="$usbids"
else
PKG_CHECK_MODULES(USBUTILS, usbutils >= 0.82)
AC_SUBST([USB_DATABASE], [$($PKG_CONFIG --variable=usbids usbutils)])
fi])
AC_MSG_CHECKING([for USB database location])
AC_MSG_RESULT([$USB_DATABASE])
AC_SUBST(USB_DATABASE)
AC_ARG_WITH(pci-ids-path,
[AS_HELP_STRING([--with-pci-ids-path=DIR], [Path to pci.ids file])],
[PCI_DATABASE=${withval}],
[if test -n "$pciids" ; then
PCI_DATABASE="$pciids"
else
AC_MSG_ERROR([pci.ids not found, try --with-pci-ids-path=])
fi])
[AS_HELP_STRING([--with-pci-ids-path=DIR], [Path to pci.ids file])],
[PCI_DATABASE=${withval}],
[if test -n "$pciids" ; then
PCI_DATABASE="$pciids"
else
AC_MSG_ERROR([pci.ids not found, try --with-pci-ids-path=])
fi])
AC_MSG_CHECKING([for PCI database location])
AC_MSG_RESULT([$PCI_DATABASE])
AC_SUBST(PCI_DATABASE)
AC_ARG_WITH([rootprefix],
AS_HELP_STRING([--with-rootprefix=DIR], [rootfs directory prefix for config files and kernel modules]),
[], [with_rootprefix=${ac_default_prefix}])
AS_HELP_STRING([--with-rootprefix=DIR], [rootfs directory prefix for config files and kernel modules]),
[], [with_rootprefix=${ac_default_prefix}])
AC_SUBST([rootprefix], [$with_rootprefix])
AC_ARG_WITH([rootlibdir],
AS_HELP_STRING([--with-rootlibdir=DIR], [rootfs directory to install shared libraries]),
[], [with_rootlibdir=$libdir])
AS_HELP_STRING([--with-rootlibdir=DIR], [rootfs directory to install shared libraries]),
[], [with_rootlibdir=$libdir])
AC_SUBST([rootlib_execdir], [$with_rootlibdir])
AC_ARG_WITH([selinux],
AS_HELP_STRING([--with-selinux], [enable SELinux support]),
[], [with_selinux=no])
AS_HELP_STRING([--with-selinux], [enable SELinux support]),
[], [with_selinux=no])
AS_IF([test "x$with_selinux" = "xyes"], [
LIBS_save=$LIBS
AC_CHECK_LIB(selinux, getprevcon,
[],
AC_MSG_ERROR([SELinux selected but libselinux not found]))
LIBS=$LIBS_save
SELINUX_LIBS="-lselinux -lsepol"
AC_DEFINE(WITH_SELINUX, [1] ,[SELinux support.])
LIBS_save=$LIBS
AC_CHECK_LIB(selinux, getprevcon,
[],
AC_MSG_ERROR([SELinux selected but libselinux not found]))
LIBS=$LIBS_save
SELINUX_LIBS="-lselinux -lsepol"
AC_DEFINE(WITH_SELINUX, [1] ,[SELinux support.])
])
AC_SUBST([SELINUX_LIBS])
AM_CONDITIONAL(WITH_SELINUX, [test "x$with_selinux" = "xyes"])
AC_ARG_ENABLE([debug],
AS_HELP_STRING([--enable-debug], [enable debug messages @<:@default=disabled@:>@]),
[], [enable_debug=no])
AS_HELP_STRING([--enable-debug], [enable debug messages @<:@default=disabled@:>@]),
[], [enable_debug=no])
AS_IF([test "x$enable_debug" = "xyes"], [ AC_DEFINE(ENABLE_DEBUG, [1], [Debug messages.]) ])
AC_ARG_ENABLE([logging],
AS_HELP_STRING([--disable-logging], [disable system logging @<:@default=enabled@:>@]),
[], enable_logging=yes)
AS_HELP_STRING([--disable-logging], [disable system logging @<:@default=enabled@:>@]),
[], enable_logging=yes)
AS_IF([test "x$enable_logging" = "xyes"], [ AC_DEFINE(ENABLE_LOGGING, [1], [System logging.]) ])
AC_ARG_WITH(firmware-path,
AS_HELP_STRING([--with-firmware-path=DIR[[[:DIR[...]]]]],
[Firmware search path (default=/lib/firmware/updates:/lib/firmware)]),
[], [with_firmware_path="$rootprefix/lib/firmware/updates:$rootprefix/lib/firmware"])
AS_HELP_STRING([--with-firmware-path=DIR[[[:DIR[...]]]]],
[Firmware search path (default=/lib/firmware/updates:/lib/firmware)]),
[], [with_firmware_path="$rootprefix/lib/firmware/updates:$rootprefix/lib/firmware"])
OLD_IFS=$IFS
IFS=:
for i in $with_firmware_path; do
if test "x${FIRMWARE_PATH}" = "x"; then
FIRMWARE_PATH="\\\"${i}/\\\""
else
FIRMWARE_PATH="${FIRMWARE_PATH}, \\\"${i}/\\\""
fi
if test "x${FIRMWARE_PATH}" = "x"; then
FIRMWARE_PATH="\\\"${i}/\\\""
else
FIRMWARE_PATH="${FIRMWARE_PATH}, \\\"${i}/\\\""
fi
done
IFS=$OLD_IFS
AC_SUBST([FIRMWARE_PATH], [$FIRMWARE_PATH])
AC_ARG_WITH([systemdsystemunitdir],
AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files]),
[], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files]),
[], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
AS_IF([test "x$with_systemdsystemunitdir" != "xno"], [ AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir]) ])
AM_CONDITIONAL(WITH_SYSTEMD, [test -n "$with_systemdsystemunitdir" -a "x$with_systemdsystemunitdir" != "xno" ])
@@ -119,21 +119,21 @@ AM_CONDITIONAL(WITH_SYSTEMD, [test -n "$with_systemdsystemunitdir" -a "x$with_sy
# GUdev - libudev gobject interface
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([gudev],
AS_HELP_STRING([--disable-gudev], [disable Gobject libudev support @<:@default=enabled@:>@]),
[], [enable_gudev=yes])
AS_HELP_STRING([--disable-gudev], [disable Gobject libudev support @<:@default=enabled@:>@]),
[], [enable_gudev=yes])
AS_IF([test "x$enable_gudev" = "xyes"], [ PKG_CHECK_MODULES([GLIB], [glib-2.0 >= 2.22.0 gobject-2.0 >= 2.22.0]) ])
AC_ARG_ENABLE([introspection],
AS_HELP_STRING([--disable-introspection], [disable GObject introspection @<:@default=enabled@:>@]),
[], [enable_introspection=yes])
AS_HELP_STRING([--disable-introspection], [disable GObject introspection @<:@default=enabled@:>@]),
[], [enable_introspection=yes])
AS_IF([test "x$enable_introspection" = "xyes"], [
PKG_CHECK_MODULES([INTROSPECTION], [gobject-introspection-1.0 >= 0.6.2])
AC_DEFINE([ENABLE_INTROSPECTION], [1], [enable GObject introspection support])
AC_SUBST([G_IR_SCANNER], [$($PKG_CONFIG --variable=g_ir_scanner gobject-introspection-1.0)])
AC_SUBST([G_IR_COMPILER], [$($PKG_CONFIG --variable=g_ir_compiler gobject-introspection-1.0)])
AC_SUBST([G_IR_GENERATE], [$($PKG_CONFIG --variable=g_ir_generate gobject-introspection-1.0)])
AC_SUBST([GIRDIR], [$($PKG_CONFIG --define-variable=datadir=${datadir} --variable=girdir gobject-introspection-1.0)])
AC_SUBST([GIRTYPELIBDIR], [$($PKG_CONFIG --define-variable=libdir=${libdir} --variable=typelibdir gobject-introspection-1.0)])
PKG_CHECK_MODULES([INTROSPECTION], [gobject-introspection-1.0 >= 0.6.2])
AC_DEFINE([ENABLE_INTROSPECTION], [1], [enable GObject introspection support])
AC_SUBST([G_IR_SCANNER], [$($PKG_CONFIG --variable=g_ir_scanner gobject-introspection-1.0)])
AC_SUBST([G_IR_COMPILER], [$($PKG_CONFIG --variable=g_ir_compiler gobject-introspection-1.0)])
AC_SUBST([G_IR_GENERATE], [$($PKG_CONFIG --variable=g_ir_generate gobject-introspection-1.0)])
AC_SUBST([GIRDIR], [$($PKG_CONFIG --define-variable=datadir=${datadir} --variable=girdir gobject-introspection-1.0)])
AC_SUBST([GIRTYPELIBDIR], [$($PKG_CONFIG --define-variable=libdir=${libdir} --variable=typelibdir gobject-introspection-1.0)])
])
AM_CONDITIONAL([ENABLE_INTROSPECTION], [test "x$enable_introspection" = "xyes"])
AM_CONDITIONAL([ENABLE_GUDEV], [test "x$enable_gudev" = "xyes"])
@@ -142,16 +142,16 @@ AM_CONDITIONAL([ENABLE_GUDEV], [test "x$enable_gudev" = "xyes"])
# keymap - map custom hardware's multimedia keys
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([keymap],
AS_HELP_STRING([--disable-keymap], [disable keymap fixup support @<:@default=enabled@:>@]),
[], [enable_keymap=yes])
AS_HELP_STRING([--disable-keymap], [disable keymap fixup support @<:@default=enabled@:>@]),
[], [enable_keymap=yes])
AS_IF([test "x$enable_keymap" = "xyes"], [
AC_PATH_PROG([GPERF], [gperf])
if test -z "$GPERF"; then
AC_MSG_ERROR([gperf is needed])
fi
AC_PATH_PROG([GPERF], [gperf])
if test -z "$GPERF"; then
AC_MSG_ERROR([gperf is needed])
fi
AC_CHECK_HEADER([linux/input.h], [:], AC_MSG_ERROR([kernel headers not found]))
AC_SUBST([INCLUDE_PREFIX], [$(echo '#include <linux/input.h>' | eval $ac_cpp -E - | sed -n '/linux\/input.h/ {s:.*"\(.*\)/linux/input.h".*:\1:; p; q}')])
AC_CHECK_HEADER([linux/input.h], [:], AC_MSG_ERROR([kernel headers not found]))
AC_SUBST([INCLUDE_PREFIX], [$(echo '#include <linux/input.h>' | eval $ac_cpp -E - | sed -n '/linux\/input.h/ {s:.*"\(.*\)/linux/input.h".*:\1:; p; q}')])
])
AM_CONDITIONAL([ENABLE_KEYMAP], [test "x$enable_keymap" = "xyes"])
@@ -159,29 +159,29 @@ AM_CONDITIONAL([ENABLE_KEYMAP], [test "x$enable_keymap" = "xyes"])
# mtd_probe - autoloads FTL module for mtd devices
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([mtd_probe],
AS_HELP_STRING([--disable-mtd_probe], [disable MTD support @<:@default=enabled@:>@]),
[], [enable_mtd_probe=yes])
AS_HELP_STRING([--disable-mtd_probe], [disable MTD support @<:@default=enabled@:>@]),
[], [enable_mtd_probe=yes])
AM_CONDITIONAL([ENABLE_MTD_PROBE], [test "x$enable_mtd_probe" = "xyes"])
# ------------------------------------------------------------------------------
# rule_generator - persistent network and optical device rule generator
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([rule_generator],
AS_HELP_STRING([--enable-rule_generator], [enable persistent network + cdrom links support @<:@default=disabled@:>@]),
[], [enable_rule_generator=no])
AS_HELP_STRING([--enable-rule_generator], [enable persistent network + cdrom links support @<:@default=disabled@:>@]),
[], [enable_rule_generator=no])
AM_CONDITIONAL([ENABLE_RULE_GENERATOR], [test "x$enable_rule_generator" = "xyes"])
# ------------------------------------------------------------------------------
# udev_acl - apply ACLs for users with local forground sessions
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([udev_acl],
AS_HELP_STRING([--enable-udev_acl], [enable local user acl permissions support @<:@default=disabled@:>@]),
[], [enable_udev_acl=no])
AS_HELP_STRING([--enable-udev_acl], [enable local user acl permissions support @<:@default=disabled@:>@]),
[], [enable_udev_acl=no])
AS_IF([test "x$enable_udev_acl" = "xyes"], [
AC_CHECK_LIB([acl], [acl_init], [:], AC_MSG_ERROR([libacl not found]))
AC_CHECK_HEADER([acl/libacl.h], [:], AC_MSG_ERROR([libacl header not found]))
AC_CHECK_LIB([acl], [acl_init], [:], AC_MSG_ERROR([libacl not found]))
AC_CHECK_HEADER([acl/libacl.h], [:], AC_MSG_ERROR([libacl header not found]))
PKG_CHECK_MODULES([GLIB], [glib-2.0 >= 2.22.0 gobject-2.0 >= 2.22.0])
PKG_CHECK_MODULES([GLIB], [glib-2.0 >= 2.22.0 gobject-2.0 >= 2.22.0])
])
AM_CONDITIONAL([ENABLE_UDEV_ACL], [test "x$enable_udev_acl" = "xyes"])
@@ -189,16 +189,16 @@ AM_CONDITIONAL([ENABLE_UDEV_ACL], [test "x$enable_udev_acl" = "xyes"])
# create_floppy_devices - historical floppy kernel device nodes (/dev/fd0h1440, ...)
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([floppy],
AS_HELP_STRING([--enable-floppy], [enable legacy floppy support @<:@default=disabled@:>@]),
[], [enable_floppy=no])
AS_HELP_STRING([--enable-floppy], [enable legacy floppy support @<:@default=disabled@:>@]),
[], [enable_floppy=no])
AM_CONDITIONAL([ENABLE_FLOPPY], [test "x$enable_floppy" = "xyes"])
# ------------------------------------------------------------------------------
# edd_id - create /dev/disk/by-id/edd-* links for BIOS EDD data
# ------------------------------------------------------------------------------
AC_ARG_ENABLE([edd],
AS_HELP_STRING([--enable-edd], [enable disk edd support @<:@default=disabled@:>@]),
[], [enable_edd=no])
AS_HELP_STRING([--enable-edd], [enable disk edd support @<:@default=disabled@:>@]),
[], [enable_edd=no])
AM_CONDITIONAL([ENABLE_EDD], [test "x$enable_edd" = "xyes"])
my_CFLAGS="-Wall \
@@ -211,50 +211,50 @@ AC_SUBST([my_CFLAGS])
AC_CONFIG_HEADERS(config.h)
AC_CONFIG_FILES([
Makefile
src/docs/Makefile
src/docs/version.xml
src/extras/gudev/docs/Makefile
src/extras/gudev/docs/version.xml
Makefile
src/docs/Makefile
src/docs/version.xml
src/extras/gudev/docs/Makefile
src/extras/gudev/docs/version.xml
])
AC_OUTPUT
AC_MSG_RESULT([
$PACKAGE $VERSION
========
$PACKAGE $VERSION
========
prefix: ${prefix}
rootprefix: ${rootprefix}
sysconfdir: ${sysconfdir}
bindir: ${bindir}
libdir: ${libdir}
rootlibdir: ${rootlib_execdir}
libexecdir: ${libexecdir}
datarootdir: ${datarootdir}
mandir: ${mandir}
includedir: ${includedir}
include_prefix: ${INCLUDE_PREFIX}
systemdsystemunitdir: ${systemdsystemunitdir}
firmware path: ${FIRMWARE_PATH}
usb.ids: ${USB_DATABASE}
pci.ids: ${PCI_DATABASE}
prefix: ${prefix}
rootprefix: ${rootprefix}
sysconfdir: ${sysconfdir}
bindir: ${bindir}
libdir: ${libdir}
rootlibdir: ${rootlib_execdir}
libexecdir: ${libexecdir}
datarootdir: ${datarootdir}
mandir: ${mandir}
includedir: ${includedir}
include_prefix: ${INCLUDE_PREFIX}
systemdsystemunitdir: ${systemdsystemunitdir}
firmware path: ${FIRMWARE_PATH}
usb.ids: ${USB_DATABASE}
pci.ids: ${PCI_DATABASE}
compiler: ${CC}
cflags: ${CFLAGS}
ldflags: ${LDFLAGS}
xsltproc: ${XSLTPROC}
gperf: ${GPERF}
compiler: ${CC}
cflags: ${CFLAGS}
ldflags: ${LDFLAGS}
xsltproc: ${XSLTPROC}
gperf: ${GPERF}
logging: ${enable_logging}
debug: ${enable_debug}
selinux: ${with_selinux}
logging: ${enable_logging}
debug: ${enable_debug}
selinux: ${with_selinux}
gudev: ${enable_gudev}
gintrospection: ${enable_introspection}
keymap: ${enable_keymap}
mtd_probe: ${enable_mtd_probe}
rule_generator: ${enable_rule_generator}
udev_acl: ${enable_udev_acl}
floppy: ${enable_floppy}
edd: ${enable_edd}
gudev: ${enable_gudev}
gintrospection: ${enable_introspection}
keymap: ${enable_keymap}
mtd_probe: ${enable_mtd_probe}
rule_generator: ${enable_rule_generator}
udev_acl: ${enable_udev_acl}
floppy: ${enable_floppy}
edd: ${enable_edd}
])
+1 -1
View File
@@ -1,4 +1,4 @@
# do not edit this file, it will be overwritten on update
KERNEL=="z90crypt", MODE="0666"
KERNEL=="z90crypt", MODE="0666"
+31 -31
View File
@@ -2,44 +2,44 @@
KERNEL=="pty[pqrstuvwxyzabcdef][0123456789abcdef]", GROUP="tty", MODE="0660"
KERNEL=="tty[pqrstuvwxyzabcdef][0123456789abcdef]", GROUP="tty", MODE="0660"
KERNEL=="ptmx", GROUP="tty", MODE="0666"
KERNEL=="tty", GROUP="tty", MODE="0666"
KERNEL=="tty[0-9]*", GROUP="tty", MODE="0620"
KERNEL=="ptmx", GROUP="tty", MODE="0666"
KERNEL=="tty", GROUP="tty", MODE="0666"
KERNEL=="tty[0-9]*", GROUP="tty", MODE="0620"
KERNEL=="vcs|vcs[0-9]*|vcsa|vcsa[0-9]*", GROUP="tty"
# serial
KERNEL=="tty[A-Z]*[0-9]|pppox[0-9]*|ircomm[0-9]*|noz[0-9]*|rfcomm[0-9]*", GROUP="dialout"
KERNEL=="mwave", GROUP="dialout"
KERNEL=="hvc*|hvsi*", GROUP="dialout"
KERNEL=="mwave", GROUP="dialout"
KERNEL=="hvc*|hvsi*", GROUP="dialout"
# virtio serial / console ports
KERNEL=="vport*", ATTR{name}=="?*", SYMLINK+="virtio-ports/$attr{name}"
# mem
KERNEL=="null|zero|full|random|urandom", MODE="0666"
KERNEL=="mem|kmem|port|nvram", GROUP="kmem", MODE="0640"
KERNEL=="mem|kmem|port|nvram", GROUP="kmem", MODE="0640"
# input
SUBSYSTEM=="input", ENV{ID_INPUT}=="", IMPORT{builtin}="input_id"
KERNEL=="mouse*|mice|event*", MODE="0640"
KERNEL=="ts[0-9]*|uinput", MODE="0640"
KERNEL=="js[0-9]*", MODE="0644"
KERNEL=="mouse*|mice|event*", MODE="0640"
KERNEL=="ts[0-9]*|uinput", MODE="0640"
KERNEL=="js[0-9]*", MODE="0644"
# video4linux
SUBSYSTEM=="video4linux", GROUP="video"
KERNEL=="vttuner*", GROUP="video"
KERNEL=="vtx*|vbi*", GROUP="video"
KERNEL=="winradio*", GROUP="video"
SUBSYSTEM=="video4linux", GROUP="video"
KERNEL=="vttuner*", GROUP="video"
KERNEL=="vtx*|vbi*", GROUP="video"
KERNEL=="winradio*", GROUP="video"
# graphics
KERNEL=="agpgart", GROUP="video"
KERNEL=="pmu", GROUP="video"
KERNEL=="nvidia*|nvidiactl*", GROUP="video"
SUBSYSTEM=="graphics", GROUP="video"
SUBSYSTEM=="drm", GROUP="video"
KERNEL=="agpgart", GROUP="video"
KERNEL=="pmu", GROUP="video"
KERNEL=="nvidia*|nvidiactl*", GROUP="video"
SUBSYSTEM=="graphics", GROUP="video"
SUBSYSTEM=="drm", GROUP="video"
# sound
SUBSYSTEM=="sound", GROUP="audio", \
SUBSYSTEM=="sound", GROUP="audio", \
OPTIONS+="static_node=snd/seq", OPTIONS+="static_node=snd/timer"
# DVB (video)
@@ -56,11 +56,11 @@ SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", MODE="0664"
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", IMPORT{builtin}="usb_id"
# printer
KERNEL=="parport[0-9]*", GROUP="lp"
SUBSYSTEM=="printer", KERNEL=="lp*", GROUP="lp"
SUBSYSTEM=="ppdev", GROUP="lp"
KERNEL=="lp[0-9]*", GROUP="lp"
KERNEL=="irlpt[0-9]*", GROUP="lp"
KERNEL=="parport[0-9]*", GROUP="lp"
SUBSYSTEM=="printer", KERNEL=="lp*", GROUP="lp"
SUBSYSTEM=="ppdev", GROUP="lp"
KERNEL=="lp[0-9]*", GROUP="lp"
KERNEL=="irlpt[0-9]*", GROUP="lp"
SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:0701??:*", GROUP="lp"
# block
@@ -91,17 +91,17 @@ SUBSYSTEM=="aoe", GROUP="disk", MODE="0220"
SUBSYSTEM=="aoe", KERNEL=="err", MODE="0440"
# network
KERNEL=="tun", MODE="0666", OPTIONS+="static_node=net/tun"
KERNEL=="rfkill", MODE="0644"
KERNEL=="tun", MODE="0666", OPTIONS+="static_node=net/tun"
KERNEL=="rfkill", MODE="0644"
# CPU
KERNEL=="cpu[0-9]*", MODE="0444"
KERNEL=="cpu[0-9]*", MODE="0444"
KERNEL=="fuse", ACTION=="add", MODE="0666", OPTIONS+="static_node=fuse"
KERNEL=="fuse", ACTION=="add", MODE="0666", OPTIONS+="static_node=fuse"
SUBSYSTEM=="rtc", DRIVERS=="rtc_cmos", SYMLINK+="rtc"
KERNEL=="mmtimer", MODE="0644"
KERNEL=="rflash[0-9]*", MODE="0400"
KERNEL=="rrom[0-9]*", MODE="0400"
KERNEL=="mmtimer", MODE="0644"
KERNEL=="rflash[0-9]*", MODE="0400"
KERNEL=="rrom[0-9]*", MODE="0400"
SUBSYSTEM=="firmware", ACTION=="add", IMPORT{builtin}="firmware"
+6 -6
View File
@@ -1,5 +1,5 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
@@ -10,7 +10,7 @@
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@@ -112,7 +112,7 @@ modification follow. Pay close attention to the difference between a
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
@@ -432,7 +432,7 @@ decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
@@ -455,7 +455,7 @@ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
+195 -195
View File
@@ -71,32 +71,32 @@
static int debug = 0;
static void log_fn(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)
const char *file, int line, const char *fn,
const char *format, va_list args)
{
if (debug) {
fprintf(stderr, "%s: ", fn);
vfprintf(stderr, format, args);
} else {
vsyslog(priority, format, args);
}
if (debug) {
fprintf(stderr, "%s: ", fn);
vfprintf(stderr, format, args);
} else {
vsyslog(priority, format, args);
}
}
typedef enum {
ORIENTATION_UNDEFINED,
ORIENTATION_NORMAL,
ORIENTATION_BOTTOM_UP,
ORIENTATION_LEFT_UP,
ORIENTATION_RIGHT_UP
ORIENTATION_UNDEFINED,
ORIENTATION_NORMAL,
ORIENTATION_BOTTOM_UP,
ORIENTATION_LEFT_UP,
ORIENTATION_RIGHT_UP
} OrientationUp;
static const char *orientations[] = {
"undefined",
"normal",
"bottom-up",
"left-up",
"right-up",
NULL
"undefined",
"normal",
"bottom-up",
"left-up",
"right-up",
NULL
};
#define ORIENTATION_UP_UP ORIENTATION_NORMAL
@@ -111,247 +111,247 @@ static const char *orientations[] = {
static const char *
orientation_to_string (OrientationUp o)
{
return orientations[o];
return orientations[o];
}
static OrientationUp
string_to_orientation (const char *orientation)
{
int i;
int i;
if (orientation == NULL)
return ORIENTATION_UNDEFINED;
for (i = 0; orientations[i] != NULL; i++) {
if (strcmp (orientation, orientations[i]) == 0)
return i;
}
return ORIENTATION_UNDEFINED;
if (orientation == NULL)
return ORIENTATION_UNDEFINED;
for (i = 0; orientations[i] != NULL; i++) {
if (strcmp (orientation, orientations[i]) == 0)
return i;
}
return ORIENTATION_UNDEFINED;
}
static OrientationUp
orientation_calc (OrientationUp prev,
int x, int y, int z)
int x, int y, int z)
{
int rotation;
OrientationUp ret = prev;
int rotation;
OrientationUp ret = prev;
/* Portrait check */
rotation = round(atan((double) x / sqrt(y * y + z * z)) * RADIANS_TO_DEGREES);
/* Portrait check */
rotation = round(atan((double) x / sqrt(y * y + z * z)) * RADIANS_TO_DEGREES);
if (abs(rotation) > THRESHOLD_PORTRAIT) {
ret = (rotation < 0) ? ORIENTATION_LEFT_UP : ORIENTATION_RIGHT_UP;
if (abs(rotation) > THRESHOLD_PORTRAIT) {
ret = (rotation < 0) ? ORIENTATION_LEFT_UP : ORIENTATION_RIGHT_UP;
/* Some threshold to switching between portrait modes */
if (prev == ORIENTATION_LEFT_UP || prev == ORIENTATION_RIGHT_UP) {
if (abs(rotation) < SAME_AXIS_LIMIT) {
ret = prev;
}
}
/* Some threshold to switching between portrait modes */
if (prev == ORIENTATION_LEFT_UP || prev == ORIENTATION_RIGHT_UP) {
if (abs(rotation) < SAME_AXIS_LIMIT) {
ret = prev;
}
}
} else {
/* Landscape check */
rotation = round(atan((double) y / sqrt(x * x + z * z)) * RADIANS_TO_DEGREES);
} else {
/* Landscape check */
rotation = round(atan((double) y / sqrt(x * x + z * z)) * RADIANS_TO_DEGREES);
if (abs(rotation) > THRESHOLD_LANDSCAPE) {
ret = (rotation < 0) ? ORIENTATION_BOTTOM_UP : ORIENTATION_NORMAL;
if (abs(rotation) > THRESHOLD_LANDSCAPE) {
ret = (rotation < 0) ? ORIENTATION_BOTTOM_UP : ORIENTATION_NORMAL;
/* Some threshold to switching between landscape modes */
if (prev == ORIENTATION_BOTTOM_UP || prev == ORIENTATION_NORMAL) {
if (abs(rotation) < SAME_AXIS_LIMIT) {
ret = prev;
}
}
}
}
/* Some threshold to switching between landscape modes */
if (prev == ORIENTATION_BOTTOM_UP || prev == ORIENTATION_NORMAL) {
if (abs(rotation) < SAME_AXIS_LIMIT) {
ret = prev;
}
}
}
}
return ret;
return ret;
}
static OrientationUp
get_prev_orientation(struct udev_device *dev)
{
const char *value;
const char *value;
value = udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER_ORIENTATION");
if (value == NULL)
return ORIENTATION_UNDEFINED;
return string_to_orientation(value);
value = udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER_ORIENTATION");
if (value == NULL)
return ORIENTATION_UNDEFINED;
return string_to_orientation(value);
}
#define SET_AXIS(axis, code_) if (ev[i].code == code_) { if (got_##axis == 0) { axis = ev[i].value; got_##axis = 1; } }
/* accelerometers */
static void test_orientation(struct udev *udev,
struct udev_device *dev,
const char *devpath)
struct udev_device *dev,
const char *devpath)
{
OrientationUp old, new;
int fd, r;
struct input_event ev[64];
int got_syn = 0;
int got_x, got_y, got_z;
int x = 0, y = 0, z = 0;
char text[64];
OrientationUp old, new;
int fd, r;
struct input_event ev[64];
int got_syn = 0;
int got_x, got_y, got_z;
int x = 0, y = 0, z = 0;
char text[64];
old = get_prev_orientation(dev);
old = get_prev_orientation(dev);
if ((fd = open(devpath, O_RDONLY)) < 0)
return;
if ((fd = open(devpath, O_RDONLY)) < 0)
return;
got_x = got_y = got_z = 0;
got_x = got_y = got_z = 0;
while (1) {
int i;
while (1) {
int i;
r = read(fd, ev, sizeof(struct input_event) * 64);
r = read(fd, ev, sizeof(struct input_event) * 64);
if (r < (int) sizeof(struct input_event))
return;
if (r < (int) sizeof(struct input_event))
return;
for (i = 0; i < r / (int) sizeof(struct input_event); i++) {
if (got_syn == 1) {
if (ev[i].type == EV_ABS) {
SET_AXIS(x, ABS_X);
SET_AXIS(y, ABS_Y);
SET_AXIS(z, ABS_Z);
}
}
if (ev[i].type == EV_SYN && ev[i].code == SYN_REPORT) {
got_syn = 1;
}
if (got_x && got_y && got_z)
goto read_dev;
}
}
for (i = 0; i < r / (int) sizeof(struct input_event); i++) {
if (got_syn == 1) {
if (ev[i].type == EV_ABS) {
SET_AXIS(x, ABS_X);
SET_AXIS(y, ABS_Y);
SET_AXIS(z, ABS_Z);
}
}
if (ev[i].type == EV_SYN && ev[i].code == SYN_REPORT) {
got_syn = 1;
}
if (got_x && got_y && got_z)
goto read_dev;
}
}
read_dev:
close(fd);
close(fd);
if (!got_x || !got_y || !got_z)
return;
if (!got_x || !got_y || !got_z)
return;
new = orientation_calc(old, x, y, z);
snprintf(text, sizeof(text), "ID_INPUT_ACCELEROMETER_ORIENTATION=%s", orientation_to_string(new));
puts(text);
new = orientation_calc(old, x, y, z);
snprintf(text, sizeof(text), "ID_INPUT_ACCELEROMETER_ORIENTATION=%s", orientation_to_string(new));
puts(text);
}
static void help(void)
{
printf("Usage: accelerometer [options] <device path>\n"
" --debug debug to stderr\n"
" --help print this help text\n\n");
printf("Usage: accelerometer [options] <device path>\n"
" --debug debug to stderr\n"
" --help print this help text\n\n");
}
int main (int argc, char** argv)
{
struct udev *udev;
struct udev_device *dev;
struct udev *udev;
struct udev_device *dev;
static const struct option options[] = {
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
static const struct option options[] = {
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
char devpath[PATH_MAX];
char *devnode;
const char *id_path;
struct udev_enumerate *enumerate;
struct udev_list_entry *list_entry;
char devpath[PATH_MAX];
char *devnode;
const char *id_path;
struct udev_enumerate *enumerate;
struct udev_list_entry *list_entry;
udev = udev_new();
if (udev == NULL)
return 1;
udev = udev_new();
if (udev == NULL)
return 1;
udev_log_init("input_id");
udev_set_log_fn(udev, log_fn);
udev_log_init("input_id");
udev_set_log_fn(udev, log_fn);
/* CLI argument parsing */
while (1) {
int option;
/* CLI argument parsing */
while (1) {
int option;
option = getopt_long(argc, argv, "dxh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "dxh", options, NULL);
if (option == -1)
break;
switch (option) {
case 'd':
debug = 1;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
help();
exit(0);
default:
exit(1);
}
}
switch (option) {
case 'd':
debug = 1;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
help();
exit(0);
default:
exit(1);
}
}
if (argv[optind] == NULL) {
help();
exit(1);
}
if (argv[optind] == NULL) {
help();
exit(1);
}
/* get the device */
snprintf(devpath, sizeof(devpath), "%s/%s", udev_get_sys_path(udev), argv[optind]);
dev = udev_device_new_from_syspath(udev, devpath);
if (dev == NULL) {
fprintf(stderr, "unable to access '%s'\n", devpath);
return 1;
}
/* get the device */
snprintf(devpath, sizeof(devpath), "%s/%s", udev_get_sys_path(udev), argv[optind]);
dev = udev_device_new_from_syspath(udev, devpath);
if (dev == NULL) {
fprintf(stderr, "unable to access '%s'\n", devpath);
return 1;
}
id_path = udev_device_get_property_value(dev, "ID_PATH");
if (id_path == NULL) {
fprintf (stderr, "unable to get property ID_PATH for '%s'", devpath);
return 0;
}
id_path = udev_device_get_property_value(dev, "ID_PATH");
if (id_path == NULL) {
fprintf (stderr, "unable to get property ID_PATH for '%s'", devpath);
return 0;
}
/* Get the children devices and find the devnode
* FIXME: use udev_enumerate_add_match_children() instead
* when it's available */
devnode = NULL;
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_property(enumerate, "ID_PATH", id_path);
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
const char *node;
/* Get the children devices and find the devnode
* FIXME: use udev_enumerate_add_match_children() instead
* when it's available */
devnode = NULL;
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_property(enumerate, "ID_PATH", id_path);
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
const char *node;
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device == NULL)
continue;
/* Already found it */
if (devnode != NULL) {
udev_device_unref(device);
continue;
}
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device == NULL)
continue;
/* Already found it */
if (devnode != NULL) {
udev_device_unref(device);
continue;
}
node = udev_device_get_devnode(device);
if (node == NULL) {
udev_device_unref(device);
continue;
}
/* Use the event sub-device */
if (strstr(node, "/event") == NULL) {
udev_device_unref(device);
continue;
}
node = udev_device_get_devnode(device);
if (node == NULL) {
udev_device_unref(device);
continue;
}
/* Use the event sub-device */
if (strstr(node, "/event") == NULL) {
udev_device_unref(device);
continue;
}
devnode = strdup(node);
udev_device_unref(device);
}
devnode = strdup(node);
udev_device_unref(device);
}
if (devnode == NULL) {
fprintf(stderr, "unable to get device node for '%s'\n", devpath);
return 0;
}
if (devnode == NULL) {
fprintf(stderr, "unable to get device node for '%s'\n", devpath);
return 0;
}
info(udev, "Opening accelerometer device %s\n", devnode);
test_orientation(udev, dev, devnode);
free(devnode);
info(udev, "Opening accelerometer device %s\n", devnode);
test_orientation(udev, dev, devnode);
free(devnode);
return 0;
return 0;
}
+559 -559
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+285 -285
View File
@@ -34,19 +34,19 @@
#include "libudev.h"
#include "libudev-private.h"
#define BUFSIZE 16
#define UDEV_ALARM_TIMEOUT 180
#define BUFSIZE 16
#define UDEV_ALARM_TIMEOUT 180
enum collect_state {
STATE_NONE,
STATE_OLD,
STATE_CONFIRMED,
STATE_NONE,
STATE_OLD,
STATE_CONFIRMED,
};
struct _mate {
struct udev_list_node node;
char *name;
enum collect_state state;
struct udev_list_node node;
char *name;
enum collect_state state;
};
static struct udev_list_node bunch;
@@ -57,29 +57,29 @@ static size_t bufsize = BUFSIZE;
static struct _mate *node_to_mate(struct udev_list_node *node)
{
char *mate;
char *mate;
mate = (char *)node;
mate -= offsetof(struct _mate, node);
return (struct _mate *)mate;
mate = (char *)node;
mate -= offsetof(struct _mate, node);
return (struct _mate *)mate;
}
static void sig_alrm(int signo)
{
exit(4);
exit(4);
}
static void usage(void)
{
printf("usage: collect [--add|--remove] [--debug] <checkpoint> <id> <idlist>\n"
"\n"
" Adds ID <id> to the list governed by <checkpoint>.\n"
" <id> must be part of the list <idlist>.\n"
" If all IDs given by <idlist> are listed (ie collect has been\n"
" invoked for each ID in <idlist>) collect returns 0, the\n"
" number of missing IDs otherwise.\n"
" On error a negative number is returned.\n"
"\n");
printf("usage: collect [--add|--remove] [--debug] <checkpoint> <id> <idlist>\n"
"\n"
" Adds ID <id> to the list governed by <checkpoint>.\n"
" <id> must be part of the list <idlist>.\n"
" If all IDs given by <idlist> are listed (ie collect has been\n"
" invoked for each ID in <idlist>) collect returns 0, the\n"
" number of missing IDs otherwise.\n"
" On error a negative number is returned.\n"
"\n");
}
/*
@@ -89,34 +89,34 @@ static void usage(void)
*/
static int prepare(char *dir, char *filename)
{
struct stat statbuf;
char buf[512];
int fd;
struct stat statbuf;
char buf[512];
int fd;
if (stat(dir, &statbuf) < 0)
mkdir(dir, 0700);
if (stat(dir, &statbuf) < 0)
mkdir(dir, 0700);
sprintf(buf, "%s/%s", dir, filename);
sprintf(buf, "%s/%s", dir, filename);
fd = open(buf,O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (fd < 0)
fprintf(stderr, "Cannot open %s: %s\n", buf, strerror(errno));
fd = open(buf,O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (fd < 0)
fprintf(stderr, "Cannot open %s: %s\n", buf, strerror(errno));
if (lockf(fd,F_TLOCK,0) < 0) {
if (debug)
fprintf(stderr, "Lock taken, wait for %d seconds\n", UDEV_ALARM_TIMEOUT);
if (errno == EAGAIN || errno == EACCES) {
alarm(UDEV_ALARM_TIMEOUT);
lockf(fd, F_LOCK, 0);
if (debug)
fprintf(stderr, "Acquired lock on %s\n", buf);
} else {
if (debug)
fprintf(stderr, "Could not get lock on %s: %s\n", buf, strerror(errno));
}
}
if (lockf(fd,F_TLOCK,0) < 0) {
if (debug)
fprintf(stderr, "Lock taken, wait for %d seconds\n", UDEV_ALARM_TIMEOUT);
if (errno == EAGAIN || errno == EACCES) {
alarm(UDEV_ALARM_TIMEOUT);
lockf(fd, F_LOCK, 0);
if (debug)
fprintf(stderr, "Acquired lock on %s\n", buf);
} else {
if (debug)
fprintf(stderr, "Could not get lock on %s: %s\n", buf, strerror(errno));
}
}
return fd;
return fd;
}
/*
@@ -136,58 +136,58 @@ static int prepare(char *dir, char *filename)
*/
static int checkout(int fd)
{
int len;
char *buf, *ptr, *word = NULL;
struct _mate *him;
int len;
char *buf, *ptr, *word = NULL;
struct _mate *him;
restart:
len = bufsize >> 1;
buf = calloc(1,bufsize + 1);
if (!buf) {
fprintf(stderr, "Out of memory\n");
return -1;
}
memset(buf, ' ', bufsize);
ptr = buf + len;
while ((read(fd, buf + len, len)) > 0) {
while (ptr && *ptr) {
word = ptr;
ptr = strpbrk(word," \n\t\r");
if (!ptr && word < (buf + len)) {
bufsize = bufsize << 1;
if (debug)
fprintf(stderr, "ID overflow, restarting with size %zi\n", bufsize);
free(buf);
lseek(fd, 0, SEEK_SET);
goto restart;
}
if (ptr) {
*ptr = '\0';
ptr++;
if (!strlen(word))
continue;
len = bufsize >> 1;
buf = calloc(1,bufsize + 1);
if (!buf) {
fprintf(stderr, "Out of memory\n");
return -1;
}
memset(buf, ' ', bufsize);
ptr = buf + len;
while ((read(fd, buf + len, len)) > 0) {
while (ptr && *ptr) {
word = ptr;
ptr = strpbrk(word," \n\t\r");
if (!ptr && word < (buf + len)) {
bufsize = bufsize << 1;
if (debug)
fprintf(stderr, "ID overflow, restarting with size %zi\n", bufsize);
free(buf);
lseek(fd, 0, SEEK_SET);
goto restart;
}
if (ptr) {
*ptr = '\0';
ptr++;
if (!strlen(word))
continue;
if (debug)
fprintf(stderr, "Found word %s\n", word);
him = malloc(sizeof (struct _mate));
him->name = strdup(word);
him->state = STATE_OLD;
udev_list_node_append(&him->node, &bunch);
word = NULL;
}
}
memcpy(buf, buf + len, len);
memset(buf + len, ' ', len);
if (debug)
fprintf(stderr, "Found word %s\n", word);
him = malloc(sizeof (struct _mate));
him->name = strdup(word);
him->state = STATE_OLD;
udev_list_node_append(&him->node, &bunch);
word = NULL;
}
}
memcpy(buf, buf + len, len);
memset(buf + len, ' ', len);
if (!ptr)
ptr = word;
if (!ptr)
break;
ptr -= len;
}
if (!ptr)
ptr = word;
if (!ptr)
break;
ptr -= len;
}
free(buf);
return 0;
free(buf);
return 0;
}
/*
@@ -198,22 +198,22 @@ static int checkout(int fd)
*/
static void invite(char *us)
{
struct udev_list_node *him_node;
struct _mate *who = NULL;
struct udev_list_node *him_node;
struct _mate *who = NULL;
if (debug)
fprintf(stderr, "Adding ID '%s'\n", us);
if (debug)
fprintf(stderr, "Adding ID '%s'\n", us);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
if (!strcmp(him->name, us)) {
him->state = STATE_CONFIRMED;
who = him;
}
}
if (debug && !who)
fprintf(stderr, "ID '%s' not in database\n", us);
if (!strcmp(him->name, us)) {
him->state = STATE_CONFIRMED;
who = him;
}
}
if (debug && !who)
fprintf(stderr, "ID '%s' not in database\n", us);
}
@@ -226,22 +226,22 @@ static void invite(char *us)
*/
static void reject(char *us)
{
struct udev_list_node *him_node;
struct _mate *who = NULL;
struct udev_list_node *him_node;
struct _mate *who = NULL;
if (debug)
fprintf(stderr, "Removing ID '%s'\n", us);
if (debug)
fprintf(stderr, "Removing ID '%s'\n", us);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
if (!strcmp(him->name, us)) {
him->state = STATE_NONE;
who = him;
}
}
if (debug && !who)
fprintf(stderr, "ID '%s' not in database\n", us);
if (!strcmp(him->name, us)) {
him->state = STATE_NONE;
who = him;
}
}
if (debug && !who)
fprintf(stderr, "ID '%s' not in database\n", us);
}
/*
@@ -252,18 +252,18 @@ static void reject(char *us)
*/
static void kickout(void)
{
struct udev_list_node *him_node;
struct udev_list_node *tmp;
struct udev_list_node *him_node;
struct udev_list_node *tmp;
udev_list_node_foreach_safe(him_node, tmp, &bunch) {
struct _mate *him = node_to_mate(him_node);
udev_list_node_foreach_safe(him_node, tmp, &bunch) {
struct _mate *him = node_to_mate(him_node);
if (him->state == STATE_OLD) {
udev_list_node_remove(&him->node);
free(him->name);
free(him);
}
}
if (him->state == STATE_OLD) {
udev_list_node_remove(&him->node);
free(him->name);
free(him);
}
}
}
/*
@@ -273,38 +273,38 @@ static void kickout(void)
*/
static int missing(int fd)
{
char *buf;
int ret = 0;
struct udev_list_node *him_node;
char *buf;
int ret = 0;
struct udev_list_node *him_node;
buf = malloc(bufsize);
if (!buf)
return -1;
buf = malloc(bufsize);
if (!buf)
return -1;
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
if (him->state == STATE_NONE) {
ret++;
} else {
while (strlen(him->name)+1 >= bufsize) {
char *tmpbuf;
if (him->state == STATE_NONE) {
ret++;
} else {
while (strlen(him->name)+1 >= bufsize) {
char *tmpbuf;
bufsize = bufsize << 1;
tmpbuf = realloc(buf, bufsize);
if (!tmpbuf) {
free(buf);
return -1;
}
buf = tmpbuf;
}
snprintf(buf, strlen(him->name)+2, "%s ", him->name);
write(fd, buf, strlen(buf));
}
}
bufsize = bufsize << 1;
tmpbuf = realloc(buf, bufsize);
if (!tmpbuf) {
free(buf);
return -1;
}
buf = tmpbuf;
}
snprintf(buf, strlen(him->name)+2, "%s ", him->name);
write(fd, buf, strlen(buf));
}
}
free(buf);
return ret;
free(buf);
return ret;
}
/*
@@ -314,160 +314,160 @@ static int missing(int fd)
*/
static void everybody(void)
{
struct udev_list_node *him_node;
const char *state = "";
struct udev_list_node *him_node;
const char *state = "";
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
switch (him->state) {
case STATE_NONE:
state = "none";
break;
case STATE_OLD:
state = "old";
break;
case STATE_CONFIRMED:
state = "confirmed";
break;
}
fprintf(stderr, "ID: %s=%s\n", him->name, state);
}
switch (him->state) {
case STATE_NONE:
state = "none";
break;
case STATE_OLD:
state = "old";
break;
case STATE_CONFIRMED:
state = "confirmed";
break;
}
fprintf(stderr, "ID: %s=%s\n", him->name, state);
}
}
int main(int argc, char **argv)
{
struct udev *udev;
static const struct option options[] = {
{ "add", no_argument, NULL, 'a' },
{ "remove", no_argument, NULL, 'r' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
int argi;
char *checkpoint, *us;
int fd;
int i;
int ret = EXIT_SUCCESS;
int prune = 0;
char tmpdir[UTIL_PATH_SIZE];
struct udev *udev;
static const struct option options[] = {
{ "add", no_argument, NULL, 'a' },
{ "remove", no_argument, NULL, 'r' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
int argi;
char *checkpoint, *us;
int fd;
int i;
int ret = EXIT_SUCCESS;
int prune = 0;
char tmpdir[UTIL_PATH_SIZE];
udev = udev_new();
if (udev == NULL) {
ret = EXIT_FAILURE;
goto exit;
}
udev = udev_new();
if (udev == NULL) {
ret = EXIT_FAILURE;
goto exit;
}
while (1) {
int option;
while (1) {
int option;
option = getopt_long(argc, argv, "ardh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "ardh", options, NULL);
if (option == -1)
break;
switch (option) {
case 'a':
prune = 0;
break;
case 'r':
prune = 1;
break;
case 'd':
debug = 1;
break;
case 'h':
usage();
goto exit;
default:
ret = 1;
goto exit;
}
}
switch (option) {
case 'a':
prune = 0;
break;
case 'r':
prune = 1;
break;
case 'd':
debug = 1;
break;
case 'h':
usage();
goto exit;
default:
ret = 1;
goto exit;
}
}
argi = optind;
if (argi + 2 > argc) {
printf("Missing parameter(s)\n");
ret = 1;
goto exit;
}
checkpoint = argv[argi++];
us = argv[argi++];
argi = optind;
if (argi + 2 > argc) {
printf("Missing parameter(s)\n");
ret = 1;
goto exit;
}
checkpoint = argv[argi++];
us = argv[argi++];
if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
fprintf(stderr, "Cannot set SIGALRM: %s\n", strerror(errno));
ret = 2;
goto exit;
}
if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
fprintf(stderr, "Cannot set SIGALRM: %s\n", strerror(errno));
ret = 2;
goto exit;
}
udev_list_node_init(&bunch);
udev_list_node_init(&bunch);
if (debug)
fprintf(stderr, "Using checkpoint '%s'\n", checkpoint);
if (debug)
fprintf(stderr, "Using checkpoint '%s'\n", checkpoint);
util_strscpyl(tmpdir, sizeof(tmpdir), udev_get_run_path(udev), "/collect", NULL);
fd = prepare(tmpdir, checkpoint);
if (fd < 0) {
ret = 3;
goto out;
}
util_strscpyl(tmpdir, sizeof(tmpdir), udev_get_run_path(udev), "/collect", NULL);
fd = prepare(tmpdir, checkpoint);
if (fd < 0) {
ret = 3;
goto out;
}
if (checkout(fd) < 0) {
ret = 2;
goto out;
}
if (checkout(fd) < 0) {
ret = 2;
goto out;
}
for (i = argi; i < argc; i++) {
struct udev_list_node *him_node;
struct _mate *who;
for (i = argi; i < argc; i++) {
struct udev_list_node *him_node;
struct _mate *who;
who = NULL;
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
who = NULL;
udev_list_node_foreach(him_node, &bunch) {
struct _mate *him = node_to_mate(him_node);
if (!strcmp(him->name, argv[i]))
who = him;
}
if (!who) {
struct _mate *him;
if (!strcmp(him->name, argv[i]))
who = him;
}
if (!who) {
struct _mate *him;
if (debug)
fprintf(stderr, "ID %s: not in database\n", argv[i]);
him = malloc(sizeof (struct _mate));
him->name = malloc(strlen(argv[i]) + 1);
strcpy(him->name, argv[i]);
him->state = STATE_NONE;
udev_list_node_append(&him->node, &bunch);
} else {
if (debug)
fprintf(stderr, "ID %s: found in database\n", argv[i]);
who->state = STATE_CONFIRMED;
}
}
if (debug)
fprintf(stderr, "ID %s: not in database\n", argv[i]);
him = malloc(sizeof (struct _mate));
him->name = malloc(strlen(argv[i]) + 1);
strcpy(him->name, argv[i]);
him->state = STATE_NONE;
udev_list_node_append(&him->node, &bunch);
} else {
if (debug)
fprintf(stderr, "ID %s: found in database\n", argv[i]);
who->state = STATE_CONFIRMED;
}
}
if (prune)
reject(us);
else
invite(us);
if (prune)
reject(us);
else
invite(us);
if (debug) {
everybody();
fprintf(stderr, "Prune lists\n");
}
kickout();
if (debug) {
everybody();
fprintf(stderr, "Prune lists\n");
}
kickout();
lseek(fd, 0, SEEK_SET);
ftruncate(fd, 0);
ret = missing(fd);
lseek(fd, 0, SEEK_SET);
ftruncate(fd, 0);
ret = missing(fd);
lockf(fd, F_ULOCK, 0);
close(fd);
lockf(fd, F_ULOCK, 0);
close(fd);
out:
if (debug)
everybody();
if (ret >= 0)
printf("COLLECT_%s=%d\n", checkpoint, ret);
if (debug)
everybody();
if (ret >= 0)
printf("COLLECT_%s=%d\n", checkpoint, ret);
exit:
udev_unref(udev);
return ret;
udev_unref(udev);
return ret;
}
+134 -134
View File
@@ -36,161 +36,161 @@
#include "libudev-private.h"
static void log_fn(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)
const char *file, int line, const char *fn,
const char *format, va_list args)
{
vsyslog(priority, format, args);
vsyslog(priority, format, args);
}
int main(int argc, char *argv[])
{
struct udev *udev;
const char *node = NULL;
int i;
int export = 0;
uint32_t disk_id;
uint16_t mbr_valid;
struct dirent *dent;
int disk_fd;
int sysfs_fd;
DIR *dir = NULL;
int rc = 1;
char filename[UTIL_PATH_SIZE];
char match[UTIL_PATH_SIZE];
struct udev *udev;
const char *node = NULL;
int i;
int export = 0;
uint32_t disk_id;
uint16_t mbr_valid;
struct dirent *dent;
int disk_fd;
int sysfs_fd;
DIR *dir = NULL;
int rc = 1;
char filename[UTIL_PATH_SIZE];
char match[UTIL_PATH_SIZE];
udev = udev_new();
if (udev == NULL)
goto exit;
udev = udev_new();
if (udev == NULL)
goto exit;
udev_log_init("edd_id");
udev_set_log_fn(udev, log_fn);
udev_log_init("edd_id");
udev_set_log_fn(udev, log_fn);
for (i = 1 ; i < argc; i++) {
char *arg = argv[i];
for (i = 1 ; i < argc; i++) {
char *arg = argv[i];
if (strcmp(arg, "--export") == 0) {
export = 1;
} else
node = arg;
}
if (node == NULL) {
err(udev, "no node specified\n");
fprintf(stderr, "no node specified\n");
goto exit;
}
if (strcmp(arg, "--export") == 0) {
export = 1;
} else
node = arg;
}
if (node == NULL) {
err(udev, "no node specified\n");
fprintf(stderr, "no node specified\n");
goto exit;
}
/* check for kernel support */
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), "/firmware/edd", NULL);
dir = opendir(filename);
if (dir == NULL) {
info(udev, "no kernel EDD support\n");
fprintf(stderr, "no kernel EDD support\n");
rc = 2;
goto exit;
}
/* check for kernel support */
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), "/firmware/edd", NULL);
dir = opendir(filename);
if (dir == NULL) {
info(udev, "no kernel EDD support\n");
fprintf(stderr, "no kernel EDD support\n");
rc = 2;
goto exit;
}
disk_fd = open(node, O_RDONLY);
if (disk_fd < 0) {
info(udev, "unable to open '%s'\n", node);
fprintf(stderr, "unable to open '%s'\n", node);
rc = 3;
goto closedir;
}
disk_fd = open(node, O_RDONLY);
if (disk_fd < 0) {
info(udev, "unable to open '%s'\n", node);
fprintf(stderr, "unable to open '%s'\n", node);
rc = 3;
goto closedir;
}
/* check for valid MBR signature */
if (lseek(disk_fd, 510, SEEK_SET) < 0) {
info(udev, "seek to MBR validity failed '%s'\n", node);
rc = 4;
goto close;
}
if (read(disk_fd, &mbr_valid, sizeof(mbr_valid)) != sizeof(mbr_valid)) {
info(udev, "read MBR validity failed '%s'\n", node);
rc = 5;
goto close;
}
if (mbr_valid != 0xAA55) {
fprintf(stderr, "no valid MBR signature '%s'\n", node);
info(udev, "no valid MBR signature '%s'\n", node);
rc=6;
goto close;
}
/* check for valid MBR signature */
if (lseek(disk_fd, 510, SEEK_SET) < 0) {
info(udev, "seek to MBR validity failed '%s'\n", node);
rc = 4;
goto close;
}
if (read(disk_fd, &mbr_valid, sizeof(mbr_valid)) != sizeof(mbr_valid)) {
info(udev, "read MBR validity failed '%s'\n", node);
rc = 5;
goto close;
}
if (mbr_valid != 0xAA55) {
fprintf(stderr, "no valid MBR signature '%s'\n", node);
info(udev, "no valid MBR signature '%s'\n", node);
rc=6;
goto close;
}
/* read EDD signature */
if (lseek(disk_fd, 440, SEEK_SET) < 0) {
info(udev, "seek to signature failed '%s'\n", node);
rc = 7;
goto close;
}
if (read(disk_fd, &disk_id, sizeof(disk_id)) != sizeof(disk_id)) {
info(udev, "read signature failed '%s'\n", node);
rc = 8;
goto close;
}
/* all zero is invalid */
info(udev, "read id 0x%08x from '%s'\n", disk_id, node);
if (disk_id == 0) {
fprintf(stderr, "no EDD signature '%s'\n", node);
info(udev, "'%s' signature is zero\n", node);
rc = 9;
goto close;
}
/* read EDD signature */
if (lseek(disk_fd, 440, SEEK_SET) < 0) {
info(udev, "seek to signature failed '%s'\n", node);
rc = 7;
goto close;
}
if (read(disk_fd, &disk_id, sizeof(disk_id)) != sizeof(disk_id)) {
info(udev, "read signature failed '%s'\n", node);
rc = 8;
goto close;
}
/* all zero is invalid */
info(udev, "read id 0x%08x from '%s'\n", disk_id, node);
if (disk_id == 0) {
fprintf(stderr, "no EDD signature '%s'\n", node);
info(udev, "'%s' signature is zero\n", node);
rc = 9;
goto close;
}
/* lookup signature in sysfs to determine the name */
match[0] = '\0';
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
char sysfs_id_buf[256];
uint32_t sysfs_id;
ssize_t size;
/* lookup signature in sysfs to determine the name */
match[0] = '\0';
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
char sysfs_id_buf[256];
uint32_t sysfs_id;
ssize_t size;
if (dent->d_name[0] == '.')
continue;
if (dent->d_name[0] == '.')
continue;
util_strscpyl(filename, sizeof(filename), dent->d_name, "/mbr_signature", NULL);
sysfs_fd = openat(dirfd(dir), filename, O_RDONLY);
if (sysfs_fd < 0) {
info(udev, "unable to open sysfs '%s'\n", filename);
continue;
}
util_strscpyl(filename, sizeof(filename), dent->d_name, "/mbr_signature", NULL);
sysfs_fd = openat(dirfd(dir), filename, O_RDONLY);
if (sysfs_fd < 0) {
info(udev, "unable to open sysfs '%s'\n", filename);
continue;
}
size = read(sysfs_fd, sysfs_id_buf, sizeof(sysfs_id_buf)-1);
close(sysfs_fd);
if (size <= 0) {
info(udev, "read sysfs '%s' failed\n", filename);
continue;
}
sysfs_id_buf[size] = '\0';
info(udev, "read '%s' from '%s'\n", sysfs_id_buf, filename);
sysfs_id = strtoul(sysfs_id_buf, NULL, 16);
size = read(sysfs_fd, sysfs_id_buf, sizeof(sysfs_id_buf)-1);
close(sysfs_fd);
if (size <= 0) {
info(udev, "read sysfs '%s' failed\n", filename);
continue;
}
sysfs_id_buf[size] = '\0';
info(udev, "read '%s' from '%s'\n", sysfs_id_buf, filename);
sysfs_id = strtoul(sysfs_id_buf, NULL, 16);
/* look for matching value, that appears only once */
if (disk_id == sysfs_id) {
if (match[0] == '\0') {
/* store id */
util_strscpy(match, sizeof(match), dent->d_name);
} else {
/* error, same signature for another device */
info(udev, "'%s' does not have a unique signature\n", node);
fprintf(stderr, "'%s' does not have a unique signature\n", node);
rc = 10;
goto exit;
}
}
}
/* look for matching value, that appears only once */
if (disk_id == sysfs_id) {
if (match[0] == '\0') {
/* store id */
util_strscpy(match, sizeof(match), dent->d_name);
} else {
/* error, same signature for another device */
info(udev, "'%s' does not have a unique signature\n", node);
fprintf(stderr, "'%s' does not have a unique signature\n", node);
rc = 10;
goto exit;
}
}
}
if (match[0] != '\0') {
if (export)
printf("ID_EDD=%s\n", match);
else
printf("%s\n", match);
rc = 0;
}
if (match[0] != '\0') {
if (export)
printf("ID_EDD=%s\n", match);
else
printf("%s\n", match);
rc = 0;
}
close:
close(disk_fd);
close(disk_fd);
closedir:
closedir(dir);
closedir(dir);
exit:
udev_unref(udev);
udev_log_close();
return rc;
udev_unref(udev);
udev_log_close();
return rc;
}
+115 -115
View File
@@ -34,12 +34,12 @@
#include "libudev-private.h"
static char *table[] = {
"", "d360", "h1200", "u360", "u720", "h360", "h720",
"u1440", "u2880", "CompaQ", "h1440", "u1680", "h410",
"u820", "h1476", "u1722", "h420", "u830", "h1494", "u1743",
"h880", "u1040", "u1120", "h1600", "u1760", "u1920",
"u3200", "u3520", "u3840", "u1840", "u800", "u1600",
NULL
"", "d360", "h1200", "u360", "u720", "h360", "h720",
"u1440", "u2880", "CompaQ", "h1440", "u1680", "h410",
"u820", "h1476", "u1722", "h420", "u830", "h1494", "u1743",
"h880", "u1040", "u1120", "h1600", "u1760", "u1920",
"u3200", "u3520", "u3840", "u1840", "u800", "u1600",
NULL
};
static int t360[] = { 1, 0 };
@@ -48,130 +48,130 @@ static int t3in[] = { 8, 9, 26, 27, 28, 7, 11, 15, 19, 24, 25, 29, 31, 3, 4, 13,
static int *table_sup[] = { NULL, t360, t1200, t3in+5+8, t3in+5, t3in, t3in };
static void log_fn(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)
const char *file, int line, const char *fn,
const char *format, va_list args)
{
vsyslog(priority, format, args);
vsyslog(priority, format, args);
}
int main(int argc, char **argv)
{
struct udev *udev;
char *dev;
char *devname;
char node[64];
int type = 0, i, fdnum, c;
int major = 2, minor;
uid_t uid = 0;
gid_t gid = 0;
mode_t mode = 0660;
int create_nodes = 0;
int print_nodes = 0;
int is_err = 0;
struct udev *udev;
char *dev;
char *devname;
char node[64];
int type = 0, i, fdnum, c;
int major = 2, minor;
uid_t uid = 0;
gid_t gid = 0;
mode_t mode = 0660;
int create_nodes = 0;
int print_nodes = 0;
int is_err = 0;
udev = udev_new();
if (udev == NULL)
goto exit;
udev = udev_new();
if (udev == NULL)
goto exit;
udev_log_init("create_floppy_devices");
udev_set_log_fn(udev, log_fn);
udev_selinux_init(udev);
udev_log_init("create_floppy_devices");
udev_set_log_fn(udev, log_fn);
udev_selinux_init(udev);
while ((c = getopt(argc, argv, "cudm:U:G:M:t:")) != -1) {
switch (c) {
case 'c':
create_nodes = 1;
break;
case 'd':
print_nodes = 1;
break;
case 'U':
uid = util_lookup_user(udev, optarg);
break;
case 'G':
gid = util_lookup_group(udev, optarg);
break;
case 'M':
mode = strtol(optarg, NULL, 0);
mode = mode & 0666;
break;
case 'm':
major = strtol(optarg, NULL, 0);
break;
case 't':
type = strtol(optarg, NULL, 0);
break;
default:
is_err++;
break;
}
}
while ((c = getopt(argc, argv, "cudm:U:G:M:t:")) != -1) {
switch (c) {
case 'c':
create_nodes = 1;
break;
case 'd':
print_nodes = 1;
break;
case 'U':
uid = util_lookup_user(udev, optarg);
break;
case 'G':
gid = util_lookup_group(udev, optarg);
break;
case 'M':
mode = strtol(optarg, NULL, 0);
mode = mode & 0666;
break;
case 'm':
major = strtol(optarg, NULL, 0);
break;
case 't':
type = strtol(optarg, NULL, 0);
break;
default:
is_err++;
break;
}
}
if (is_err || optind >= argc) {
printf("Usage: %s [OPTION] device\n"
" -c create\n"
" -d debug\n"
" -m Major number\n"
" -t floppy type number\n"
" -U device node user ownership\n"
" -G device node group owner\n"
" -M device node mode\n"
"\n", argv[0]);
return 1;
}
if (is_err || optind >= argc) {
printf("Usage: %s [OPTION] device\n"
" -c create\n"
" -d debug\n"
" -m Major number\n"
" -t floppy type number\n"
" -U device node user ownership\n"
" -G device node group owner\n"
" -M device node mode\n"
"\n", argv[0]);
return 1;
}
dev = argv[optind];
devname = strrchr(dev, '/');
if (devname != NULL)
devname = &devname[1];
else
devname = dev;
if (strncmp(devname, "fd", 2) != 0) {
fprintf(stderr,"Device '%s' is not a floppy device\n", dev);
return 1;
}
dev = argv[optind];
devname = strrchr(dev, '/');
if (devname != NULL)
devname = &devname[1];
else
devname = dev;
if (strncmp(devname, "fd", 2) != 0) {
fprintf(stderr,"Device '%s' is not a floppy device\n", dev);
return 1;
}
fdnum = strtol(&devname[2], NULL, 10);
if (fdnum < 0 || fdnum > 7) {
fprintf(stderr,"Floppy device number %d out of range (0-7)\n", fdnum);
return 1;
}
if (fdnum > 3)
fdnum += 124;
fdnum = strtol(&devname[2], NULL, 10);
if (fdnum < 0 || fdnum > 7) {
fprintf(stderr,"Floppy device number %d out of range (0-7)\n", fdnum);
return 1;
}
if (fdnum > 3)
fdnum += 124;
if (major < 1) {
fprintf(stderr,"Invalid major number %d\n", major);
return 1;
}
if (major < 1) {
fprintf(stderr,"Invalid major number %d\n", major);
return 1;
}
if (type < 0 || type >= (int) ARRAY_SIZE(table_sup)) {
fprintf(stderr,"Invalid CMOS type %d\n", type);
return 1;
}
if (type < 0 || type >= (int) ARRAY_SIZE(table_sup)) {
fprintf(stderr,"Invalid CMOS type %d\n", type);
return 1;
}
if (type == 0)
return 0;
if (type == 0)
return 0;
i = 0;
while (table_sup[type][i]) {
sprintf(node, "%s%s", dev, table[table_sup[type][i]]);
minor = (table_sup[type][i] << 2) + fdnum;
if (print_nodes)
printf("%s b %.4o %d %d\n", node, mode, major, minor);
if (create_nodes) {
unlink(node);
udev_selinux_setfscreatecon(udev, node, S_IFBLK | mode);
mknod(node, S_IFBLK | mode, makedev(major,minor));
udev_selinux_resetfscreatecon(udev);
chown(node, uid, gid);
chmod(node, S_IFBLK | mode);
}
i++;
}
i = 0;
while (table_sup[type][i]) {
sprintf(node, "%s%s", dev, table[table_sup[type][i]]);
minor = (table_sup[type][i] << 2) + fdnum;
if (print_nodes)
printf("%s b %.4o %d %d\n", node, mode, major, minor);
if (create_nodes) {
unlink(node);
udev_selinux_setfscreatecon(udev, node, S_IFBLK | mode);
mknod(node, S_IFBLK | mode, makedev(major,minor));
udev_selinux_resetfscreatecon(udev);
chown(node, uid, gid);
chmod(node, S_IFBLK | mode);
}
i++;
}
udev_selinux_exit(udev);
udev_unref(udev);
udev_log_close();
udev_selinux_exit(udev);
udev_unref(udev);
udev_log_close();
exit:
return 0;
return 0;
}
+6 -6
View File
@@ -1,5 +1,5 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
@@ -10,7 +10,7 @@
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@@ -112,7 +112,7 @@ modification follow. Pay close attention to the difference between a
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
@@ -432,7 +432,7 @@ decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
@@ -455,7 +455,7 @@ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
+6 -6
View File
@@ -78,14 +78,14 @@ expand_content_files=
# e.g. GTKDOC_CFLAGS=-I$(top_srcdir) -I$(top_builddir) $(GTK_DEBUG_FLAGS)
# e.g. GTKDOC_LIBS=$(top_builddir)/gtk/$(gtktargetlib)
GTKDOC_CFLAGS = \
$(DBUS_GLIB_CFLAGS) \
$(GLIB_CFLAGS) \
-I$(top_srcdir)/src/extras/gudev \
-I$(top_builddir)/src/extras/gudev
$(DBUS_GLIB_CFLAGS) \
$(GLIB_CFLAGS) \
-I$(top_srcdir)/src/extras/gudev \
-I$(top_builddir)/src/extras/gudev
GTKDOC_LIBS = \
$(GLIB_LIBS) \
$(top_builddir)/src/extras/gudev/libgudev-1.0.la
$(GLIB_LIBS) \
$(top_builddir)/src/extras/gudev/libgudev-1.0.la
# This includes the standard gtk-doc make rules, copied by gtkdocize.
include $(top_srcdir)/gtk-doc.make
+38 -38
View File
@@ -9,22 +9,22 @@
<releaseinfo>For GUdev version &version;</releaseinfo>
<authorgroup>
<author>
<firstname>David</firstname>
<surname>Zeuthen</surname>
<affiliation>
<address>
<email>davidz@redhat.com</email>
</address>
</affiliation>
<firstname>David</firstname>
<surname>Zeuthen</surname>
<affiliation>
<address>
<email>davidz@redhat.com</email>
</address>
</affiliation>
</author>
<author>
<firstname>Bastien</firstname>
<surname>Nocera</surname>
<affiliation>
<address>
<email>hadess@hadess.net</email>
</address>
</affiliation>
<firstname>Bastien</firstname>
<surname>Nocera</surname>
<affiliation>
<address>
<email>hadess@hadess.net</email>
</address>
</affiliation>
</author>
</authorgroup>
@@ -35,32 +35,32 @@
<legalnotice>
<para>
Permission is granted to copy, distribute and/or modify this
document under the terms of the <citetitle>GNU Free
Documentation License</citetitle>, Version 1.1 or any later
version published by the Free Software Foundation with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. You may obtain a copy of the <citetitle>GNU Free
Documentation License</citetitle> from the Free Software
Foundation by visiting <ulink type="http"
url="http://www.fsf.org">their Web site</ulink> or by writing
to:
Permission is granted to copy, distribute and/or modify this
document under the terms of the <citetitle>GNU Free
Documentation License</citetitle>, Version 1.1 or any later
version published by the Free Software Foundation with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover
Texts. You may obtain a copy of the <citetitle>GNU Free
Documentation License</citetitle> from the Free Software
Foundation by visiting <ulink type="http"
url="http://www.fsf.org">their Web site</ulink> or by writing
to:
<address>
The Free Software Foundation, Inc.,
<street>59 Temple Place</street> - Suite 330,
<city>Boston</city>, <state>MA</state> <postcode>02111-1307</postcode>,
<country>USA</country>
</address>
<address>
The Free Software Foundation, Inc.,
<street>59 Temple Place</street> - Suite 330,
<city>Boston</city>, <state>MA</state> <postcode>02111-1307</postcode>,
<country>USA</country>
</address>
</para>
<para>
Many of the names used by companies to distinguish their
products and services are claimed as trademarks. Where those
names appear in any freedesktop.org documentation, and those
trademarks are made aware to the members of the
freedesktop.org Project, the names have been printed in caps
or initial caps.
Many of the names used by companies to distinguish their
products and services are claimed as trademarks. Where those
names appear in any freedesktop.org documentation, and those
trademarks are made aware to the members of the
freedesktop.org Project, the names have been printed in caps
or initial caps.
</para>
</legalnotice>
</bookinfo>
@@ -69,8 +69,8 @@
<title>API Reference</title>
<partintro>
<para>
This part presents the class and function reference for the
<literal>libgudev</literal> library.
This part presents the class and function reference for the
<literal>libgudev</literal> library.
</para>
</partintro>
<xi:include href="xml/gudevclient.xml"/>
+2 -2
View File
@@ -87,8 +87,8 @@ G_DEFINE_TYPE (GUdevClient, g_udev_client, G_TYPE_OBJECT)
static gboolean
monitor_event (GIOChannel *source,
GIOCondition condition,
gpointer data)
GIOCondition condition,
gpointer data)
{
GUdevClient *client = (GUdevClient *) data;
GUdevDevice *device;
+15 -15
View File
@@ -9,30 +9,30 @@ KEYMAPS_DIR=$SRCDIR/src/extras/keymap/keymaps #extras/keymap/keymaps
RULES=$SRCDIR/src/extras/keymap/95-keymap.rules
[ -e "$KEYLIST" ] || {
echo "need $KEYLIST please build first" >&2
exit 1
echo "need $KEYLIST please build first" >&2
exit 1
}
missing=$(join -v 2 <(awk '{print tolower(substr($1,5))}' $KEYLIST | sort -u) \
<(grep -hv '^#' ${KEYMAPS_DIR}/*| awk '{print $2}' | sort -u))
[ -z "$missing" ] || {
echo "ERROR: unknown key names in extras/keymap/keymaps/*:" >&2
echo "$missing" >&2
exit 1
echo "ERROR: unknown key names in extras/keymap/keymaps/*:" >&2
echo "$missing" >&2
exit 1
}
# check that all maps referred to in $RULES exist
maps=$(sed -rn '/keymap \$name/ { s/^.*\$name ([^"[:space:]]+).*$/\1/; p }' $RULES)
for m in $maps; do
# ignore inline mappings
[ "$m" = "${m#0x}" ] || continue
# ignore inline mappings
[ "$m" = "${m#0x}" ] || continue
[ -e ${KEYMAPS_DIR}/$m ] || {
echo "ERROR: unknown map name in $RULES: $m" >&2
exit 1
}
grep -q "extras/keymap/keymaps/$m\>" $SRCDIR/Makefile.am || {
echo "ERROR: map file $m is not added to Makefile.am" >&2
exit 1
}
[ -e ${KEYMAPS_DIR}/$m ] || {
echo "ERROR: unknown map name in $RULES: $m" >&2
exit 1
}
grep -q "extras/keymap/keymaps/$m\>" $SRCDIR/Makefile.am || {
echo "ERROR: map file $m is not added to Makefile.am" >&2
exit 1
}
done
+36 -39
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
#!/bin/sh -e
# Find "real" keyboard devices and print their device path.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
#
@@ -14,58 +14,55 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
set -e
# returns OK if $1 contains $2
strstr() {
[ "${1#*$2*}" != "$1" ]
[ "${1#*$2*}" != "$1" ]
}
# returns OK if $1 contains $2 at the beginning
str_starts() {
[ "${1#$2*}" != "$1" ]
[ "${1#$2*}" != "$1" ]
}
str_line_starts() {
while read a; do str_starts "$a" "$1" && return 0;done
return 1;
while read a; do str_starts "$a" "$1" && return 0;done
return 1;
}
# print a list of input devices which are keyboard-like
keyboard_devices() {
# standard AT keyboard
for dev in `udevadm trigger --dry-run --verbose --property-match=ID_INPUT_KEYBOARD=1`; do
walk=`udevadm info --attribute-walk --path=$dev`
env=`udevadm info --query=env --path=$dev`
# filter out non-event devices, such as the parent input devices which
# have no devnode
if ! echo "$env" | str_line_starts 'DEVNAME='; then
continue
fi
if strstr "$walk" 'DRIVERS=="atkbd"'; then
echo -n 'AT keyboard: '
elif echo "$env" | str_line_starts 'ID_USB_DRIVER=usbhid'; then
echo -n 'USB keyboard: '
else
echo -n 'Unknown type: '
fi
udevadm info --query=name --path=$dev
done
# standard AT keyboard
for dev in `udevadm trigger --dry-run --verbose --property-match=ID_INPUT_KEYBOARD=1`; do
walk=`udevadm info --attribute-walk --path=$dev`
env=`udevadm info --query=env --path=$dev`
# filter out non-event devices, such as the parent input devices which have no devnode
if ! echo "$env" | str_line_starts 'DEVNAME='; then
continue
fi
if strstr "$walk" 'DRIVERS=="atkbd"'; then
echo -n 'AT keyboard: '
elif echo "$env" | str_line_starts 'ID_USB_DRIVER=usbhid'; then
echo -n 'USB keyboard: '
else
echo -n 'Unknown type: '
fi
udevadm info --query=name --path=$dev
done
# modules
module=$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*Extra Buttons')
module="$module
$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*extra buttons')"
module="$module
$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='Sony Vaio Keys')"
for m in $module; do
for evdev in $m/event*/dev; do
if [ -e "$evdev" ]; then
echo -n 'module: '
udevadm info --query=name --path=${evdev%%/dev}
fi
done
done
# modules
module=$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*Extra Buttons')
module="$module
$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='*extra buttons')"
module="$module
$(udevadm trigger --verbose --dry-run --subsystem-match=input --attr-match=name='Sony Vaio Keys')"
for m in $module; do
for evdev in $m/event*/dev; do
if [ -e "$evdev" ]; then
echo -n 'module: '
udevadm info --query=name --path=${evdev%%/dev}
fi
done
done
}
keyboard_devices
@@ -5,18 +5,18 @@
# $2 file with scancode list (hex or dec)
case "$2" in
/*) scf="$2" ;;
*) scf="@pkglibexecdir@/keymaps/force-release/$2" ;;
/*) scf="$2" ;;
*) scf="@pkglibexecdir@/keymaps/force-release/$2" ;;
esac
read attr <"/sys/$1/force_release"
while read scancode dummy; do
case "$scancode" in
\#*) ;;
*)
scancode=$(($scancode))
attr="$attr${attr:+,}$scancode"
;;
esac
case "$scancode" in
\#*) ;;
*)
scancode=$(($scancode))
attr="$attr${attr:+,}$scancode"
;;
esac
done <"$scf"
echo "$attr" >"/sys/$1/force_release"
+291 -291
View File
@@ -45,403 +45,403 @@ const struct key* lookup_key (const char *str, unsigned int len);
static int evdev_open(const char *dev)
{
int fd;
char fn[PATH_MAX];
int fd;
char fn[PATH_MAX];
if (strncmp(dev, "/dev", 4) != 0) {
snprintf(fn, sizeof(fn), "/dev/%s", dev);
dev = fn;
}
if (strncmp(dev, "/dev", 4) != 0) {
snprintf(fn, sizeof(fn), "/dev/%s", dev);
dev = fn;
}
if ((fd = open(dev, O_RDWR)) < 0) {
fprintf(stderr, "error open('%s'): %m\n", dev);
return -1;
}
return fd;
if ((fd = open(dev, O_RDWR)) < 0) {
fprintf(stderr, "error open('%s'): %m\n", dev);
return -1;
}
return fd;
}
static int evdev_get_keycode(int fd, int scancode, int e)
{
int codes[2];
int codes[2];
codes[0] = scancode;
if (ioctl(fd, EVIOCGKEYCODE, codes) < 0) {
if (e && errno == EINVAL) {
return -2;
} else {
fprintf(stderr, "EVIOCGKEYCODE: %m\n");
return -1;
}
}
return codes[1];
codes[0] = scancode;
if (ioctl(fd, EVIOCGKEYCODE, codes) < 0) {
if (e && errno == EINVAL) {
return -2;
} else {
fprintf(stderr, "EVIOCGKEYCODE: %m\n");
return -1;
}
}
return codes[1];
}
static int evdev_set_keycode(int fd, int scancode, int keycode)
{
int codes[2];
int codes[2];
codes[0] = scancode;
codes[1] = keycode;
codes[0] = scancode;
codes[1] = keycode;
if (ioctl(fd, EVIOCSKEYCODE, codes) < 0) {
fprintf(stderr, "EVIOCSKEYCODE: %m\n");
return -1;
}
return 0;
if (ioctl(fd, EVIOCSKEYCODE, codes) < 0) {
fprintf(stderr, "EVIOCSKEYCODE: %m\n");
return -1;
}
return 0;
}
static int evdev_driver_version(int fd, char *v, size_t l)
{
int version;
int version;
if (ioctl(fd, EVIOCGVERSION, &version)) {
fprintf(stderr, "EVIOCGVERSION: %m\n");
return -1;
}
if (ioctl(fd, EVIOCGVERSION, &version)) {
fprintf(stderr, "EVIOCGVERSION: %m\n");
return -1;
}
snprintf(v, l, "%i.%i.%i.", version >> 16, (version >> 8) & 0xff, version & 0xff);
return 0;
snprintf(v, l, "%i.%i.%i.", version >> 16, (version >> 8) & 0xff, version & 0xff);
return 0;
}
static int evdev_device_name(int fd, char *n, size_t l)
{
if (ioctl(fd, EVIOCGNAME(l), n) < 0) {
fprintf(stderr, "EVIOCGNAME: %m\n");
return -1;
}
return 0;
if (ioctl(fd, EVIOCGNAME(l), n) < 0) {
fprintf(stderr, "EVIOCGNAME: %m\n");
return -1;
}
return 0;
}
/* Return a lower-case string with KEY_ prefix removed */
static const char* format_keyname(const char* key) {
static char result[101];
const char* s;
int len;
static char result[101];
const char* s;
int len;
for (s = key+4, len = 0; *s && len < 100; ++len, ++s)
result[len] = tolower(*s);
result[len] = '\0';
return result;
for (s = key+4, len = 0; *s && len < 100; ++len, ++s)
result[len] = tolower(*s);
result[len] = '\0';
return result;
}
static int dump_table(int fd) {
char version[256], name[256];
int scancode, r = -1;
char version[256], name[256];
int scancode, r = -1;
if (evdev_driver_version(fd, version, sizeof(version)) < 0)
goto fail;
if (evdev_driver_version(fd, version, sizeof(version)) < 0)
goto fail;
if (evdev_device_name(fd, name, sizeof(name)) < 0)
goto fail;
if (evdev_device_name(fd, name, sizeof(name)) < 0)
goto fail;
printf("### evdev %s, driver '%s'\n", version, name);
printf("### evdev %s, driver '%s'\n", version, name);
r = 0;
for (scancode = 0; scancode < MAX_SCANCODES; scancode++) {
int keycode;
r = 0;
for (scancode = 0; scancode < MAX_SCANCODES; scancode++) {
int keycode;
if ((keycode = evdev_get_keycode(fd, scancode, 1)) < 0) {
if (keycode == -2)
continue;
r = -1;
break;
}
if ((keycode = evdev_get_keycode(fd, scancode, 1)) < 0) {
if (keycode == -2)
continue;
r = -1;
break;
}
if (keycode < KEY_MAX && key_names[keycode])
printf("0x%03x %s\n", scancode, format_keyname(key_names[keycode]));
else
printf("0x%03x 0x%03x\n", scancode, keycode);
}
if (keycode < KEY_MAX && key_names[keycode])
printf("0x%03x %s\n", scancode, format_keyname(key_names[keycode]));
else
printf("0x%03x 0x%03x\n", scancode, keycode);
}
fail:
return r;
return r;
}
static void set_key(int fd, const char* scancode_str, const char* keyname)
{
unsigned scancode;
char *endptr;
char t[105] = "KEY_UNKNOWN";
const struct key *k;
unsigned scancode;
char *endptr;
char t[105] = "KEY_UNKNOWN";
const struct key *k;
scancode = (unsigned) strtol(scancode_str, &endptr, 0);
if (*endptr != '\0') {
fprintf(stderr, "ERROR: Invalid scancode\n");
exit(1);
}
scancode = (unsigned) strtol(scancode_str, &endptr, 0);
if (*endptr != '\0') {
fprintf(stderr, "ERROR: Invalid scancode\n");
exit(1);
}
snprintf(t, sizeof(t), "KEY_%s", keyname);
snprintf(t, sizeof(t), "KEY_%s", keyname);
if (!(k = lookup_key(t, strlen(t)))) {
fprintf(stderr, "ERROR: Unknown key name '%s'\n", keyname);
exit(1);
}
if (!(k = lookup_key(t, strlen(t)))) {
fprintf(stderr, "ERROR: Unknown key name '%s'\n", keyname);
exit(1);
}
if (evdev_set_keycode(fd, scancode, k->id) < 0)
fprintf(stderr, "setting scancode 0x%2X to key code %i failed\n",
scancode, k->id);
else
printf("setting scancode 0x%2X to key code %i\n",
scancode, k->id);
if (evdev_set_keycode(fd, scancode, k->id) < 0)
fprintf(stderr, "setting scancode 0x%2X to key code %i failed\n",
scancode, k->id);
else
printf("setting scancode 0x%2X to key code %i\n",
scancode, k->id);
}
static int merge_table(int fd, FILE *f) {
int r = 0;
int line = 0;
int r = 0;
int line = 0;
while (!feof(f)) {
char s[256], *p;
int scancode, new_keycode, old_keycode;
while (!feof(f)) {
char s[256], *p;
int scancode, new_keycode, old_keycode;
if (!fgets(s, sizeof(s), f))
break;
if (!fgets(s, sizeof(s), f))
break;
line++;
p = s+strspn(s, "\t ");
if (*p == '#' || *p == '\n')
continue;
line++;
p = s+strspn(s, "\t ");
if (*p == '#' || *p == '\n')
continue;
if (sscanf(p, "%i %i", &scancode, &new_keycode) != 2) {
char t[105] = "KEY_UNKNOWN";
const struct key *k;
if (sscanf(p, "%i %i", &scancode, &new_keycode) != 2) {
char t[105] = "KEY_UNKNOWN";
const struct key *k;
if (sscanf(p, "%i %100s", &scancode, t+4) != 2) {
fprintf(stderr, "WARNING: Parse failure at line %i, ignoring.\n", line);
r = -1;
continue;
}
if (sscanf(p, "%i %100s", &scancode, t+4) != 2) {
fprintf(stderr, "WARNING: Parse failure at line %i, ignoring.\n", line);
r = -1;
continue;
}
if (!(k = lookup_key(t, strlen(t)))) {
fprintf(stderr, "WARNING: Unknown key '%s' at line %i, ignoring.\n", t, line);
r = -1;
continue;
}
if (!(k = lookup_key(t, strlen(t)))) {
fprintf(stderr, "WARNING: Unknown key '%s' at line %i, ignoring.\n", t, line);
r = -1;
continue;
}
new_keycode = k->id;
}
new_keycode = k->id;
}
if ((old_keycode = evdev_get_keycode(fd, scancode, 0)) < 0) {
r = -1;
goto fail;
}
if ((old_keycode = evdev_get_keycode(fd, scancode, 0)) < 0) {
r = -1;
goto fail;
}
if (evdev_set_keycode(fd, scancode, new_keycode) < 0) {
r = -1;
goto fail;
}
if (evdev_set_keycode(fd, scancode, new_keycode) < 0) {
r = -1;
goto fail;
}
if (new_keycode != old_keycode)
fprintf(stderr, "Remapped scancode 0x%02x to 0x%02x (prior: 0x%02x)\n",
scancode, new_keycode, old_keycode);
}
if (new_keycode != old_keycode)
fprintf(stderr, "Remapped scancode 0x%02x to 0x%02x (prior: 0x%02x)\n",
scancode, new_keycode, old_keycode);
}
fail:
fclose(f);
return r;
fclose(f);
return r;
}
/* read one event; return 1 if valid */
static int read_event(int fd, struct input_event* ev)
{
int ret;
ret = read(fd, ev, sizeof(struct input_event));
int ret;
ret = read(fd, ev, sizeof(struct input_event));
if (ret < 0) {
perror("read");
return 0;
}
if (ret != sizeof(struct input_event)) {
fprintf(stderr, "did not get enough data for event struct, aborting\n");
return 0;
}
if (ret < 0) {
perror("read");
return 0;
}
if (ret != sizeof(struct input_event)) {
fprintf(stderr, "did not get enough data for event struct, aborting\n");
return 0;
}
return 1;
return 1;
}
static void print_key(uint32_t scancode, uint16_t keycode, int has_scan, int has_key)
{
const char *keyname;
const char *keyname;
/* ignore key release events */
if (has_key == 1)
return;
/* ignore key release events */
if (has_key == 1)
return;
if (has_key == 0 && has_scan != 0) {
fprintf(stderr, "got scan code event 0x%02X without a key code event\n",
scancode);
return;
}
if (has_key == 0 && has_scan != 0) {
fprintf(stderr, "got scan code event 0x%02X without a key code event\n",
scancode);
return;
}
if (has_scan != 0)
printf("scan code: 0x%02X ", scancode);
else
printf("(no scan code received) ");
if (has_scan != 0)
printf("scan code: 0x%02X ", scancode);
else
printf("(no scan code received) ");
keyname = key_names[keycode];
if (keyname != NULL)
printf("key code: %s\n", format_keyname(keyname));
else
printf("key code: %03X\n", keycode);
keyname = key_names[keycode];
if (keyname != NULL)
printf("key code: %s\n", format_keyname(keyname));
else
printf("key code: %03X\n", keycode);
}
static void interactive(int fd)
{
struct input_event ev;
uint32_t last_scan = 0;
uint16_t last_key = 0;
int has_scan; /* boolean */
int has_key; /* 0: none, 1: release, 2: press */
struct input_event ev;
uint32_t last_scan = 0;
uint16_t last_key = 0;
int has_scan; /* boolean */
int has_key; /* 0: none, 1: release, 2: press */
/* grab input device */
ioctl(fd, EVIOCGRAB, 1);
puts("Press ESC to finish, or Control-C if this device is not your primary keyboard");
/* grab input device */
ioctl(fd, EVIOCGRAB, 1);
puts("Press ESC to finish, or Control-C if this device is not your primary keyboard");
has_scan = has_key = 0;
while (read_event(fd, &ev)) {
/* Drivers usually send the scan code first, then the key code,
* then a SYN. Some drivers (like thinkpad_acpi) send the key
* code first, and some drivers might not send SYN events, so
* keep a robust state machine which can deal with any of those
*/
has_scan = has_key = 0;
while (read_event(fd, &ev)) {
/* Drivers usually send the scan code first, then the key code,
* then a SYN. Some drivers (like thinkpad_acpi) send the key
* code first, and some drivers might not send SYN events, so
* keep a robust state machine which can deal with any of those
*/
if (ev.type == EV_MSC && ev.code == MSC_SCAN) {
if (has_scan) {
fputs("driver did not send SYN event in between key events; previous event:\n",
stderr);
print_key(last_scan, last_key, has_scan, has_key);
has_key = 0;
}
if (ev.type == EV_MSC && ev.code == MSC_SCAN) {
if (has_scan) {
fputs("driver did not send SYN event in between key events; previous event:\n",
stderr);
print_key(last_scan, last_key, has_scan, has_key);
has_key = 0;
}
last_scan = ev.value;
has_scan = 1;
/*printf("--- got scan %u; has scan %i key %i\n", last_scan, has_scan, has_key); */
}
else if (ev.type == EV_KEY) {
if (has_key) {
fputs("driver did not send SYN event in between key events; previous event:\n",
stderr);
print_key(last_scan, last_key, has_scan, has_key);
has_scan = 0;
}
last_scan = ev.value;
has_scan = 1;
/*printf("--- got scan %u; has scan %i key %i\n", last_scan, has_scan, has_key); */
}
else if (ev.type == EV_KEY) {
if (has_key) {
fputs("driver did not send SYN event in between key events; previous event:\n",
stderr);
print_key(last_scan, last_key, has_scan, has_key);
has_scan = 0;
}
last_key = ev.code;
has_key = 1 + ev.value;
/*printf("--- got key %hu; has scan %i key %i\n", last_key, has_scan, has_key);*/
last_key = ev.code;
has_key = 1 + ev.value;
/*printf("--- got key %hu; has scan %i key %i\n", last_key, has_scan, has_key);*/
/* Stop on ESC */
if (ev.code == KEY_ESC && ev.value == 0)
break;
}
else if (ev.type == EV_SYN) {
/*printf("--- got SYN; has scan %i key %i\n", has_scan, has_key);*/
print_key(last_scan, last_key, has_scan, has_key);
/* Stop on ESC */
if (ev.code == KEY_ESC && ev.value == 0)
break;
}
else if (ev.type == EV_SYN) {
/*printf("--- got SYN; has scan %i key %i\n", has_scan, has_key);*/
print_key(last_scan, last_key, has_scan, has_key);
has_scan = has_key = 0;
}
has_scan = has_key = 0;
}
}
}
/* release input device */
ioctl(fd, EVIOCGRAB, 0);
/* release input device */
ioctl(fd, EVIOCGRAB, 0);
}
static void help(int error)
{
const char* h = "Usage: keymap <event device> [<map file>]\n"
" keymap <event device> scancode keyname [...]\n"
" keymap -i <event device>\n";
if (error) {
fputs(h, stderr);
exit(2);
} else {
fputs(h, stdout);
exit(0);
}
const char* h = "Usage: keymap <event device> [<map file>]\n"
" keymap <event device> scancode keyname [...]\n"
" keymap -i <event device>\n";
if (error) {
fputs(h, stderr);
exit(2);
} else {
fputs(h, stdout);
exit(0);
}
}
int main(int argc, char **argv)
{
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "interactive", no_argument, NULL, 'i' },
{}
};
int fd = -1;
int opt_interactive = 0;
int i;
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "interactive", no_argument, NULL, 'i' },
{}
};
int fd = -1;
int opt_interactive = 0;
int i;
while (1) {
int option;
while (1) {
int option;
option = getopt_long(argc, argv, "hi", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "hi", options, NULL);
if (option == -1)
break;
switch (option) {
case 'h':
help(0);
switch (option) {
case 'h':
help(0);
case 'i':
opt_interactive = 1;
break;
default:
return 1;
}
}
case 'i':
opt_interactive = 1;
break;
default:
return 1;
}
}
if (argc < optind+1)
help (1);
if (argc < optind+1)
help (1);
if ((fd = evdev_open(argv[optind])) < 0)
return 3;
if ((fd = evdev_open(argv[optind])) < 0)
return 3;
/* one argument (device): dump or interactive */
if (argc == optind+1) {
if (opt_interactive)
interactive(fd);
else
dump_table(fd);
return 0;
}
/* one argument (device): dump or interactive */
if (argc == optind+1) {
if (opt_interactive)
interactive(fd);
else
dump_table(fd);
return 0;
}
/* two arguments (device, mapfile): set map file */
if (argc == optind+2) {
const char *filearg = argv[optind+1];
if (strchr(filearg, '/')) {
/* Keymap file argument is a path */
FILE *f = fopen(filearg, "r");
if (f)
merge_table(fd, f);
else
perror(filearg);
} else {
/* Keymap file argument is a filename */
/* Open override file if present, otherwise default file */
char keymap_path[PATH_MAX];
snprintf(keymap_path, sizeof(keymap_path), "%s%s", SYSCONFDIR "/udev/keymaps/", filearg);
FILE *f = fopen(keymap_path, "r");
if (f) {
merge_table(fd, f);
} else {
snprintf(keymap_path, sizeof(keymap_path), "%s%s", PKGLIBEXECDIR "/keymaps/", filearg);
f = fopen(keymap_path, "r");
if (f)
merge_table(fd, f);
else
perror(keymap_path);
}
}
return 0;
}
/* two arguments (device, mapfile): set map file */
if (argc == optind+2) {
const char *filearg = argv[optind+1];
if (strchr(filearg, '/')) {
/* Keymap file argument is a path */
FILE *f = fopen(filearg, "r");
if (f)
merge_table(fd, f);
else
perror(filearg);
} else {
/* Keymap file argument is a filename */
/* Open override file if present, otherwise default file */
char keymap_path[PATH_MAX];
snprintf(keymap_path, sizeof(keymap_path), "%s%s", SYSCONFDIR "/udev/keymaps/", filearg);
FILE *f = fopen(keymap_path, "r");
if (f) {
merge_table(fd, f);
} else {
snprintf(keymap_path, sizeof(keymap_path), "%s%s", PKGLIBEXECDIR "/keymaps/", filearg);
f = fopen(keymap_path, "r");
if (f)
merge_table(fd, f);
else
perror(keymap_path);
}
}
return 0;
}
/* more arguments (device, scancode/keyname pairs): set keys directly */
if ((argc - optind - 1) % 2 == 0) {
for (i = optind+1; i < argc; i += 2)
set_key(fd, argv[i], argv[i+1]);
return 0;
}
/* more arguments (device, scancode/keyname pairs): set keys directly */
if ((argc - optind - 1) % 2 == 0) {
for (i = optind+1; i < argc; i += 2)
set_key(fd, argv[i], argv[i+1]);
return 0;
}
/* invalid number of arguments */
help(1);
return 1; /* not reached */
/* invalid number of arguments */
help(1);
return 1; /* not reached */
}
+1 -1
View File
@@ -1,4 +1,4 @@
0x84 bluetooth # sent when bluetooth module missing, and key pressed
0x92 media # acer arcade
0x92 media # acer arcade
0xD4 bluetooth # bluetooth on
0xD9 bluetooth # bluetooth off
+6 -6
View File
@@ -1,7 +1,7 @@
# Key codes observed on S10-3, assumed valid on other IdeaPad models
0x81 rfkill # does nothing in BIOS
0x83 display_off # BIOS toggles screen state
0xB9 brightnessup # does nothing in BIOS
0xBA brightnessdown # does nothing in BIOS
0xF1 camera # BIOS toggles camera power
0xf2 unknown # trackpad enable/disable (does nothing in BIOS)
0x81 rfkill # does nothing in BIOS
0x83 display_off # BIOS toggles screen state
0xB9 brightnessup # does nothing in BIOS
0xBA brightnessdown # does nothing in BIOS
0xF1 camera # BIOS toggles camera power
0xf2 unknown # trackpad enable/disable (does nothing in BIOS)
+17 -17
View File
@@ -28,24 +28,24 @@
int main(int argc, char** argv)
{
if (argc != 2) {
printf("usage: mtd_probe /dev/mtd[n]\n");
return 1;
}
if (argc != 2) {
printf("usage: mtd_probe /dev/mtd[n]\n");
return 1;
}
int mtd_fd = open(argv[1], O_RDONLY);
if (mtd_fd == -1) {
perror("open");
exit(-1);
}
int mtd_fd = open(argv[1], O_RDONLY);
if (mtd_fd == -1) {
perror("open");
exit(-1);
}
mtd_info_t mtd_info;
int error = ioctl(mtd_fd, MEMGETINFO, &mtd_info);
if (error == -1) {
perror("ioctl");
exit(-1);
}
mtd_info_t mtd_info;
int error = ioctl(mtd_fd, MEMGETINFO, &mtd_info);
if (error == -1) {
perror("ioctl");
exit(-1);
}
probe_smart_media(mtd_fd, &mtd_info);
return -1;
probe_smart_media(mtd_fd, &mtd_info);
return -1;
}
+12 -12
View File
@@ -21,29 +21,29 @@
/* Full oob structure as written on the flash */
struct sm_oob {
uint32_t reserved;
uint8_t data_status;
uint8_t block_status;
uint8_t lba_copy1[2];
uint8_t ecc2[3];
uint8_t lba_copy2[2];
uint8_t ecc1[3];
uint32_t reserved;
uint8_t data_status;
uint8_t block_status;
uint8_t lba_copy1[2];
uint8_t ecc2[3];
uint8_t lba_copy2[2];
uint8_t ecc1[3];
} __attribute__((packed));
/* one sector is always 512 bytes, but it can consist of two nand pages */
#define SM_SECTOR_SIZE 512
#define SM_SECTOR_SIZE 512
/* oob area is also 16 bytes, but might be from two pages */
#define SM_OOB_SIZE 16
#define SM_OOB_SIZE 16
/* This is maximum zone size, and all devices that have more that one zone
have this size */
#define SM_MAX_ZONE_SIZE 1024
#define SM_MAX_ZONE_SIZE 1024
/* support for small page nand */
#define SM_SMALL_PAGE 256
#define SM_SMALL_OOB_SIZE 8
#define SM_SMALL_PAGE 256
#define SM_SMALL_OOB_SIZE 8
void probe_smart_media(int mtd_fd, mtd_info_t *info);
+45 -45
View File
@@ -30,68 +30,68 @@
#include "mtd_probe.h"
static const uint8_t cis_signature[] = {
0x01, 0x03, 0xD9, 0x01, 0xFF, 0x18, 0x02, 0xDF, 0x01, 0x20
0x01, 0x03, 0xD9, 0x01, 0xFF, 0x18, 0x02, 0xDF, 0x01, 0x20
};
void probe_smart_media(int mtd_fd, mtd_info_t* info)
{
char* cis_buffer = malloc(SM_SECTOR_SIZE);
char* cis_buffer = malloc(SM_SECTOR_SIZE);
if (!cis_buffer)
return;
if (!cis_buffer)
return;
if (info->type != MTD_NANDFLASH)
goto exit;
if (info->type != MTD_NANDFLASH)
goto exit;
int sector_size = info->writesize;
int block_size = info->erasesize;
int size_in_megs = info->size / (1024 * 1024);
int spare_count;
int sector_size = info->writesize;
int block_size = info->erasesize;
int size_in_megs = info->size / (1024 * 1024);
int spare_count;
if (sector_size != SM_SECTOR_SIZE && sector_size != SM_SMALL_PAGE)
goto exit;
if (sector_size != SM_SECTOR_SIZE && sector_size != SM_SMALL_PAGE)
goto exit;
switch(size_in_megs) {
case 1:
case 2:
spare_count = 6;
break;
case 4:
spare_count = 12;
break;
default:
spare_count = 24;
break;
}
switch(size_in_megs) {
case 1:
case 2:
spare_count = 6;
break;
case 4:
spare_count = 12;
break;
default:
spare_count = 24;
break;
}
int offset;
int cis_found = 0;
int offset;
int cis_found = 0;
for (offset = 0 ; offset < block_size * spare_count ;
offset += sector_size) {
for (offset = 0 ; offset < block_size * spare_count ;
offset += sector_size) {
lseek(mtd_fd, SEEK_SET, offset);
if (read(mtd_fd, cis_buffer, SM_SECTOR_SIZE) == SM_SECTOR_SIZE){
cis_found = 1;
break;
}
}
lseek(mtd_fd, SEEK_SET, offset);
if (read(mtd_fd, cis_buffer, SM_SECTOR_SIZE) == SM_SECTOR_SIZE){
cis_found = 1;
break;
}
}
if (!cis_found)
goto exit;
if (!cis_found)
goto exit;
if (memcmp(cis_buffer, cis_signature, sizeof(cis_signature)) != 0 &&
(memcmp(cis_buffer + SM_SMALL_PAGE, cis_signature,
sizeof(cis_signature)) != 0))
goto exit;
if (memcmp(cis_buffer, cis_signature, sizeof(cis_signature)) != 0 &&
(memcmp(cis_buffer + SM_SMALL_PAGE, cis_signature,
sizeof(cis_signature)) != 0))
goto exit;
printf("MTD_FTL=smartmedia\n");
free(cis_buffer);
exit(0);
printf("MTD_FTL=smartmedia\n");
free(cis_buffer);
exit(0);
exit:
free(cis_buffer);
return;
free(cis_buffer);
return;
}
@@ -20,94 +20,94 @@ PATH='/usr/bin:/bin:/usr/sbin:/sbin'
# Read a single line from file $1 in the $DEVPATH directory.
# The function must not return an error even if the file does not exist.
sysread() {
local file="$1"
[ -e "/sys$DEVPATH/$file" ] || return 0
local value
read value < "/sys$DEVPATH/$file" || return 0
echo "$value"
local file="$1"
[ -e "/sys$DEVPATH/$file" ] || return 0
local value
read value < "/sys$DEVPATH/$file" || return 0
echo "$value"
}
sysreadlink() {
local file="$1"
[ -e "/sys$DEVPATH/$file" ] || return 0
readlink -f /sys$DEVPATH/$file 2> /dev/null || true
local file="$1"
[ -e "/sys$DEVPATH/$file" ] || return 0
readlink -f /sys$DEVPATH/$file 2> /dev/null || true
}
# Return true if a directory is writeable.
writeable() {
if ln -s test-link $1/.is-writeable 2> /dev/null; then
rm -f $1/.is-writeable
return 0
else
return 1
fi
if ln -s test-link $1/.is-writeable 2> /dev/null; then
rm -f $1/.is-writeable
return 0
else
return 1
fi
}
# Create a lock file for the current rules file.
lock_rules_file() {
RUNDIR=$(udevadm info --run)
[ -e "$RUNDIR" ] || return 0
RUNDIR=$(udevadm info --run)
[ -e "$RUNDIR" ] || return 0
RULES_LOCK="$RUNDIR/.lock-${RULES_FILE##*/}"
RULES_LOCK="$RUNDIR/.lock-${RULES_FILE##*/}"
retry=30
while ! mkdir $RULES_LOCK 2> /dev/null; do
if [ $retry -eq 0 ]; then
echo "Cannot lock $RULES_FILE!" >&2
exit 2
fi
sleep 1
retry=$(($retry - 1))
done
retry=30
while ! mkdir $RULES_LOCK 2> /dev/null; do
if [ $retry -eq 0 ]; then
echo "Cannot lock $RULES_FILE!" >&2
exit 2
fi
sleep 1
retry=$(($retry - 1))
done
}
unlock_rules_file() {
[ "$RULES_LOCK" ] || return 0
rmdir $RULES_LOCK || true
[ "$RULES_LOCK" ] || return 0
rmdir $RULES_LOCK || true
}
# Choose the real rules file if it is writeable or a temporary file if not.
# Both files should be checked later when looking for existing rules.
choose_rules_file() {
RUNDIR=$(udevadm info --run)
local tmp_rules_file="$RUNDIR/tmp-rules--${RULES_FILE##*/}"
[ -e "$RULES_FILE" -o -e "$tmp_rules_file" ] || PRINT_HEADER=1
RUNDIR=$(udevadm info --run)
local tmp_rules_file="$RUNDIR/tmp-rules--${RULES_FILE##*/}"
[ -e "$RULES_FILE" -o -e "$tmp_rules_file" ] || PRINT_HEADER=1
if writeable ${RULES_FILE%/*}; then
RO_RULES_FILE='/dev/null'
else
RO_RULES_FILE=$RULES_FILE
RULES_FILE=$tmp_rules_file
fi
if writeable ${RULES_FILE%/*}; then
RO_RULES_FILE='/dev/null'
else
RO_RULES_FILE=$RULES_FILE
RULES_FILE=$tmp_rules_file
fi
}
# Return the name of the first free device.
raw_find_next_available() {
local links="$1"
local links="$1"
local basename=${links%%[ 0-9]*}
local max=-1
for name in $links; do
local num=${name#$basename}
[ "$num" ] || num=0
[ $num -gt $max ] && max=$num
done
local basename=${links%%[ 0-9]*}
local max=-1
for name in $links; do
local num=${name#$basename}
[ "$num" ] || num=0
[ $num -gt $max ] && max=$num
done
local max=$(($max + 1))
# "name0" actually is just "name"
[ $max -eq 0 ] && return
echo "$max"
local max=$(($max + 1))
# "name0" actually is just "name"
[ $max -eq 0 ] && return
echo "$max"
}
# Find all rules matching a key (with action) and a pattern.
find_all_rules() {
local key="$1"
local linkre="$2"
local match="$3"
local key="$1"
local linkre="$2"
local match="$3"
local search='.*[[:space:],]'"$key"'"('"$linkre"')".*'
echo $(sed -n -r -e 's/^#.*//' -e "${match}s/${search}/\1/p" \
$RO_RULES_FILE \
$([ -e $RULES_FILE ] && echo $RULES_FILE) \
2>/dev/null)
local search='.*[[:space:],]'"$key"'"('"$linkre"')".*'
echo $(sed -n -r -e 's/^#.*//' -e "${match}s/${search}/\1/p" \
$RO_RULES_FILE \
$([ -e $RULES_FILE ] && echo $RULES_FILE) \
2>/dev/null)
}
+52 -52
View File
@@ -22,9 +22,9 @@
# debug, if UDEV_LOG=<debug>
if [ -n "$UDEV_LOG" ]; then
if [ "$UDEV_LOG" -ge 7 ]; then
set -x
fi
if [ "$UDEV_LOG" -ge 7 ]; then
set -x
fi
fi
RULES_FILE="/etc/udev/rules.d/70-persistent-cd.rules"
@@ -32,70 +32,70 @@ RULES_FILE="/etc/udev/rules.d/70-persistent-cd.rules"
. /lib/udev/rule_generator.functions
find_next_available() {
raw_find_next_available "$(find_all_rules 'SYMLINK\+=' "$1")"
raw_find_next_available "$(find_all_rules 'SYMLINK\+=' "$1")"
}
write_rule() {
local match="$1"
local link="$2"
local comment="$3"
local match="$1"
local link="$2"
local comment="$3"
{
if [ "$PRINT_HEADER" ]; then
PRINT_HEADER=
echo "# This file was automatically generated by the $0"
echo "# program, run by the cd-aliases-generator.rules rules file."
echo "#"
echo "# You can modify it, as long as you keep each rule on a single"
echo "# line, and set the \$GENERATED variable."
echo ""
fi
{
if [ "$PRINT_HEADER" ]; then
PRINT_HEADER=
echo "# This file was automatically generated by the $0"
echo "# program, run by the cd-aliases-generator.rules rules file."
echo "#"
echo "# You can modify it, as long as you keep each rule on a single"
echo "# line, and set the \$GENERATED variable."
echo ""
fi
[ "$comment" ] && echo "# $comment"
echo "$match, SYMLINK+=\"$link\", ENV{GENERATED}=\"1\""
} >> $RULES_FILE
SYMLINKS="$SYMLINKS $link"
[ "$comment" ] && echo "# $comment"
echo "$match, SYMLINK+=\"$link\", ENV{GENERATED}=\"1\""
} >> $RULES_FILE
SYMLINKS="$SYMLINKS $link"
}
if [ -z "$DEVPATH" ]; then
echo "Missing \$DEVPATH." >&2
exit 1
echo "Missing \$DEVPATH." >&2
exit 1
fi
if [ -z "$ID_CDROM" ]; then
echo "$DEVPATH is not a CD reader." >&2
exit 1
echo "$DEVPATH is not a CD reader." >&2
exit 1
fi
if [ "$1" ]; then
METHOD="$1"
METHOD="$1"
else
METHOD='by-path'
METHOD='by-path'
fi
case "$METHOD" in
by-path)
if [ -z "$ID_PATH" ]; then
echo "$DEVPATH not supported by path_id. by-id may work." >&2
exit 1
fi
RULE="ENV{ID_PATH}==\"$ID_PATH\""
;;
by-path)
if [ -z "$ID_PATH" ]; then
echo "$DEVPATH not supported by path_id. by-id may work." >&2
exit 1
fi
RULE="ENV{ID_PATH}==\"$ID_PATH\""
;;
by-id)
if [ "$ID_SERIAL" ]; then
RULE="ENV{ID_SERIAL}==\"$ID_SERIAL\""
elif [ "$ID_MODEL" -a "$ID_REVISION" ]; then
RULE="ENV{ID_MODEL}==\"$ID_MODEL\", ENV{ID_REVISION}==\"$ID_REVISION\""
else
echo "$DEVPATH not supported by ata_id. by-path may work." >&2
exit 1
fi
;;
by-id)
if [ "$ID_SERIAL" ]; then
RULE="ENV{ID_SERIAL}==\"$ID_SERIAL\""
elif [ "$ID_MODEL" -a "$ID_REVISION" ]; then
RULE="ENV{ID_MODEL}==\"$ID_MODEL\", ENV{ID_REVISION}==\"$ID_REVISION\""
else
echo "$DEVPATH not supported by ata_id. by-path may work." >&2
exit 1
fi
;;
*)
echo "Invalid argument (must be either by-path or by-id)." >&2
exit 1
;;
*)
echo "Invalid argument (must be either by-path or by-id)." >&2
exit 1
;;
esac
# Prevent concurrent processes from modifying the file at the same time.
@@ -110,13 +110,13 @@ match="SUBSYSTEM==\"block\", ENV{ID_CDROM}==\"?*\", $RULE"
comment="$ID_MODEL ($ID_PATH)"
write_rule "$match" "cdrom$link_num" "$comment"
write_rule "$match" "cdrom$link_num" "$comment"
[ "$ID_CDROM_CD_R" -o "$ID_CDROM_CD_RW" ] && \
write_rule "$match" "cdrw$link_num"
write_rule "$match" "cdrw$link_num"
[ "$ID_CDROM_DVD" ] && \
write_rule "$match" "dvd$link_num"
write_rule "$match" "dvd$link_num"
[ "$ID_CDROM_DVD_R" -o "$ID_CDROM_DVD_RW" -o "$ID_CDROM_DVD_RAM" ] && \
write_rule "$match" "dvdrw$link_num"
write_rule "$match" "dvdrw$link_num"
echo >> $RULES_FILE
unlock_rules_file
+49 -49
View File
@@ -33,9 +33,9 @@
# debug, if UDEV_LOG=<debug>
if [ -n "$UDEV_LOG" ]; then
if [ "$UDEV_LOG" -ge 7 ]; then
set -x
fi
if [ "$UDEV_LOG" -ge 7 ]; then
set -x
fi
fi
RULES_FILE='/etc/udev/rules.d/70-persistent-net.rules'
@@ -43,42 +43,42 @@ RULES_FILE='/etc/udev/rules.d/70-persistent-net.rules'
. /lib/udev/rule_generator.functions
interface_name_taken() {
local value="$(find_all_rules 'NAME=' $INTERFACE)"
if [ "$value" ]; then
return 0
else
return 1
fi
local value="$(find_all_rules 'NAME=' $INTERFACE)"
if [ "$value" ]; then
return 0
else
return 1
fi
}
find_next_available() {
raw_find_next_available "$(find_all_rules 'NAME=' "$1")"
raw_find_next_available "$(find_all_rules 'NAME=' "$1")"
}
write_rule() {
local match="$1"
local name="$2"
local comment="$3"
local match="$1"
local name="$2"
local comment="$3"
{
if [ "$PRINT_HEADER" ]; then
PRINT_HEADER=
echo "# This file was automatically generated by the $0"
echo "# program, run by the persistent-net-generator.rules rules file."
echo "#"
echo "# You can modify it, as long as you keep each rule on a single"
echo "# line, and change only the value of the NAME= key."
fi
{
if [ "$PRINT_HEADER" ]; then
PRINT_HEADER=
echo "# This file was automatically generated by the $0"
echo "# program, run by the persistent-net-generator.rules rules file."
echo "#"
echo "# You can modify it, as long as you keep each rule on a single"
echo "# line, and change only the value of the NAME= key."
fi
echo ""
[ "$comment" ] && echo "# $comment"
echo "SUBSYSTEM==\"net\", ACTION==\"add\"$match, NAME=\"$name\""
} >> $RULES_FILE
echo ""
[ "$comment" ] && echo "# $comment"
echo "SUBSYSTEM==\"net\", ACTION==\"add\"$match, NAME=\"$name\""
} >> $RULES_FILE
}
if [ -z "$INTERFACE" ]; then
echo "missing \$INTERFACE" >&2
exit 1
echo "missing \$INTERFACE" >&2
exit 1
fi
# Prevent concurrent processes from modifying the file at the same time.
@@ -89,49 +89,49 @@ choose_rules_file
# the DRIVERS key is needed to not match bridges and VLAN sub-interfaces
if [ "$MATCHADDR" ]; then
match="$match, DRIVERS==\"?*\", ATTR{address}==\"$MATCHADDR\""
match="$match, DRIVERS==\"?*\", ATTR{address}==\"$MATCHADDR\""
fi
if [ "$MATCHDRV" ]; then
match="$match, DRIVERS==\"$MATCHDRV\""
match="$match, DRIVERS==\"$MATCHDRV\""
fi
if [ "$MATCHDEVID" ]; then
match="$match, ATTR{dev_id}==\"$MATCHDEVID\""
match="$match, ATTR{dev_id}==\"$MATCHDEVID\""
fi
if [ "$MATCHID" ]; then
match="$match, KERNELS==\"$MATCHID\""
match="$match, KERNELS==\"$MATCHID\""
fi
if [ "$MATCHIFTYPE" ]; then
match="$match, ATTR{type}==\"$MATCHIFTYPE\""
match="$match, ATTR{type}==\"$MATCHIFTYPE\""
fi
if [ -z "$match" ]; then
echo "missing valid match" >&2
unlock_rules_file
exit 1
echo "missing valid match" >&2
unlock_rules_file
exit 1
fi
basename=${INTERFACE%%[0-9]*}
match="$match, KERNEL==\"$basename*\""
if [ "$INTERFACE_NAME" ]; then
# external tools may request a custom name
COMMENT="$COMMENT (custom name provided by external tool)"
if [ "$INTERFACE_NAME" != "$INTERFACE" ]; then
INTERFACE=$INTERFACE_NAME;
echo "INTERFACE_NEW=$INTERFACE"
fi
# external tools may request a custom name
COMMENT="$COMMENT (custom name provided by external tool)"
if [ "$INTERFACE_NAME" != "$INTERFACE" ]; then
INTERFACE=$INTERFACE_NAME;
echo "INTERFACE_NEW=$INTERFACE"
fi
else
# if a rule using the current name already exists, find a new name
if interface_name_taken; then
INTERFACE="$basename$(find_next_available "$basename[0-9]*")"
# prevent INTERFACE from being "eth" instead of "eth0"
[ "$INTERFACE" = "${INTERFACE%%[ \[\]0-9]*}" ] && INTERFACE=${INTERFACE}0
echo "INTERFACE_NEW=$INTERFACE"
fi
# if a rule using the current name already exists, find a new name
if interface_name_taken; then
INTERFACE="$basename$(find_next_available "$basename[0-9]*")"
# prevent INTERFACE from being "eth" instead of "eth0"
[ "$INTERFACE" = "${INTERFACE%%[ \[\]0-9]*}" ] && INTERFACE=${INTERFACE}0
echo "INTERFACE_NEW=$INTERFACE"
fi
fi
write_rule "$match" "$INTERFACE" "$COMMENT"
+29 -29
View File
@@ -5,39 +5,39 @@
*
* Copyright (C) IBM Corp. 2003
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation version 2 of the License.
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation version 2 of the License.
*/
#include <scsi/scsi.h>
struct scsi_ioctl_command {
unsigned int inlen; /* excluding scsi command length */
unsigned int outlen;
unsigned char data[1];
/* on input, scsi command starts here then opt. data */
unsigned int inlen; /* excluding scsi command length */
unsigned int outlen;
unsigned char data[1];
/* on input, scsi command starts here then opt. data */
};
/*
* Default 5 second timeout
*/
#define DEF_TIMEOUT 5000
#define DEF_TIMEOUT 5000
#define SENSE_BUFF_LEN 32
#define SENSE_BUFF_LEN 32
/*
* The request buffer size passed to the SCSI INQUIRY commands, use 254,
* as this is a nice value for some devices, especially some of the usb
* mass storage devices.
*/
#define SCSI_INQ_BUFF_LEN 254
#define SCSI_INQ_BUFF_LEN 254
/*
* SCSI INQUIRY vendor and model (really product) lengths.
*/
#define VENDOR_LENGTH 8
#define MODEL_LENGTH 16
#define VENDOR_LENGTH 8
#define MODEL_LENGTH 16
#define INQUIRY_CMD 0x12
#define INQUIRY_CMDLEN 6
@@ -50,34 +50,34 @@ struct scsi_ioctl_command {
/*
* id type values of id descriptors. These are assumed to fit in 4 bits.
*/
#define SCSI_ID_VENDOR_SPECIFIC 0
#define SCSI_ID_T10_VENDOR 1
#define SCSI_ID_EUI_64 2
#define SCSI_ID_NAA 3
#define SCSI_ID_RELPORT 4
#define SCSI_ID_TGTGROUP 5
#define SCSI_ID_LUNGROUP 6
#define SCSI_ID_MD5 7
#define SCSI_ID_NAME 8
#define SCSI_ID_VENDOR_SPECIFIC 0
#define SCSI_ID_T10_VENDOR 1
#define SCSI_ID_EUI_64 2
#define SCSI_ID_NAA 3
#define SCSI_ID_RELPORT 4
#define SCSI_ID_TGTGROUP 5
#define SCSI_ID_LUNGROUP 6
#define SCSI_ID_MD5 7
#define SCSI_ID_NAME 8
/*
* Supported NAA values. These fit in 4 bits, so the "don't care" value
* cannot conflict with real values.
*/
#define SCSI_ID_NAA_DONT_CARE 0xff
#define SCSI_ID_NAA_IEEE_REG 5
#define SCSI_ID_NAA_IEEE_REG_EXTENDED 6
#define SCSI_ID_NAA_DONT_CARE 0xff
#define SCSI_ID_NAA_IEEE_REG 5
#define SCSI_ID_NAA_IEEE_REG_EXTENDED 6
/*
* Supported Code Set values.
*/
#define SCSI_ID_BINARY 1
#define SCSI_ID_ASCII 2
#define SCSI_ID_BINARY 1
#define SCSI_ID_ASCII 2
struct scsi_id_search_values {
u_char id_type;
u_char naa_type;
u_char code_set;
u_char id_type;
u_char naa_type;
u_char code_set;
};
/*
File diff suppressed because it is too large Load Diff
+19 -19
View File
@@ -15,35 +15,35 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define MAX_PATH_LEN 512
#define MAX_PATH_LEN 512
/*
* MAX_ATTR_LEN: maximum length of the result of reading a sysfs
* attribute.
*/
#define MAX_ATTR_LEN 256
#define MAX_ATTR_LEN 256
/*
* MAX_SERIAL_LEN: the maximum length of the serial number, including
* added prefixes such as vendor and product (model) strings.
*/
#define MAX_SERIAL_LEN 256
#define MAX_SERIAL_LEN 256
/*
* MAX_BUFFER_LEN: maximum buffer size and line length used while reading
* the config file.
*/
#define MAX_BUFFER_LEN 256
#define MAX_BUFFER_LEN 256
struct scsi_id_device {
char vendor[9];
char model[17];
char revision[5];
char type[33];
char kernel[64];
char serial[MAX_SERIAL_LEN];
char serial_short[MAX_SERIAL_LEN];
int use_sg;
char vendor[9];
char model[17];
char revision[5];
char type[33];
char kernel[64];
char serial[MAX_SERIAL_LEN];
char serial_short[MAX_SERIAL_LEN];
int use_sg;
/* Always from page 0x80 e.g. 'B3G1P8500RWT' - may not be unique */
char unit_serial_number[MAX_SERIAL_LEN];
@@ -54,20 +54,20 @@ struct scsi_id_device {
/* NULs if not set - otherwise hex encoding using lower-case e.g. '0xe00000d80000' */
char wwn_vendor_extension[17];
/* NULs if not set - otherwise decimal number */
char tgpt_group[8];
/* NULs if not set - otherwise decimal number */
char tgpt_group[8];
};
extern int scsi_std_inquiry(struct udev *udev, struct scsi_id_device *dev_scsi, const char *devname);
extern int scsi_get_serial (struct udev *udev, struct scsi_id_device *dev_scsi, const char *devname,
int page_code, int len);
int page_code, int len);
/*
* Page code values.
*/
enum page_code {
PAGE_83_PRE_SPC3 = -0x83,
PAGE_UNSPECIFIED = 0x00,
PAGE_80 = 0x80,
PAGE_83 = 0x83,
PAGE_83_PRE_SPC3 = -0x83,
PAGE_UNSPECIFIED = 0x00,
PAGE_80 = 0x80,
PAGE_83 = 0x83,
};
File diff suppressed because it is too large Load Diff
+324 -324
View File
@@ -28,403 +28,403 @@
static int debug;
enum{
ACTION_NONE = 0,
ACTION_REMOVE,
ACTION_ADD,
ACTION_CHANGE
ACTION_NONE = 0,
ACTION_REMOVE,
ACTION_ADD,
ACTION_CHANGE
};
static int set_facl(const char* filename, uid_t uid, int add)
{
int get;
acl_t acl;
acl_entry_t entry = NULL;
acl_entry_t e;
acl_permset_t permset;
int ret;
int get;
acl_t acl;
acl_entry_t entry = NULL;
acl_entry_t e;
acl_permset_t permset;
int ret;
/* don't touch ACLs for root */
if (uid == 0)
return 0;
/* don't touch ACLs for root */
if (uid == 0)
return 0;
/* read current record */
acl = acl_get_file(filename, ACL_TYPE_ACCESS);
if (!acl)
return -1;
/* read current record */
acl = acl_get_file(filename, ACL_TYPE_ACCESS);
if (!acl)
return -1;
/* locate ACL_USER entry for uid */
get = acl_get_entry(acl, ACL_FIRST_ENTRY, &e);
while (get == 1) {
acl_tag_t t;
/* locate ACL_USER entry for uid */
get = acl_get_entry(acl, ACL_FIRST_ENTRY, &e);
while (get == 1) {
acl_tag_t t;
acl_get_tag_type(e, &t);
if (t == ACL_USER) {
uid_t *u;
acl_get_tag_type(e, &t);
if (t == ACL_USER) {
uid_t *u;
u = (uid_t*)acl_get_qualifier(e);
if (u == NULL) {
ret = -1;
goto out;
}
if (*u == uid) {
entry = e;
acl_free(u);
break;
}
acl_free(u);
}
u = (uid_t*)acl_get_qualifier(e);
if (u == NULL) {
ret = -1;
goto out;
}
if (*u == uid) {
entry = e;
acl_free(u);
break;
}
acl_free(u);
}
get = acl_get_entry(acl, ACL_NEXT_ENTRY, &e);
}
get = acl_get_entry(acl, ACL_NEXT_ENTRY, &e);
}
/* remove ACL_USER entry for uid */
if (!add) {
if (entry == NULL) {
ret = 0;
goto out;
}
acl_delete_entry(acl, entry);
goto update;
}
/* remove ACL_USER entry for uid */
if (!add) {
if (entry == NULL) {
ret = 0;
goto out;
}
acl_delete_entry(acl, entry);
goto update;
}
/* create ACL_USER entry for uid */
if (entry == NULL) {
ret = acl_create_entry(&acl, &entry);
if (ret != 0)
goto out;
acl_set_tag_type(entry, ACL_USER);
acl_set_qualifier(entry, &uid);
}
/* create ACL_USER entry for uid */
if (entry == NULL) {
ret = acl_create_entry(&acl, &entry);
if (ret != 0)
goto out;
acl_set_tag_type(entry, ACL_USER);
acl_set_qualifier(entry, &uid);
}
/* add permissions for uid */
acl_get_permset(entry, &permset);
acl_add_perm(permset, ACL_READ|ACL_WRITE);
/* add permissions for uid */
acl_get_permset(entry, &permset);
acl_add_perm(permset, ACL_READ|ACL_WRITE);
update:
/* update record */
if (debug)
printf("%c%u %s\n", add ? '+' : '-', uid, filename);
acl_calc_mask(&acl);
ret = acl_set_file(filename, ACL_TYPE_ACCESS, acl);
if (ret != 0)
goto out;
/* update record */
if (debug)
printf("%c%u %s\n", add ? '+' : '-', uid, filename);
acl_calc_mask(&acl);
ret = acl_set_file(filename, ACL_TYPE_ACCESS, acl);
if (ret != 0)
goto out;
out:
acl_free(acl);
return ret;
acl_free(acl);
return ret;
}
/* check if a given uid is listed */
static int uid_in_list(GSList *list, uid_t uid)
{
GSList *l;
GSList *l;
for (l = list; l != NULL; l = g_slist_next(l))
if (uid == GPOINTER_TO_UINT(l->data))
return 1;
return 0;
for (l = list; l != NULL; l = g_slist_next(l))
if (uid == GPOINTER_TO_UINT(l->data))
return 1;
return 0;
}
/* return list of current uids of local active sessions */
static GSList *uids_with_local_active_session(const char *own_id)
{
GSList *list = NULL;
GKeyFile *keyfile;
GSList *list = NULL;
GKeyFile *keyfile;
keyfile = g_key_file_new();
if (g_key_file_load_from_file(keyfile, "/var/run/ConsoleKit/database", 0, NULL)) {
gchar **groups;
keyfile = g_key_file_new();
if (g_key_file_load_from_file(keyfile, "/var/run/ConsoleKit/database", 0, NULL)) {
gchar **groups;
groups = g_key_file_get_groups(keyfile, NULL);
if (groups != NULL) {
int i;
groups = g_key_file_get_groups(keyfile, NULL);
if (groups != NULL) {
int i;
for (i = 0; groups[i] != NULL; i++) {
uid_t u;
for (i = 0; groups[i] != NULL; i++) {
uid_t u;
if (!g_str_has_prefix(groups[i], "Session "))
continue;
if (own_id != NULL &&g_str_has_suffix(groups[i], own_id))
continue;
if (!g_key_file_get_boolean(keyfile, groups[i], "is_local", NULL))
continue;
if (!g_key_file_get_boolean(keyfile, groups[i], "is_active", NULL))
continue;
u = g_key_file_get_integer(keyfile, groups[i], "uid", NULL);
if (u > 0 && !uid_in_list(list, u))
list = g_slist_prepend(list, GUINT_TO_POINTER(u));
}
g_strfreev(groups);
}
}
g_key_file_free(keyfile);
if (!g_str_has_prefix(groups[i], "Session "))
continue;
if (own_id != NULL &&g_str_has_suffix(groups[i], own_id))
continue;
if (!g_key_file_get_boolean(keyfile, groups[i], "is_local", NULL))
continue;
if (!g_key_file_get_boolean(keyfile, groups[i], "is_active", NULL))
continue;
u = g_key_file_get_integer(keyfile, groups[i], "uid", NULL);
if (u > 0 && !uid_in_list(list, u))
list = g_slist_prepend(list, GUINT_TO_POINTER(u));
}
g_strfreev(groups);
}
}
g_key_file_free(keyfile);
return list;
return list;
}
/* ConsoleKit calls us with special variables */
static int consolekit_called(const char *ck_action, uid_t *uid, uid_t *uid2, const char **remove_session_id, int *action)
{
int a = ACTION_NONE;
uid_t u = 0;
uid_t u2 = 0;
const char *s;
const char *s2;
const char *old_session = NULL;
int a = ACTION_NONE;
uid_t u = 0;
uid_t u2 = 0;
const char *s;
const char *s2;
const char *old_session = NULL;
if (ck_action == NULL || strcmp(ck_action, "seat_active_session_changed") != 0)
return -1;
if (ck_action == NULL || strcmp(ck_action, "seat_active_session_changed") != 0)
return -1;
/* We can have one of: remove, add, change, no-change */
s = getenv("CK_SEAT_OLD_SESSION_ID");
s2 = getenv("CK_SEAT_SESSION_ID");
if (s == NULL && s2 == NULL) {
return -1;
} else if (s2 == NULL) {
a = ACTION_REMOVE;
} else if (s == NULL) {
a = ACTION_ADD;
} else {
a = ACTION_CHANGE;
}
/* We can have one of: remove, add, change, no-change */
s = getenv("CK_SEAT_OLD_SESSION_ID");
s2 = getenv("CK_SEAT_SESSION_ID");
if (s == NULL && s2 == NULL) {
return -1;
} else if (s2 == NULL) {
a = ACTION_REMOVE;
} else if (s == NULL) {
a = ACTION_ADD;
} else {
a = ACTION_CHANGE;
}
switch (a) {
case ACTION_ADD:
s = getenv("CK_SEAT_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
switch (a) {
case ACTION_ADD:
s = getenv("CK_SEAT_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
s = getenv("CK_SEAT_SESSION_IS_LOCAL");
if (s == NULL)
return -1;
if (strcmp(s, "true") != 0)
return 0;
s = getenv("CK_SEAT_SESSION_IS_LOCAL");
if (s == NULL)
return -1;
if (strcmp(s, "true") != 0)
return 0;
break;
case ACTION_REMOVE:
s = getenv("CK_SEAT_OLD_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
break;
case ACTION_REMOVE:
s = getenv("CK_SEAT_OLD_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
s = getenv("CK_SEAT_OLD_SESSION_IS_LOCAL");
if (s == NULL)
return -1;
if (strcmp(s, "true") != 0)
return 0;
s = getenv("CK_SEAT_OLD_SESSION_IS_LOCAL");
if (s == NULL)
return -1;
if (strcmp(s, "true") != 0)
return 0;
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
break;
case ACTION_CHANGE:
s = getenv("CK_SEAT_OLD_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
s = getenv("CK_SEAT_SESSION_USER_UID");
if (s == NULL)
return -1;
u2 = strtoul(s, NULL, 10);
break;
case ACTION_CHANGE:
s = getenv("CK_SEAT_OLD_SESSION_USER_UID");
if (s == NULL)
return -1;
u = strtoul(s, NULL, 10);
s = getenv("CK_SEAT_SESSION_USER_UID");
if (s == NULL)
return -1;
u2 = strtoul(s, NULL, 10);
s = getenv("CK_SEAT_OLD_SESSION_IS_LOCAL");
s2 = getenv("CK_SEAT_SESSION_IS_LOCAL");
if (s == NULL || s2 == NULL)
return -1;
/* don't process non-local session changes */
if (strcmp(s, "true") != 0 && strcmp(s2, "true") != 0)
return 0;
s = getenv("CK_SEAT_OLD_SESSION_IS_LOCAL");
s2 = getenv("CK_SEAT_SESSION_IS_LOCAL");
if (s == NULL || s2 == NULL)
return -1;
/* don't process non-local session changes */
if (strcmp(s, "true") != 0 && strcmp(s2, "true") != 0)
return 0;
if (strcmp(s, "true") == 0 && strcmp(s, "true") == 0) {
/* process the change */
if (u == u2) {
/* special case: we noop if we are
* changing between local sessions for
* the same uid */
a = ACTION_NONE;
}
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
} else if (strcmp(s, "true") == 0) {
/* only process the removal */
a = ACTION_REMOVE;
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
} else if (strcmp(s2, "true") == 0) {
/* only process the addition */
a = ACTION_ADD;
u = u2;
}
break;
}
if (strcmp(s, "true") == 0 && strcmp(s, "true") == 0) {
/* process the change */
if (u == u2) {
/* special case: we noop if we are
* changing between local sessions for
* the same uid */
a = ACTION_NONE;
}
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
} else if (strcmp(s, "true") == 0) {
/* only process the removal */
a = ACTION_REMOVE;
old_session = getenv("CK_SEAT_OLD_SESSION_ID");
if (old_session == NULL)
return -1;
} else if (strcmp(s2, "true") == 0) {
/* only process the addition */
a = ACTION_ADD;
u = u2;
}
break;
}
*remove_session_id = old_session;
*uid = u;
*uid2 = u2;
*action = a;
return 0;
*remove_session_id = old_session;
*uid = u;
*uid2 = u2;
*action = a;
return 0;
}
/* add or remove a ACL for a given uid from all matching devices */
static void apply_acl_to_devices(uid_t uid, int add)
{
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *list_entry;
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *list_entry;
/* iterate over all devices tagged with ACL_SET */
udev = udev_new();
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_tag(enumerate, "udev-acl");
udev_enumerate_scan_devices(enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
const char *node;
/* iterate over all devices tagged with ACL_SET */
udev = udev_new();
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_tag(enumerate, "udev-acl");
udev_enumerate_scan_devices(enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
const char *node;
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device == NULL)
continue;
node = udev_device_get_devnode(device);
if (node == NULL) {
udev_device_unref(device);
continue;
}
set_facl(node, uid, add);
udev_device_unref(device);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device == NULL)
continue;
node = udev_device_get_devnode(device);
if (node == NULL) {
udev_device_unref(device);
continue;
}
set_facl(node, uid, add);
udev_device_unref(device);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
}
static void
remove_uid (uid_t uid, const char *remove_session_id)
{
/*
* Remove ACL for given uid from all matching devices
* when there is currently no local active session.
*/
GSList *list;
/*
* Remove ACL for given uid from all matching devices
* when there is currently no local active session.
*/
GSList *list;
list = uids_with_local_active_session(remove_session_id);
if (!uid_in_list(list, uid))
apply_acl_to_devices(uid, 0);
g_slist_free(list);
list = uids_with_local_active_session(remove_session_id);
if (!uid_in_list(list, uid))
apply_acl_to_devices(uid, 0);
g_slist_free(list);
}
int main (int argc, char* argv[])
{
static const struct option options[] = {
{ "action", required_argument, NULL, 'a' },
{ "device", required_argument, NULL, 'D' },
{ "user", required_argument, NULL, 'u' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
int action = -1;
const char *device = NULL;
bool uid_given = false;
uid_t uid = 0;
uid_t uid2 = 0;
const char* remove_session_id = NULL;
int rc = 0;
static const struct option options[] = {
{ "action", required_argument, NULL, 'a' },
{ "device", required_argument, NULL, 'D' },
{ "user", required_argument, NULL, 'u' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{}
};
int action = -1;
const char *device = NULL;
bool uid_given = false;
uid_t uid = 0;
uid_t uid2 = 0;
const char* remove_session_id = NULL;
int rc = 0;
/* valgrind is more important to us than a slice allocator */
g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, 1);
/* valgrind is more important to us than a slice allocator */
g_slice_set_config (G_SLICE_CONFIG_ALWAYS_MALLOC, 1);
while (1) {
int option;
while (1) {
int option;
option = getopt_long(argc, argv, "+a:D:u:dh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "+a:D:u:dh", options, NULL);
if (option == -1)
break;
switch (option) {
case 'a':
if (strcmp(optarg, "remove") == 0)
action = ACTION_REMOVE;
else
action = ACTION_ADD;
break;
case 'D':
device = optarg;
break;
case 'u':
uid_given = true;
uid = strtoul(optarg, NULL, 10);
break;
case 'd':
debug = 1;
break;
case 'h':
printf("Usage: udev-acl --action=ACTION [--device=DEVICEFILE] [--user=UID]\n\n");
goto out;
}
}
switch (option) {
case 'a':
if (strcmp(optarg, "remove") == 0)
action = ACTION_REMOVE;
else
action = ACTION_ADD;
break;
case 'D':
device = optarg;
break;
case 'u':
uid_given = true;
uid = strtoul(optarg, NULL, 10);
break;
case 'd':
debug = 1;
break;
case 'h':
printf("Usage: udev-acl --action=ACTION [--device=DEVICEFILE] [--user=UID]\n\n");
goto out;
}
}
if (action < 0 && device == NULL && !uid_given)
if (!consolekit_called(argv[optind], &uid, &uid2, &remove_session_id, &action))
uid_given = true;
if (action < 0 && device == NULL && !uid_given)
if (!consolekit_called(argv[optind], &uid, &uid2, &remove_session_id, &action))
uid_given = true;
if (action < 0) {
fprintf(stderr, "missing action\n\n");
rc = 2;
goto out;
}
if (action < 0) {
fprintf(stderr, "missing action\n\n");
rc = 2;
goto out;
}
if (device != NULL && uid_given) {
fprintf(stderr, "only one option, --device=DEVICEFILE or --user=UID expected\n\n");
rc = 3;
goto out;
}
if (device != NULL && uid_given) {
fprintf(stderr, "only one option, --device=DEVICEFILE or --user=UID expected\n\n");
rc = 3;
goto out;
}
if (uid_given) {
switch (action) {
case ACTION_ADD:
/* Add ACL for given uid to all matching devices. */
apply_acl_to_devices(uid, 1);
break;
case ACTION_REMOVE:
remove_uid(uid, remove_session_id);
break;
case ACTION_CHANGE:
remove_uid(uid, remove_session_id);
apply_acl_to_devices(uid2, 1);
break;
case ACTION_NONE:
goto out;
break;
default:
g_assert_not_reached();
break;
}
} else if (device != NULL) {
/*
* Add ACLs for all current session uids to a given device.
*
* Or remove ACLs for uids which do not have any current local
* active session. Remove is not really interesting, because in
* most cases the device node is removed anyway.
*/
GSList *list;
GSList *l;
if (uid_given) {
switch (action) {
case ACTION_ADD:
/* Add ACL for given uid to all matching devices. */
apply_acl_to_devices(uid, 1);
break;
case ACTION_REMOVE:
remove_uid(uid, remove_session_id);
break;
case ACTION_CHANGE:
remove_uid(uid, remove_session_id);
apply_acl_to_devices(uid2, 1);
break;
case ACTION_NONE:
goto out;
break;
default:
g_assert_not_reached();
break;
}
} else if (device != NULL) {
/*
* Add ACLs for all current session uids to a given device.
*
* Or remove ACLs for uids which do not have any current local
* active session. Remove is not really interesting, because in
* most cases the device node is removed anyway.
*/
GSList *list;
GSList *l;
list = uids_with_local_active_session(NULL);
for (l = list; l != NULL; l = g_slist_next(l)) {
uid_t u;
list = uids_with_local_active_session(NULL);
for (l = list; l != NULL; l = g_slist_next(l)) {
uid_t u;
u = GPOINTER_TO_UINT(l->data);
if (action == ACTION_ADD || !uid_in_list(list, u))
set_facl(device, u, action == ACTION_ADD);
}
g_slist_free(list);
} else {
fprintf(stderr, "--device=DEVICEFILE or --user=UID expected\n\n");
rc = 3;
}
u = GPOINTER_TO_UINT(l->data);
if (action == ACTION_ADD || !uid_in_list(list, u))
set_facl(device, u, action == ACTION_ADD);
}
g_slist_free(list);
} else {
fprintf(stderr, "--device=DEVICEFILE or --user=UID expected\n\n");
rc = 3;
}
out:
return rc;
return rc;
}
+46 -46
View File
@@ -32,56 +32,56 @@
int main (int argc, char *argv[])
{
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{}
};
int fd;
char *device;
struct v4l2_capability v2cap;
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{}
};
int fd;
char *device;
struct v4l2_capability v2cap;
while (1) {
int option;
while (1) {
int option;
option = getopt_long(argc, argv, "h", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "h", options, NULL);
if (option == -1)
break;
switch (option) {
case 'h':
printf("Usage: v4l_id [--help] <device file>\n\n");
return 0;
default:
return 1;
}
}
device = argv[optind];
switch (option) {
case 'h':
printf("Usage: v4l_id [--help] <device file>\n\n");
return 0;
default:
return 1;
}
}
device = argv[optind];
if (device == NULL)
return 2;
fd = open (device, O_RDONLY);
if (fd < 0)
return 3;
if (device == NULL)
return 2;
fd = open (device, O_RDONLY);
if (fd < 0)
return 3;
if (ioctl (fd, VIDIOC_QUERYCAP, &v2cap) == 0) {
printf("ID_V4L_VERSION=2\n");
printf("ID_V4L_PRODUCT=%s\n", v2cap.card);
printf("ID_V4L_CAPABILITIES=:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) > 0)
printf("capture:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) > 0)
printf("video_output:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OVERLAY) > 0)
printf("video_overlay:");
if ((v2cap.capabilities & V4L2_CAP_AUDIO) > 0)
printf("audio:");
if ((v2cap.capabilities & V4L2_CAP_TUNER) > 0)
printf("tuner:");
if ((v2cap.capabilities & V4L2_CAP_RADIO) > 0)
printf("radio:");
printf("\n");
}
if (ioctl (fd, VIDIOC_QUERYCAP, &v2cap) == 0) {
printf("ID_V4L_VERSION=2\n");
printf("ID_V4L_PRODUCT=%s\n", v2cap.card);
printf("ID_V4L_CAPABILITIES=:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) > 0)
printf("capture:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) > 0)
printf("video_output:");
if ((v2cap.capabilities & V4L2_CAP_VIDEO_OVERLAY) > 0)
printf("video_overlay:");
if ((v2cap.capabilities & V4L2_CAP_AUDIO) > 0)
printf("audio:");
if ((v2cap.capabilities & V4L2_CAP_TUNER) > 0)
printf("tuner:");
if ((v2cap.capabilities & V4L2_CAP_RADIO) > 0)
printf("radio:");
printf("\n");
}
close (fd);
return 0;
close (fd);
return 0;
}
+120 -120
View File
@@ -24,162 +24,162 @@
static void udev_device_tag(struct udev_device *dev, const char *tag, bool add)
{
const char *id;
struct udev *udev = udev_device_get_udev(dev);
char filename[UTIL_PATH_SIZE];
const char *id;
struct udev *udev = udev_device_get_udev(dev);
char filename[UTIL_PATH_SIZE];
id = udev_device_get_id_filename(dev);
if (id == NULL)
return;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/tags/", tag, "/", id, NULL);
id = udev_device_get_id_filename(dev);
if (id == NULL)
return;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/tags/", tag, "/", id, NULL);
if (add) {
int fd;
if (add) {
int fd;
util_create_path(udev, filename);
fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
if (fd >= 0)
close(fd);
} else {
unlink(filename);
}
util_create_path(udev, filename);
fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
if (fd >= 0)
close(fd);
} else {
unlink(filename);
}
}
int udev_device_tag_index(struct udev_device *dev, struct udev_device *dev_old, bool add)
{
struct udev_list_entry *list_entry;
bool found;
struct udev_list_entry *list_entry;
bool found;
if (add && dev_old != NULL) {
/* delete possible left-over tags */
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev_old)) {
const char *tag_old = udev_list_entry_get_name(list_entry);
struct udev_list_entry *list_entry_current;
if (add && dev_old != NULL) {
/* delete possible left-over tags */
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev_old)) {
const char *tag_old = udev_list_entry_get_name(list_entry);
struct udev_list_entry *list_entry_current;
found = false;
udev_list_entry_foreach(list_entry_current, udev_device_get_tags_list_entry(dev)) {
const char *tag = udev_list_entry_get_name(list_entry_current);
found = false;
udev_list_entry_foreach(list_entry_current, udev_device_get_tags_list_entry(dev)) {
const char *tag = udev_list_entry_get_name(list_entry_current);
if (strcmp(tag, tag_old) == 0) {
found = true;
break;
}
}
if (!found)
udev_device_tag(dev_old, tag_old, false);
}
}
if (strcmp(tag, tag_old) == 0) {
found = true;
break;
}
}
if (!found)
udev_device_tag(dev_old, tag_old, false);
}
}
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev))
udev_device_tag(dev, udev_list_entry_get_name(list_entry), add);
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(dev))
udev_device_tag(dev, udev_list_entry_get_name(list_entry), add);
return 0;
return 0;
}
static bool device_has_info(struct udev_device *udev_device)
{
struct udev_list_entry *list_entry;
struct udev_list_entry *list_entry;
if (udev_device_get_devlinks_list_entry(udev_device) != NULL)
return true;
if (udev_device_get_devlink_priority(udev_device) != 0)
return true;
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device))
if (udev_list_entry_get_num(list_entry))
return true;
if (udev_device_get_tags_list_entry(udev_device) != NULL)
return true;
if (udev_device_get_watch_handle(udev_device) >= 0)
return true;
return false;
if (udev_device_get_devlinks_list_entry(udev_device) != NULL)
return true;
if (udev_device_get_devlink_priority(udev_device) != 0)
return true;
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device))
if (udev_list_entry_get_num(list_entry))
return true;
if (udev_device_get_tags_list_entry(udev_device) != NULL)
return true;
if (udev_device_get_watch_handle(udev_device) >= 0)
return true;
return false;
}
int udev_device_update_db(struct udev_device *udev_device)
{
bool has_info;
const char *id;
struct udev *udev = udev_device_get_udev(udev_device);
char filename[UTIL_PATH_SIZE];
char filename_tmp[UTIL_PATH_SIZE];
FILE *f;
bool has_info;
const char *id;
struct udev *udev = udev_device_get_udev(udev_device);
char filename[UTIL_PATH_SIZE];
char filename_tmp[UTIL_PATH_SIZE];
FILE *f;
id = udev_device_get_id_filename(udev_device);
if (id == NULL)
return -1;
id = udev_device_get_id_filename(udev_device);
if (id == NULL)
return -1;
has_info = device_has_info(udev_device);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data/", id, NULL);
has_info = device_has_info(udev_device);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data/", id, NULL);
/* do not store anything for otherwise empty devices */
if (!has_info &&
major(udev_device_get_devnum(udev_device)) == 0 &&
udev_device_get_ifindex(udev_device) == 0) {
unlink(filename);
return 0;
}
/* do not store anything for otherwise empty devices */
if (!has_info &&
major(udev_device_get_devnum(udev_device)) == 0 &&
udev_device_get_ifindex(udev_device) == 0) {
unlink(filename);
return 0;
}
/* write a database file */
util_strscpyl(filename_tmp, sizeof(filename_tmp), filename, ".tmp", NULL);
util_create_path(udev, filename_tmp);
f = fopen(filename_tmp, "we");
if (f == NULL) {
err(udev, "unable to create temporary db file '%s': %m\n", filename_tmp);
return -1;
}
/* write a database file */
util_strscpyl(filename_tmp, sizeof(filename_tmp), filename, ".tmp", NULL);
util_create_path(udev, filename_tmp);
f = fopen(filename_tmp, "we");
if (f == NULL) {
err(udev, "unable to create temporary db file '%s': %m\n", filename_tmp);
return -1;
}
/*
* set 'sticky' bit to indicate that we should not clean the
* database when we transition from initramfs to the real root
*/
if (udev_device_get_db_persist(udev_device))
fchmod(fileno(f), 01644);
/*
* set 'sticky' bit to indicate that we should not clean the
* database when we transition from initramfs to the real root
*/
if (udev_device_get_db_persist(udev_device))
fchmod(fileno(f), 01644);
if (has_info) {
struct udev_list_entry *list_entry;
if (has_info) {
struct udev_list_entry *list_entry;
if (major(udev_device_get_devnum(udev_device)) > 0) {
size_t devlen = strlen(udev_get_dev_path(udev))+1;
if (major(udev_device_get_devnum(udev_device)) > 0) {
size_t devlen = strlen(udev_get_dev_path(udev))+1;
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(udev_device))
fprintf(f, "S:%s\n", &udev_list_entry_get_name(list_entry)[devlen]);
if (udev_device_get_devlink_priority(udev_device) != 0)
fprintf(f, "L:%i\n", udev_device_get_devlink_priority(udev_device));
if (udev_device_get_watch_handle(udev_device) >= 0)
fprintf(f, "W:%i\n", udev_device_get_watch_handle(udev_device));
}
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(udev_device))
fprintf(f, "S:%s\n", &udev_list_entry_get_name(list_entry)[devlen]);
if (udev_device_get_devlink_priority(udev_device) != 0)
fprintf(f, "L:%i\n", udev_device_get_devlink_priority(udev_device));
if (udev_device_get_watch_handle(udev_device) >= 0)
fprintf(f, "W:%i\n", udev_device_get_watch_handle(udev_device));
}
if (udev_device_get_usec_initialized(udev_device) > 0)
fprintf(f, "I:%llu\n", udev_device_get_usec_initialized(udev_device));
if (udev_device_get_usec_initialized(udev_device) > 0)
fprintf(f, "I:%llu\n", udev_device_get_usec_initialized(udev_device));
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
if (!udev_list_entry_get_num(list_entry))
continue;
fprintf(f, "E:%s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
}
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
if (!udev_list_entry_get_num(list_entry))
continue;
fprintf(f, "E:%s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
}
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
fprintf(f, "G:%s\n", udev_list_entry_get_name(list_entry));
}
udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
fprintf(f, "G:%s\n", udev_list_entry_get_name(list_entry));
}
fclose(f);
rename(filename_tmp, filename);
info(udev, "created %s file '%s' for '%s'\n", has_info ? "db" : "empty",
filename, udev_device_get_devpath(udev_device));
return 0;
fclose(f);
rename(filename_tmp, filename);
info(udev, "created %s file '%s' for '%s'\n", has_info ? "db" : "empty",
filename, udev_device_get_devpath(udev_device));
return 0;
}
int udev_device_delete_db(struct udev_device *udev_device)
{
const char *id;
struct udev *udev = udev_device_get_udev(udev_device);
char filename[UTIL_PATH_SIZE];
const char *id;
struct udev *udev = udev_device_get_udev(udev_device);
char filename[UTIL_PATH_SIZE];
id = udev_device_get_id_filename(udev_device);
if (id == NULL)
return -1;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data/", id, NULL);
unlink(filename);
return 0;
id = udev_device_get_id_filename(udev_device);
if (id == NULL)
return -1;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data/", id, NULL);
unlink(filename);
return 0;
}
+985 -985
View File
File diff suppressed because it is too large Load Diff
+548 -548
View File
File diff suppressed because it is too large Load Diff
+176 -176
View File
@@ -33,232 +33,232 @@
* contains a name, and optionally a value.
*/
struct udev_list_entry {
struct udev_list_node node;
struct udev_list *list;
char *name;
char *value;
int num;
struct udev_list_node node;
struct udev_list *list;
char *name;
char *value;
int num;
};
/* the list's head points to itself if empty */
void udev_list_node_init(struct udev_list_node *list)
{
list->next = list;
list->prev = list;
list->next = list;
list->prev = list;
}
int udev_list_node_is_empty(struct udev_list_node *list)
{
return list->next == list;
return list->next == list;
}
static void udev_list_node_insert_between(struct udev_list_node *new,
struct udev_list_node *prev,
struct udev_list_node *next)
struct udev_list_node *prev,
struct udev_list_node *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
void udev_list_node_append(struct udev_list_node *new, struct udev_list_node *list)
{
udev_list_node_insert_between(new, list->prev, list);
udev_list_node_insert_between(new, list->prev, list);
}
void udev_list_node_remove(struct udev_list_node *entry)
{
struct udev_list_node *prev = entry->prev;
struct udev_list_node *next = entry->next;
struct udev_list_node *prev = entry->prev;
struct udev_list_node *next = entry->next;
next->prev = prev;
prev->next = next;
next->prev = prev;
prev->next = next;
entry->prev = NULL;
entry->next = NULL;
entry->prev = NULL;
entry->next = NULL;
}
/* return list entry which embeds this node */
static struct udev_list_entry *list_node_to_entry(struct udev_list_node *node)
{
char *list;
char *list;
list = (char *)node;
list -= offsetof(struct udev_list_entry, node);
return (struct udev_list_entry *)list;
list = (char *)node;
list -= offsetof(struct udev_list_entry, node);
return (struct udev_list_entry *)list;
}
void udev_list_init(struct udev *udev, struct udev_list *list, bool unique)
{
memset(list, 0x00, sizeof(struct udev_list));
list->udev = udev;
list->unique = unique;
udev_list_node_init(&list->node);
memset(list, 0x00, sizeof(struct udev_list));
list->udev = udev;
list->unique = unique;
udev_list_node_init(&list->node);
}
/* insert entry into a list as the last element */
void udev_list_entry_append(struct udev_list_entry *new, struct udev_list *list)
{
/* inserting before the list head make the node the last node in the list */
udev_list_node_insert_between(&new->node, list->node.prev, &list->node);
new->list = list;
/* inserting before the list head make the node the last node in the list */
udev_list_node_insert_between(&new->node, list->node.prev, &list->node);
new->list = list;
}
/* insert entry into a list, before a given existing entry */
void udev_list_entry_insert_before(struct udev_list_entry *new, struct udev_list_entry *entry)
{
udev_list_node_insert_between(&new->node, entry->node.prev, &entry->node);
new->list = entry->list;
udev_list_node_insert_between(&new->node, entry->node.prev, &entry->node);
new->list = entry->list;
}
/* binary search in sorted array */
static int list_search(struct udev_list *list, const char *name)
{
unsigned int first, last;
unsigned int first, last;
first = 0;
last = list->entries_cur;
while (first < last) {
unsigned int i;
int cmp;
first = 0;
last = list->entries_cur;
while (first < last) {
unsigned int i;
int cmp;
i = (first + last)/2;
cmp = strcmp(name, list->entries[i]->name);
if (cmp < 0)
last = i;
else if (cmp > 0)
first = i+1;
else
return i;
}
i = (first + last)/2;
cmp = strcmp(name, list->entries[i]->name);
if (cmp < 0)
last = i;
else if (cmp > 0)
first = i+1;
else
return i;
}
/* not found, return negative insertion-index+1 */
return -(first+1);
/* not found, return negative insertion-index+1 */
return -(first+1);
}
struct udev_list_entry *udev_list_entry_add(struct udev_list *list, const char *name, const char *value)
{
struct udev_list_entry *entry;
int i = 0;
struct udev_list_entry *entry;
int i = 0;
if (list->unique) {
/* lookup existing name or insertion-index */
i = list_search(list, name);
if (i >= 0) {
entry = list->entries[i];
if (list->unique) {
/* lookup existing name or insertion-index */
i = list_search(list, name);
if (i >= 0) {
entry = list->entries[i];
dbg(list->udev, "'%s' is already in the list\n", name);
free(entry->value);
if (value == NULL) {
entry->value = NULL;
dbg(list->udev, "'%s' value unset\n", name);
return entry;
}
entry->value = strdup(value);
if (entry->value == NULL)
return NULL;
dbg(list->udev, "'%s' value replaced with '%s'\n", name, value);
return entry;
}
}
dbg(list->udev, "'%s' is already in the list\n", name);
free(entry->value);
if (value == NULL) {
entry->value = NULL;
dbg(list->udev, "'%s' value unset\n", name);
return entry;
}
entry->value = strdup(value);
if (entry->value == NULL)
return NULL;
dbg(list->udev, "'%s' value replaced with '%s'\n", name, value);
return entry;
}
}
/* add new name */
entry = calloc(1, sizeof(struct udev_list_entry));
if (entry == NULL)
return NULL;
entry->name = strdup(name);
if (entry->name == NULL) {
free(entry);
return NULL;
}
if (value != NULL) {
entry->value = strdup(value);
if (entry->value == NULL) {
free(entry->name);
free(entry);
return NULL;
}
}
/* add new name */
entry = calloc(1, sizeof(struct udev_list_entry));
if (entry == NULL)
return NULL;
entry->name = strdup(name);
if (entry->name == NULL) {
free(entry);
return NULL;
}
if (value != NULL) {
entry->value = strdup(value);
if (entry->value == NULL) {
free(entry->name);
free(entry);
return NULL;
}
}
if (list->unique) {
/* allocate or enlarge sorted array if needed */
if (list->entries_cur >= list->entries_max) {
unsigned int add;
if (list->unique) {
/* allocate or enlarge sorted array if needed */
if (list->entries_cur >= list->entries_max) {
unsigned int add;
add = list->entries_max;
if (add < 1)
add = 64;
list->entries = realloc(list->entries, (list->entries_max + add) * sizeof(struct udev_list_entry *));
if (list->entries == NULL) {
free(entry->name);
free(entry->value);
return NULL;
}
list->entries_max += add;
}
add = list->entries_max;
if (add < 1)
add = 64;
list->entries = realloc(list->entries, (list->entries_max + add) * sizeof(struct udev_list_entry *));
if (list->entries == NULL) {
free(entry->name);
free(entry->value);
return NULL;
}
list->entries_max += add;
}
/* the negative i returned the insertion index */
i = (-i)-1;
/* the negative i returned the insertion index */
i = (-i)-1;
/* insert into sorted list */
if ((unsigned int)i < list->entries_cur)
udev_list_entry_insert_before(entry, list->entries[i]);
else
udev_list_entry_append(entry, list);
/* insert into sorted list */
if ((unsigned int)i < list->entries_cur)
udev_list_entry_insert_before(entry, list->entries[i]);
else
udev_list_entry_append(entry, list);
/* insert into sorted array */
memmove(&list->entries[i+1], &list->entries[i],
(list->entries_cur - i) * sizeof(struct udev_list_entry *));
list->entries[i] = entry;
list->entries_cur++;
} else {
udev_list_entry_append(entry, list);
}
/* insert into sorted array */
memmove(&list->entries[i+1], &list->entries[i],
(list->entries_cur - i) * sizeof(struct udev_list_entry *));
list->entries[i] = entry;
list->entries_cur++;
} else {
udev_list_entry_append(entry, list);
}
dbg(list->udev, "'%s=%s' added\n", entry->name, entry->value);
return entry;
dbg(list->udev, "'%s=%s' added\n", entry->name, entry->value);
return entry;
}
void udev_list_entry_delete(struct udev_list_entry *entry)
{
if (entry->list->entries != NULL) {
int i;
struct udev_list *list = entry->list;
if (entry->list->entries != NULL) {
int i;
struct udev_list *list = entry->list;
/* remove entry from sorted array */
i = list_search(list, entry->name);
if (i >= 0) {
memmove(&list->entries[i], &list->entries[i+1],
((list->entries_cur-1) - i) * sizeof(struct udev_list_entry *));
list->entries_cur--;
}
}
/* remove entry from sorted array */
i = list_search(list, entry->name);
if (i >= 0) {
memmove(&list->entries[i], &list->entries[i+1],
((list->entries_cur-1) - i) * sizeof(struct udev_list_entry *));
list->entries_cur--;
}
}
udev_list_node_remove(&entry->node);
free(entry->name);
free(entry->value);
free(entry);
udev_list_node_remove(&entry->node);
free(entry->name);
free(entry->value);
free(entry);
}
void udev_list_cleanup(struct udev_list *list)
{
struct udev_list_entry *entry_loop;
struct udev_list_entry *entry_tmp;
struct udev_list_entry *entry_loop;
struct udev_list_entry *entry_tmp;
free(list->entries);
list->entries = NULL;
list->entries_cur = 0;
list->entries_max = 0;
udev_list_entry_foreach_safe(entry_loop, entry_tmp, udev_list_get_entry(list))
udev_list_entry_delete(entry_loop);
free(list->entries);
list->entries = NULL;
list->entries_cur = 0;
list->entries_max = 0;
udev_list_entry_foreach_safe(entry_loop, entry_tmp, udev_list_get_entry(list))
udev_list_entry_delete(entry_loop);
}
struct udev_list_entry *udev_list_get_entry(struct udev_list *list)
{
if (udev_list_node_is_empty(&list->node))
return NULL;
return list_node_to_entry(list->node.next);
if (udev_list_node_is_empty(&list->node))
return NULL;
return list_node_to_entry(list->node.next);
}
/**
@@ -269,15 +269,15 @@ struct udev_list_entry *udev_list_get_entry(struct udev_list *list)
*/
UDEV_EXPORT struct udev_list_entry *udev_list_entry_get_next(struct udev_list_entry *list_entry)
{
struct udev_list_node *next;
struct udev_list_node *next;
if (list_entry == NULL)
return NULL;
next = list_entry->node.next;
/* empty list or no more entries */
if (next == &list_entry->list->node)
return NULL;
return list_node_to_entry(next);
if (list_entry == NULL)
return NULL;
next = list_entry->node.next;
/* empty list or no more entries */
if (next == &list_entry->list->node)
return NULL;
return list_node_to_entry(next);
}
/**
@@ -289,18 +289,18 @@ UDEV_EXPORT struct udev_list_entry *udev_list_entry_get_next(struct udev_list_en
*/
UDEV_EXPORT struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list_entry *list_entry, const char *name)
{
int i;
int i;
if (list_entry == NULL)
return NULL;
if (list_entry == NULL)
return NULL;
if (!list_entry->list->unique)
return NULL;
if (!list_entry->list->unique)
return NULL;
i = list_search(list_entry->list, name);
if (i < 0)
return NULL;
return list_entry->list->entries[i];
i = list_search(list_entry->list, name);
if (i < 0)
return NULL;
return list_entry->list->entries[i];
}
/**
@@ -311,9 +311,9 @@ UDEV_EXPORT struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list
*/
UDEV_EXPORT const char *udev_list_entry_get_name(struct udev_list_entry *list_entry)
{
if (list_entry == NULL)
return NULL;
return list_entry->name;
if (list_entry == NULL)
return NULL;
return list_entry->name;
}
/**
@@ -324,21 +324,21 @@ UDEV_EXPORT const char *udev_list_entry_get_name(struct udev_list_entry *list_en
*/
UDEV_EXPORT const char *udev_list_entry_get_value(struct udev_list_entry *list_entry)
{
if (list_entry == NULL)
return NULL;
return list_entry->value;
if (list_entry == NULL)
return NULL;
return list_entry->value;
}
int udev_list_entry_get_num(struct udev_list_entry *list_entry)
{
if (list_entry == NULL)
return -EINVAL;
return list_entry->num;
if (list_entry == NULL)
return -EINVAL;
return list_entry->num;
}
void udev_list_entry_set_num(struct udev_list_entry *list_entry, int num)
{
if (list_entry == NULL)
return;
list_entry->num = num;
if (list_entry == NULL)
return;
list_entry->num = num;
}
+518 -518
View File
File diff suppressed because it is too large Load Diff
+29 -29
View File
@@ -19,8 +19,8 @@
#include "libudev.h"
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#define READ_END 0
#define WRITE_END 1
#define READ_END 0
#define WRITE_END 1
static inline void __attribute__((always_inline, format(printf, 2, 3)))
udev_log_null(struct udev *udev, const char *format, ...) {}
@@ -49,19 +49,19 @@ udev_log_null(struct udev *udev, const char *format, ...) {}
static inline void udev_log_init(const char *program_name)
{
openlog(program_name, LOG_PID | LOG_CONS, LOG_DAEMON);
openlog(program_name, LOG_PID | LOG_CONS, LOG_DAEMON);
}
static inline void udev_log_close(void)
{
closelog();
closelog();
}
/* libudev.c */
void udev_log(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, ...)
__attribute__((format(printf, 6, 7)));
int priority, const char *file, int line, const char *fn,
const char *format, ...)
__attribute__((format(printf, 6, 7)));
int udev_get_rules_path(struct udev *udev, char **path[], unsigned long long *ts_usec[]);
struct udev_list_entry *udev_add_property(struct udev *udev, const char *key, const char *value);
struct udev_list_entry *udev_get_properties_list_entry(struct udev *udev);
@@ -107,20 +107,20 @@ int udev_device_tag_index(struct udev_device *dev, struct udev_device *dev_old,
int udev_monitor_disconnect(struct udev_monitor *udev_monitor);
int udev_monitor_allow_unicast_sender(struct udev_monitor *udev_monitor, struct udev_monitor *sender);
int udev_monitor_send_device(struct udev_monitor *udev_monitor,
struct udev_monitor *destination, struct udev_device *udev_device);
struct udev_monitor *destination, struct udev_device *udev_device);
struct udev_monitor *udev_monitor_new_from_netlink_fd(struct udev *udev, const char *name, int fd);
/* libudev-list.c */
struct udev_list_node {
struct udev_list_node *next, *prev;
struct udev_list_node *next, *prev;
};
struct udev_list {
struct udev *udev;
struct udev_list_node node;
struct udev_list_entry **entries;
unsigned int entries_cur;
unsigned int entries_max;
bool unique;
struct udev *udev;
struct udev_list_node node;
struct udev_list_entry **entries;
unsigned int entries_cur;
unsigned int entries_max;
bool unique;
};
#define UDEV_LIST(list) struct udev_list_node list = { &(list), &(list) }
void udev_list_node_init(struct udev_list_node *list);
@@ -128,13 +128,13 @@ int udev_list_node_is_empty(struct udev_list_node *list);
void udev_list_node_append(struct udev_list_node *new, struct udev_list_node *list);
void udev_list_node_remove(struct udev_list_node *entry);
#define udev_list_node_foreach(node, list) \
for (node = (list)->next; \
node != list; \
node = (node)->next)
for (node = (list)->next; \
node != list; \
node = (node)->next)
#define udev_list_node_foreach_safe(node, tmp, list) \
for (node = (list)->next, tmp = (node)->next; \
node != list; \
node = tmp, tmp = (tmp)->next)
for (node = (list)->next, tmp = (node)->next; \
node != list; \
node = tmp, tmp = (tmp)->next)
void udev_list_init(struct udev *udev, struct udev_list *list, bool unique);
void udev_list_cleanup(struct udev_list *list);
struct udev_list_entry *udev_list_get_entry(struct udev_list *list);
@@ -145,9 +145,9 @@ void udev_list_entry_append(struct udev_list_entry *new, struct udev_list *list)
int udev_list_entry_get_num(struct udev_list_entry *list_entry);
void udev_list_entry_set_num(struct udev_list_entry *list_entry, int num);
#define udev_list_entry_foreach_safe(entry, tmp, first) \
for (entry = first, tmp = udev_list_entry_get_next(entry); \
entry != NULL; \
entry = tmp, tmp = udev_list_entry_get_next(tmp))
for (entry = first, tmp = udev_list_entry_get_next(entry); \
entry != NULL; \
entry = tmp, tmp = udev_list_entry_get_next(tmp))
/* libudev-queue.c */
unsigned long long int udev_get_kernel_seqnum(struct udev *udev);
@@ -163,10 +163,10 @@ int udev_queue_export_device_queued(struct udev_queue_export *udev_queue_export,
int udev_queue_export_device_finished(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device);
/* libudev-util.c */
#define UTIL_PATH_SIZE 1024
#define UTIL_NAME_SIZE 512
#define UTIL_LINE_SIZE 16384
#define UDEV_ALLOWED_CHARS_INPUT "/ $%?,"
#define UTIL_PATH_SIZE 1024
#define UTIL_NAME_SIZE 512
#define UTIL_LINE_SIZE 16384
#define UDEV_ALLOWED_CHARS_INPUT "/ $%?,"
ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size);
int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size);
int util_log_priority(const char *priority);
@@ -189,7 +189,7 @@ int util_delete_path(struct udev *udev, const char *path);
uid_t util_lookup_user(struct udev *udev, const char *user);
gid_t util_lookup_group(struct udev *udev, const char *group);
int util_resolve_subsys_kernel(struct udev *udev, const char *string,
char *result, size_t maxsize, int read_value);
char *result, size_t maxsize, int read_value);
unsigned long long ts_usec(const struct timespec *ts);
unsigned long long now_usec(void);
+252 -252
View File
@@ -22,11 +22,11 @@
* with the same sequence number but a devpath len of 0.
*
* Example:
* { 0x0000000000000001 }
* { 0x0000000000000001, 0x0019, "/devices/virtual/mem/null" },
* { 0x0000000000000002, 0x001b, "/devices/virtual/mem/random" },
* { 0x0000000000000001, 0x0000 },
* { 0x0000000000000003, 0x0019, "/devices/virtual/mem/zero" },
* { 0x0000000000000001 }
* { 0x0000000000000001, 0x0019, "/devices/virtual/mem/null" },
* { 0x0000000000000002, 0x001b, "/devices/virtual/mem/random" },
* { 0x0000000000000001, 0x0000 },
* { 0x0000000000000003, 0x0019, "/devices/virtual/mem/zero" },
*
* Events 2 and 3 are still queued, but event 1 has finished.
*
@@ -55,83 +55,83 @@
static int rebuild_queue_file(struct udev_queue_export *udev_queue_export);
struct udev_queue_export {
struct udev *udev;
int queued_count; /* number of unfinished events exported in queue file */
FILE *queue_file;
unsigned long long int seqnum_max; /* earliest sequence number in queue file */
unsigned long long int seqnum_min; /* latest sequence number in queue file */
int waste_bytes; /* queue file bytes wasted on finished events */
struct udev *udev;
int queued_count; /* number of unfinished events exported in queue file */
FILE *queue_file;
unsigned long long int seqnum_max; /* earliest sequence number in queue file */
unsigned long long int seqnum_min; /* latest sequence number in queue file */
int waste_bytes; /* queue file bytes wasted on finished events */
};
struct udev_queue_export *udev_queue_export_new(struct udev *udev)
{
struct udev_queue_export *udev_queue_export;
unsigned long long int initial_seqnum;
struct udev_queue_export *udev_queue_export;
unsigned long long int initial_seqnum;
if (udev == NULL)
return NULL;
if (udev == NULL)
return NULL;
udev_queue_export = calloc(1, sizeof(struct udev_queue_export));
if (udev_queue_export == NULL)
return NULL;
udev_queue_export->udev = udev;
udev_queue_export = calloc(1, sizeof(struct udev_queue_export));
if (udev_queue_export == NULL)
return NULL;
udev_queue_export->udev = udev;
initial_seqnum = udev_get_kernel_seqnum(udev);
udev_queue_export->seqnum_min = initial_seqnum;
udev_queue_export->seqnum_max = initial_seqnum;
initial_seqnum = udev_get_kernel_seqnum(udev);
udev_queue_export->seqnum_min = initial_seqnum;
udev_queue_export->seqnum_max = initial_seqnum;
udev_queue_export_cleanup(udev_queue_export);
if (rebuild_queue_file(udev_queue_export) != 0) {
free(udev_queue_export);
return NULL;
}
udev_queue_export_cleanup(udev_queue_export);
if (rebuild_queue_file(udev_queue_export) != 0) {
free(udev_queue_export);
return NULL;
}
return udev_queue_export;
return udev_queue_export;
}
struct udev_queue_export *udev_queue_export_unref(struct udev_queue_export *udev_queue_export)
{
if (udev_queue_export == NULL)
return NULL;
if (udev_queue_export->queue_file != NULL)
fclose(udev_queue_export->queue_file);
free(udev_queue_export);
return NULL;
if (udev_queue_export == NULL)
return NULL;
if (udev_queue_export->queue_file != NULL)
fclose(udev_queue_export->queue_file);
free(udev_queue_export);
return NULL;
}
void udev_queue_export_cleanup(struct udev_queue_export *udev_queue_export)
{
char filename[UTIL_PATH_SIZE];
char filename[UTIL_PATH_SIZE];
if (udev_queue_export == NULL)
return;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.tmp", NULL);
unlink(filename);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.bin", NULL);
unlink(filename);
if (udev_queue_export == NULL)
return;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.tmp", NULL);
unlink(filename);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.bin", NULL);
unlink(filename);
}
static int skip_to(FILE *file, long offset)
{
long old_offset;
long old_offset;
/* fseek may drop buffered data, avoid it for small seeks */
old_offset = ftell(file);
if (offset > old_offset && offset - old_offset <= BUFSIZ) {
size_t skip_bytes = offset - old_offset;
char buf[skip_bytes];
/* fseek may drop buffered data, avoid it for small seeks */
old_offset = ftell(file);
if (offset > old_offset && offset - old_offset <= BUFSIZ) {
size_t skip_bytes = offset - old_offset;
char buf[skip_bytes];
if (fread(buf, skip_bytes, 1, file) != skip_bytes)
return -1;
}
if (fread(buf, skip_bytes, 1, file) != skip_bytes)
return -1;
}
return fseek(file, offset, SEEK_SET);
return fseek(file, offset, SEEK_SET);
}
struct queue_devpaths {
unsigned int devpaths_first; /* index of first queued event */
unsigned int devpaths_size;
long devpaths[]; /* seqnum -> offset of devpath in queue file (or 0) */
unsigned int devpaths_first; /* index of first queued event */
unsigned int devpaths_size;
long devpaths[]; /* seqnum -> offset of devpath in queue file (or 0) */
};
/*
@@ -140,273 +140,273 @@ struct queue_devpaths {
*/
static struct queue_devpaths *build_index(struct udev_queue_export *udev_queue_export)
{
struct queue_devpaths *devpaths;
unsigned long long int range;
long devpath_offset;
ssize_t devpath_len;
unsigned long long int seqnum;
unsigned long long int n;
unsigned int i;
struct queue_devpaths *devpaths;
unsigned long long int range;
long devpath_offset;
ssize_t devpath_len;
unsigned long long int seqnum;
unsigned long long int n;
unsigned int i;
/* seek to the first event in the file */
rewind(udev_queue_export->queue_file);
udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum);
/* seek to the first event in the file */
rewind(udev_queue_export->queue_file);
udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum);
/* allocate the table */
range = udev_queue_export->seqnum_min - udev_queue_export->seqnum_max;
if (range - 1 > INT_MAX) {
err(udev_queue_export->udev, "queue file overflow\n");
return NULL;
}
devpaths = calloc(1, sizeof(struct queue_devpaths) + (range + 1) * sizeof(long));
if (devpaths == NULL)
return NULL;
devpaths->devpaths_size = range + 1;
/* allocate the table */
range = udev_queue_export->seqnum_min - udev_queue_export->seqnum_max;
if (range - 1 > INT_MAX) {
err(udev_queue_export->udev, "queue file overflow\n");
return NULL;
}
devpaths = calloc(1, sizeof(struct queue_devpaths) + (range + 1) * sizeof(long));
if (devpaths == NULL)
return NULL;
devpaths->devpaths_size = range + 1;
/* read all records and populate the table */
for (;;) {
if (udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum) < 0)
break;
n = seqnum - udev_queue_export->seqnum_max;
if (n >= devpaths->devpaths_size)
goto read_error;
/* read all records and populate the table */
for (;;) {
if (udev_queue_read_seqnum(udev_queue_export->queue_file, &seqnum) < 0)
break;
n = seqnum - udev_queue_export->seqnum_max;
if (n >= devpaths->devpaths_size)
goto read_error;
devpath_offset = ftell(udev_queue_export->queue_file);
devpath_len = udev_queue_skip_devpath(udev_queue_export->queue_file);
if (devpath_len < 0)
goto read_error;
devpath_offset = ftell(udev_queue_export->queue_file);
devpath_len = udev_queue_skip_devpath(udev_queue_export->queue_file);
if (devpath_len < 0)
goto read_error;
if (devpath_len > 0)
devpaths->devpaths[n] = devpath_offset;
else
devpaths->devpaths[n] = 0;
}
if (devpath_len > 0)
devpaths->devpaths[n] = devpath_offset;
else
devpaths->devpaths[n] = 0;
}
/* find first queued event */
for (i = 0; i < devpaths->devpaths_size; i++) {
if (devpaths->devpaths[i] != 0)
break;
}
devpaths->devpaths_first = i;
/* find first queued event */
for (i = 0; i < devpaths->devpaths_size; i++) {
if (devpaths->devpaths[i] != 0)
break;
}
devpaths->devpaths_first = i;
return devpaths;
return devpaths;
read_error:
err(udev_queue_export->udev, "queue file corrupted\n");
free(devpaths);
return NULL;
err(udev_queue_export->udev, "queue file corrupted\n");
free(devpaths);
return NULL;
}
static int rebuild_queue_file(struct udev_queue_export *udev_queue_export)
{
unsigned long long int seqnum;
struct queue_devpaths *devpaths = NULL;
char filename[UTIL_PATH_SIZE];
char filename_tmp[UTIL_PATH_SIZE];
FILE *new_queue_file = NULL;
unsigned int i;
unsigned long long int seqnum;
struct queue_devpaths *devpaths = NULL;
char filename[UTIL_PATH_SIZE];
char filename_tmp[UTIL_PATH_SIZE];
FILE *new_queue_file = NULL;
unsigned int i;
/* read old queue file */
if (udev_queue_export->queue_file != NULL) {
dbg(udev_queue_export->udev, "compacting queue file, freeing %d bytes\n",
udev_queue_export->waste_bytes);
/* read old queue file */
if (udev_queue_export->queue_file != NULL) {
dbg(udev_queue_export->udev, "compacting queue file, freeing %d bytes\n",
udev_queue_export->waste_bytes);
devpaths = build_index(udev_queue_export);
if (devpaths != NULL)
udev_queue_export->seqnum_max += devpaths->devpaths_first;
}
if (devpaths == NULL) {
dbg(udev_queue_export->udev, "creating empty queue file\n");
udev_queue_export->queued_count = 0;
udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
}
devpaths = build_index(udev_queue_export);
if (devpaths != NULL)
udev_queue_export->seqnum_max += devpaths->devpaths_first;
}
if (devpaths == NULL) {
dbg(udev_queue_export->udev, "creating empty queue file\n");
udev_queue_export->queued_count = 0;
udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
}
/* create new queue file */
util_strscpyl(filename_tmp, sizeof(filename_tmp), udev_get_run_path(udev_queue_export->udev), "/queue.tmp", NULL);
new_queue_file = fopen(filename_tmp, "w+");
if (new_queue_file == NULL)
goto error;
seqnum = udev_queue_export->seqnum_max;
fwrite(&seqnum, 1, sizeof(unsigned long long int), new_queue_file);
/* create new queue file */
util_strscpyl(filename_tmp, sizeof(filename_tmp), udev_get_run_path(udev_queue_export->udev), "/queue.tmp", NULL);
new_queue_file = fopen(filename_tmp, "w+");
if (new_queue_file == NULL)
goto error;
seqnum = udev_queue_export->seqnum_max;
fwrite(&seqnum, 1, sizeof(unsigned long long int), new_queue_file);
/* copy unfinished events only to the new file */
if (devpaths != NULL) {
for (i = devpaths->devpaths_first; i < devpaths->devpaths_size; i++) {
char devpath[UTIL_PATH_SIZE];
int err;
unsigned short devpath_len;
/* copy unfinished events only to the new file */
if (devpaths != NULL) {
for (i = devpaths->devpaths_first; i < devpaths->devpaths_size; i++) {
char devpath[UTIL_PATH_SIZE];
int err;
unsigned short devpath_len;
if (devpaths->devpaths[i] != 0)
{
skip_to(udev_queue_export->queue_file, devpaths->devpaths[i]);
err = udev_queue_read_devpath(udev_queue_export->queue_file, devpath, sizeof(devpath));
devpath_len = err;
if (devpaths->devpaths[i] != 0)
{
skip_to(udev_queue_export->queue_file, devpaths->devpaths[i]);
err = udev_queue_read_devpath(udev_queue_export->queue_file, devpath, sizeof(devpath));
devpath_len = err;
fwrite(&seqnum, sizeof(unsigned long long int), 1, new_queue_file);
fwrite(&devpath_len, sizeof(unsigned short), 1, new_queue_file);
fwrite(devpath, 1, devpath_len, new_queue_file);
}
seqnum++;
}
free(devpaths);
devpaths = NULL;
}
fflush(new_queue_file);
if (ferror(new_queue_file))
goto error;
fwrite(&seqnum, sizeof(unsigned long long int), 1, new_queue_file);
fwrite(&devpath_len, sizeof(unsigned short), 1, new_queue_file);
fwrite(devpath, 1, devpath_len, new_queue_file);
}
seqnum++;
}
free(devpaths);
devpaths = NULL;
}
fflush(new_queue_file);
if (ferror(new_queue_file))
goto error;
/* rename the new file on top of the old one */
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.bin", NULL);
if (rename(filename_tmp, filename) != 0)
goto error;
/* rename the new file on top of the old one */
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue_export->udev), "/queue.bin", NULL);
if (rename(filename_tmp, filename) != 0)
goto error;
if (udev_queue_export->queue_file != NULL)
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = new_queue_file;
udev_queue_export->waste_bytes = 0;
if (udev_queue_export->queue_file != NULL)
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = new_queue_file;
udev_queue_export->waste_bytes = 0;
return 0;
return 0;
error:
err(udev_queue_export->udev, "failed to create queue file: %m\n");
udev_queue_export_cleanup(udev_queue_export);
err(udev_queue_export->udev, "failed to create queue file: %m\n");
udev_queue_export_cleanup(udev_queue_export);
if (udev_queue_export->queue_file != NULL) {
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
}
if (new_queue_file != NULL)
fclose(new_queue_file);
if (udev_queue_export->queue_file != NULL) {
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
}
if (new_queue_file != NULL)
fclose(new_queue_file);
if (devpaths != NULL)
free(devpaths);
udev_queue_export->queued_count = 0;
udev_queue_export->waste_bytes = 0;
udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
if (devpaths != NULL)
free(devpaths);
udev_queue_export->queued_count = 0;
udev_queue_export->waste_bytes = 0;
udev_queue_export->seqnum_max = udev_queue_export->seqnum_min;
return -1;
return -1;
}
static int write_queue_record(struct udev_queue_export *udev_queue_export,
unsigned long long int seqnum, const char *devpath, size_t devpath_len)
unsigned long long int seqnum, const char *devpath, size_t devpath_len)
{
unsigned short len;
unsigned short len;
if (udev_queue_export->queue_file == NULL) {
dbg(udev_queue_export->udev, "can't record event: queue file not available\n");
return -1;
}
if (udev_queue_export->queue_file == NULL) {
dbg(udev_queue_export->udev, "can't record event: queue file not available\n");
return -1;
}
if (fwrite(&seqnum, sizeof(unsigned long long int), 1, udev_queue_export->queue_file) != 1)
goto write_error;
if (fwrite(&seqnum, sizeof(unsigned long long int), 1, udev_queue_export->queue_file) != 1)
goto write_error;
len = (devpath_len < USHRT_MAX) ? devpath_len : USHRT_MAX;
if (fwrite(&len, sizeof(unsigned short), 1, udev_queue_export->queue_file) != 1)
goto write_error;
if (len > 0) {
if (fwrite(devpath, 1, len, udev_queue_export->queue_file) != len)
goto write_error;
}
len = (devpath_len < USHRT_MAX) ? devpath_len : USHRT_MAX;
if (fwrite(&len, sizeof(unsigned short), 1, udev_queue_export->queue_file) != 1)
goto write_error;
if (len > 0) {
if (fwrite(devpath, 1, len, udev_queue_export->queue_file) != len)
goto write_error;
}
/* *must* flush output; caller may fork */
if (fflush(udev_queue_export->queue_file) != 0)
goto write_error;
/* *must* flush output; caller may fork */
if (fflush(udev_queue_export->queue_file) != 0)
goto write_error;
return 0;
return 0;
write_error:
/* if we failed half way through writing a record to a file,
we should not try to write any further records to it. */
err(udev_queue_export->udev, "error writing to queue file: %m\n");
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
/* if we failed half way through writing a record to a file,
we should not try to write any further records to it. */
err(udev_queue_export->udev, "error writing to queue file: %m\n");
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
return -1;
return -1;
}
enum device_state {
DEVICE_QUEUED,
DEVICE_FINISHED,
DEVICE_QUEUED,
DEVICE_FINISHED,
};
static inline size_t queue_record_size(size_t devpath_len)
{
return sizeof(unsigned long long int) + sizeof(unsigned short int) + devpath_len;
return sizeof(unsigned long long int) + sizeof(unsigned short int) + devpath_len;
}
static int update_queue(struct udev_queue_export *udev_queue_export,
struct udev_device *udev_device, enum device_state state)
struct udev_device *udev_device, enum device_state state)
{
unsigned long long int seqnum = udev_device_get_seqnum(udev_device);
const char *devpath = NULL;
size_t devpath_len = 0;
int bytes;
int err;
unsigned long long int seqnum = udev_device_get_seqnum(udev_device);
const char *devpath = NULL;
size_t devpath_len = 0;
int bytes;
int err;
/* FINISHED records have a zero length devpath */
if (state == DEVICE_QUEUED) {
devpath = udev_device_get_devpath(udev_device);
devpath_len = strlen(devpath);
}
/* FINISHED records have a zero length devpath */
if (state == DEVICE_QUEUED) {
devpath = udev_device_get_devpath(udev_device);
devpath_len = strlen(devpath);
}
/* recover from an earlier failed rebuild */
if (udev_queue_export->queue_file == NULL) {
if (rebuild_queue_file(udev_queue_export) != 0)
return -1;
}
/* recover from an earlier failed rebuild */
if (udev_queue_export->queue_file == NULL) {
if (rebuild_queue_file(udev_queue_export) != 0)
return -1;
}
/* if we're removing the last event from the queue, that's the best time to rebuild it */
if (state != DEVICE_QUEUED && udev_queue_export->queued_count == 1) {
/* we don't need to read the old queue file */
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
rebuild_queue_file(udev_queue_export);
return 0;
}
/* if we're removing the last event from the queue, that's the best time to rebuild it */
if (state != DEVICE_QUEUED && udev_queue_export->queued_count == 1) {
/* we don't need to read the old queue file */
fclose(udev_queue_export->queue_file);
udev_queue_export->queue_file = NULL;
rebuild_queue_file(udev_queue_export);
return 0;
}
/* try to rebuild the queue files before they grow larger than one page. */
bytes = ftell(udev_queue_export->queue_file) + queue_record_size(devpath_len);
if ((udev_queue_export->waste_bytes > bytes / 2) && bytes > 4096)
rebuild_queue_file(udev_queue_export);
/* try to rebuild the queue files before they grow larger than one page. */
bytes = ftell(udev_queue_export->queue_file) + queue_record_size(devpath_len);
if ((udev_queue_export->waste_bytes > bytes / 2) && bytes > 4096)
rebuild_queue_file(udev_queue_export);
/* don't record a finished event, if we already dropped the event in a failed rebuild */
if (seqnum < udev_queue_export->seqnum_max)
return 0;
/* don't record a finished event, if we already dropped the event in a failed rebuild */
if (seqnum < udev_queue_export->seqnum_max)
return 0;
/* now write to the queue */
if (state == DEVICE_QUEUED) {
udev_queue_export->queued_count++;
udev_queue_export->seqnum_min = seqnum;
} else {
udev_queue_export->waste_bytes += queue_record_size(devpath_len) + queue_record_size(0);
udev_queue_export->queued_count--;
}
err = write_queue_record(udev_queue_export, seqnum, devpath, devpath_len);
/* now write to the queue */
if (state == DEVICE_QUEUED) {
udev_queue_export->queued_count++;
udev_queue_export->seqnum_min = seqnum;
} else {
udev_queue_export->waste_bytes += queue_record_size(devpath_len) + queue_record_size(0);
udev_queue_export->queued_count--;
}
err = write_queue_record(udev_queue_export, seqnum, devpath, devpath_len);
/* try to handle ENOSPC */
if (err != 0 && udev_queue_export->queued_count == 0) {
udev_queue_export_cleanup(udev_queue_export);
err = rebuild_queue_file(udev_queue_export);
}
/* try to handle ENOSPC */
if (err != 0 && udev_queue_export->queued_count == 0) {
udev_queue_export_cleanup(udev_queue_export);
err = rebuild_queue_file(udev_queue_export);
}
return err;
return err;
}
static int update(struct udev_queue_export *udev_queue_export,
struct udev_device *udev_device, enum device_state state)
struct udev_device *udev_device, enum device_state state)
{
if (update_queue(udev_queue_export, udev_device, state) != 0)
return -1;
if (update_queue(udev_queue_export, udev_device, state) != 0)
return -1;
return 0;
return 0;
}
int udev_queue_export_device_queued(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device)
{
return update(udev_queue_export, udev_device, DEVICE_QUEUED);
return update(udev_queue_export, udev_device, DEVICE_QUEUED);
}
int udev_queue_export_device_finished(struct udev_queue_export *udev_queue_export, struct udev_device *udev_device)
{
return update(udev_queue_export, udev_device, DEVICE_FINISHED);
return update(udev_queue_export, udev_device, DEVICE_FINISHED);
}
+238 -238
View File
@@ -40,9 +40,9 @@
* Opaque object representing the current event queue in the udev daemon.
*/
struct udev_queue {
struct udev *udev;
int refcount;
struct udev_list queue_list;
struct udev *udev;
int refcount;
struct udev_list queue_list;
};
/**
@@ -56,18 +56,18 @@ struct udev_queue {
**/
UDEV_EXPORT struct udev_queue *udev_queue_new(struct udev *udev)
{
struct udev_queue *udev_queue;
struct udev_queue *udev_queue;
if (udev == NULL)
return NULL;
if (udev == NULL)
return NULL;
udev_queue = calloc(1, sizeof(struct udev_queue));
if (udev_queue == NULL)
return NULL;
udev_queue->refcount = 1;
udev_queue->udev = udev;
udev_list_init(udev, &udev_queue->queue_list, false);
return udev_queue;
udev_queue = calloc(1, sizeof(struct udev_queue));
if (udev_queue == NULL)
return NULL;
udev_queue->refcount = 1;
udev_queue->udev = udev;
udev_list_init(udev, &udev_queue->queue_list, false);
return udev_queue;
}
/**
@@ -80,10 +80,10 @@ UDEV_EXPORT struct udev_queue *udev_queue_new(struct udev *udev)
**/
UDEV_EXPORT struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue)
{
if (udev_queue == NULL)
return NULL;
udev_queue->refcount++;
return udev_queue;
if (udev_queue == NULL)
return NULL;
udev_queue->refcount++;
return udev_queue;
}
/**
@@ -95,13 +95,13 @@ UDEV_EXPORT struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue)
**/
UDEV_EXPORT void udev_queue_unref(struct udev_queue *udev_queue)
{
if (udev_queue == NULL)
return;
udev_queue->refcount--;
if (udev_queue->refcount > 0)
return;
udev_list_cleanup(&udev_queue->queue_list);
free(udev_queue);
if (udev_queue == NULL)
return;
udev_queue->refcount--;
if (udev_queue->refcount > 0)
return;
udev_list_cleanup(&udev_queue->queue_list);
free(udev_queue);
}
/**
@@ -114,30 +114,30 @@ UDEV_EXPORT void udev_queue_unref(struct udev_queue *udev_queue)
**/
UDEV_EXPORT struct udev *udev_queue_get_udev(struct udev_queue *udev_queue)
{
if (udev_queue == NULL)
return NULL;
return udev_queue->udev;
if (udev_queue == NULL)
return NULL;
return udev_queue->udev;
}
unsigned long long int udev_get_kernel_seqnum(struct udev *udev)
{
char filename[UTIL_PATH_SIZE];
unsigned long long int seqnum;
int fd;
char buf[32];
ssize_t len;
char filename[UTIL_PATH_SIZE];
unsigned long long int seqnum;
int fd;
char buf[32];
ssize_t len;
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), "/kernel/uevent_seqnum", NULL);
fd = open(filename, O_RDONLY|O_CLOEXEC);
if (fd < 0)
return 0;
len = read(fd, buf, sizeof(buf));
close(fd);
if (len <= 2)
return 0;
buf[len-1] = '\0';
seqnum = strtoull(buf, NULL, 10);
return seqnum;
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), "/kernel/uevent_seqnum", NULL);
fd = open(filename, O_RDONLY|O_CLOEXEC);
if (fd < 0)
return 0;
len = read(fd, buf, sizeof(buf));
close(fd);
if (len <= 2)
return 0;
buf[len-1] = '\0';
seqnum = strtoull(buf, NULL, 10);
return seqnum;
}
/**
@@ -148,81 +148,81 @@ unsigned long long int udev_get_kernel_seqnum(struct udev *udev)
**/
UDEV_EXPORT unsigned long long int udev_queue_get_kernel_seqnum(struct udev_queue *udev_queue)
{
unsigned long long int seqnum;
unsigned long long int seqnum;
if (udev_queue == NULL)
return -EINVAL;
if (udev_queue == NULL)
return -EINVAL;
seqnum = udev_get_kernel_seqnum(udev_queue->udev);
dbg(udev_queue->udev, "seqnum=%llu\n", seqnum);
return seqnum;
seqnum = udev_get_kernel_seqnum(udev_queue->udev);
dbg(udev_queue->udev, "seqnum=%llu\n", seqnum);
return seqnum;
}
int udev_queue_read_seqnum(FILE *queue_file, unsigned long long int *seqnum)
{
if (fread(seqnum, sizeof(unsigned long long int), 1, queue_file) != 1)
return -1;
if (fread(seqnum, sizeof(unsigned long long int), 1, queue_file) != 1)
return -1;
return 0;
return 0;
}
ssize_t udev_queue_skip_devpath(FILE *queue_file)
{
unsigned short int len;
unsigned short int len;
if (fread(&len, sizeof(unsigned short int), 1, queue_file) == 1) {
char devpath[len];
if (fread(&len, sizeof(unsigned short int), 1, queue_file) == 1) {
char devpath[len];
/* use fread to skip, fseek might drop buffered data */
if (fread(devpath, 1, len, queue_file) == len)
return len;
}
/* use fread to skip, fseek might drop buffered data */
if (fread(devpath, 1, len, queue_file) == len)
return len;
}
return -1;
return -1;
}
ssize_t udev_queue_read_devpath(FILE *queue_file, char *devpath, size_t size)
{
unsigned short int read_bytes = 0;
unsigned short int len;
unsigned short int read_bytes = 0;
unsigned short int len;
if (fread(&len, sizeof(unsigned short int), 1, queue_file) != 1)
return -1;
if (fread(&len, sizeof(unsigned short int), 1, queue_file) != 1)
return -1;
read_bytes = (len < size - 1) ? len : size - 1;
if (fread(devpath, 1, read_bytes, queue_file) != read_bytes)
return -1;
devpath[read_bytes] = '\0';
read_bytes = (len < size - 1) ? len : size - 1;
if (fread(devpath, 1, read_bytes, queue_file) != read_bytes)
return -1;
devpath[read_bytes] = '\0';
/* if devpath was too long, skip unread characters */
if (read_bytes != len) {
unsigned short int skip_bytes = len - read_bytes;
char buf[skip_bytes];
/* if devpath was too long, skip unread characters */
if (read_bytes != len) {
unsigned short int skip_bytes = len - read_bytes;
char buf[skip_bytes];
if (fread(buf, 1, skip_bytes, queue_file) != skip_bytes)
return -1;
}
if (fread(buf, 1, skip_bytes, queue_file) != skip_bytes)
return -1;
}
return read_bytes;
return read_bytes;
}
static FILE *open_queue_file(struct udev_queue *udev_queue, unsigned long long int *seqnum_start)
{
char filename[UTIL_PATH_SIZE];
FILE *queue_file;
char filename[UTIL_PATH_SIZE];
FILE *queue_file;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue->udev), "/queue.bin", NULL);
queue_file = fopen(filename, "re");
if (queue_file == NULL)
return NULL;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev_queue->udev), "/queue.bin", NULL);
queue_file = fopen(filename, "re");
if (queue_file == NULL)
return NULL;
if (udev_queue_read_seqnum(queue_file, seqnum_start) < 0) {
err(udev_queue->udev, "corrupt queue file\n");
fclose(queue_file);
return NULL;
}
if (udev_queue_read_seqnum(queue_file, seqnum_start) < 0) {
err(udev_queue->udev, "corrupt queue file\n");
fclose(queue_file);
return NULL;
}
return queue_file;
return queue_file;
}
/**
@@ -233,28 +233,28 @@ static FILE *open_queue_file(struct udev_queue *udev_queue, unsigned long long i
**/
UDEV_EXPORT unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue *udev_queue)
{
unsigned long long int seqnum_udev;
FILE *queue_file;
unsigned long long int seqnum_udev;
FILE *queue_file;
queue_file = open_queue_file(udev_queue, &seqnum_udev);
if (queue_file == NULL)
return 0;
queue_file = open_queue_file(udev_queue, &seqnum_udev);
if (queue_file == NULL)
return 0;
for (;;) {
unsigned long long int seqnum;
ssize_t devpath_len;
for (;;) {
unsigned long long int seqnum;
ssize_t devpath_len;
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
if (devpath_len > 0)
seqnum_udev = seqnum;
}
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
if (devpath_len > 0)
seqnum_udev = seqnum;
}
fclose(queue_file);
return seqnum_udev;
fclose(queue_file);
return seqnum_udev;
}
/**
@@ -265,15 +265,15 @@ UDEV_EXPORT unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue
**/
UDEV_EXPORT int udev_queue_get_udev_is_active(struct udev_queue *udev_queue)
{
unsigned long long int seqnum_start;
FILE *queue_file;
unsigned long long int seqnum_start;
FILE *queue_file;
queue_file = open_queue_file(udev_queue, &seqnum_start);
if (queue_file == NULL)
return 0;
queue_file = open_queue_file(udev_queue, &seqnum_start);
if (queue_file == NULL)
return 0;
fclose(queue_file);
return 1;
fclose(queue_file);
return 1;
}
/**
@@ -284,54 +284,54 @@ UDEV_EXPORT int udev_queue_get_udev_is_active(struct udev_queue *udev_queue)
**/
UDEV_EXPORT int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue)
{
unsigned long long int seqnum_kernel;
unsigned long long int seqnum_udev = 0;
int queued = 0;
int is_empty = 0;
FILE *queue_file;
unsigned long long int seqnum_kernel;
unsigned long long int seqnum_udev = 0;
int queued = 0;
int is_empty = 0;
FILE *queue_file;
if (udev_queue == NULL)
return -EINVAL;
queue_file = open_queue_file(udev_queue, &seqnum_udev);
if (queue_file == NULL)
return 1;
if (udev_queue == NULL)
return -EINVAL;
queue_file = open_queue_file(udev_queue, &seqnum_udev);
if (queue_file == NULL)
return 1;
for (;;) {
unsigned long long int seqnum;
ssize_t devpath_len;
for (;;) {
unsigned long long int seqnum;
ssize_t devpath_len;
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
if (devpath_len > 0) {
queued++;
seqnum_udev = seqnum;
} else {
queued--;
}
}
if (devpath_len > 0) {
queued++;
seqnum_udev = seqnum;
} else {
queued--;
}
}
if (queued > 0) {
dbg(udev_queue->udev, "queue is not empty\n");
goto out;
}
if (queued > 0) {
dbg(udev_queue->udev, "queue is not empty\n");
goto out;
}
seqnum_kernel = udev_queue_get_kernel_seqnum(udev_queue);
if (seqnum_udev < seqnum_kernel) {
dbg(udev_queue->udev, "queue is empty but kernel events still pending [%llu]<->[%llu]\n",
seqnum_kernel, seqnum_udev);
goto out;
}
seqnum_kernel = udev_queue_get_kernel_seqnum(udev_queue);
if (seqnum_udev < seqnum_kernel) {
dbg(udev_queue->udev, "queue is empty but kernel events still pending [%llu]<->[%llu]\n",
seqnum_kernel, seqnum_udev);
goto out;
}
dbg(udev_queue->udev, "queue is empty\n");
is_empty = 1;
dbg(udev_queue->udev, "queue is empty\n");
is_empty = 1;
out:
fclose(queue_file);
return is_empty;
fclose(queue_file);
return is_empty;
}
/**
@@ -343,58 +343,58 @@ out:
* Returns: a flag indicating if any of the sequence numbers in the given range is currently active.
**/
UDEV_EXPORT int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
unsigned long long int start, unsigned long long int end)
unsigned long long int start, unsigned long long int end)
{
unsigned long long int seqnum;
ssize_t devpath_len;
int unfinished;
FILE *queue_file;
unsigned long long int seqnum;
ssize_t devpath_len;
int unfinished;
FILE *queue_file;
if (udev_queue == NULL)
return -EINVAL;
queue_file = open_queue_file(udev_queue, &seqnum);
if (queue_file == NULL)
return 1;
if (start < seqnum)
start = seqnum;
if (start > end) {
fclose(queue_file);
return 1;
}
if (end - start > INT_MAX - 1) {
fclose(queue_file);
return -EOVERFLOW;
}
if (udev_queue == NULL)
return -EINVAL;
queue_file = open_queue_file(udev_queue, &seqnum);
if (queue_file == NULL)
return 1;
if (start < seqnum)
start = seqnum;
if (start > end) {
fclose(queue_file);
return 1;
}
if (end - start > INT_MAX - 1) {
fclose(queue_file);
return -EOVERFLOW;
}
/*
* we might start with 0, and handle the initial seqnum
* only when we find an entry in the queue file
**/
unfinished = end - start;
/*
* we might start with 0, and handle the initial seqnum
* only when we find an entry in the queue file
**/
unfinished = end - start;
do {
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
do {
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
devpath_len = udev_queue_skip_devpath(queue_file);
if (devpath_len < 0)
break;
/*
* we might start with an empty or re-build queue file, where
* the initial seqnum is not recorded as finished
*/
if (start == seqnum && devpath_len > 0)
unfinished++;
/*
* we might start with an empty or re-build queue file, where
* the initial seqnum is not recorded as finished
*/
if (start == seqnum && devpath_len > 0)
unfinished++;
if (devpath_len == 0) {
if (seqnum >= start && seqnum <= end)
unfinished--;
}
} while (unfinished > 0);
if (devpath_len == 0) {
if (seqnum >= start && seqnum <= end)
unfinished--;
}
} while (unfinished > 0);
fclose(queue_file);
fclose(queue_file);
return (unfinished == 0);
return (unfinished == 0);
}
/**
@@ -406,11 +406,11 @@ UDEV_EXPORT int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *ud
**/
UDEV_EXPORT int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum)
{
if (!udev_queue_get_seqnum_sequence_is_finished(udev_queue, seqnum, seqnum))
return 0;
if (!udev_queue_get_seqnum_sequence_is_finished(udev_queue, seqnum, seqnum))
return 0;
dbg(udev_queue->udev, "seqnum: %llu finished\n", seqnum);
return 1;
dbg(udev_queue->udev, "seqnum: %llu finished\n", seqnum);
return 1;
}
/**
@@ -421,54 +421,54 @@ UDEV_EXPORT int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue,
**/
UDEV_EXPORT struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue)
{
unsigned long long int seqnum;
FILE *queue_file;
unsigned long long int seqnum;
FILE *queue_file;
if (udev_queue == NULL)
return NULL;
udev_list_cleanup(&udev_queue->queue_list);
if (udev_queue == NULL)
return NULL;
udev_list_cleanup(&udev_queue->queue_list);
queue_file = open_queue_file(udev_queue, &seqnum);
if (queue_file == NULL)
return NULL;
queue_file = open_queue_file(udev_queue, &seqnum);
if (queue_file == NULL)
return NULL;
for (;;) {
char syspath[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
char seqnum_str[32];
struct udev_list_entry *list_entry;
for (;;) {
char syspath[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
char seqnum_str[32];
struct udev_list_entry *list_entry;
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
snprintf(seqnum_str, sizeof(seqnum_str), "%llu", seqnum);
if (udev_queue_read_seqnum(queue_file, &seqnum) < 0)
break;
snprintf(seqnum_str, sizeof(seqnum_str), "%llu", seqnum);
s = syspath;
l = util_strpcpyl(&s, sizeof(syspath), udev_get_sys_path(udev_queue->udev), NULL);
len = udev_queue_read_devpath(queue_file, s, l);
if (len < 0)
break;
s = syspath;
l = util_strpcpyl(&s, sizeof(syspath), udev_get_sys_path(udev_queue->udev), NULL);
len = udev_queue_read_devpath(queue_file, s, l);
if (len < 0)
break;
if (len > 0) {
udev_list_entry_add(&udev_queue->queue_list, syspath, seqnum_str);
} else {
udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_queue->queue_list)) {
if (strcmp(seqnum_str, udev_list_entry_get_value(list_entry)) == 0) {
udev_list_entry_delete(list_entry);
break;
}
}
}
}
fclose(queue_file);
if (len > 0) {
udev_list_entry_add(&udev_queue->queue_list, syspath, seqnum_str);
} else {
udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_queue->queue_list)) {
if (strcmp(seqnum_str, udev_list_entry_get_value(list_entry)) == 0) {
udev_list_entry_delete(list_entry);
break;
}
}
}
}
fclose(queue_file);
return udev_list_get_entry(&udev_queue->queue_list);
return udev_list_get_entry(&udev_queue->queue_list);
}
struct udev_list_entry *udev_queue_get_failed_list_entry(struct udev_queue *udev_queue);
UDEV_EXPORT struct udev_list_entry *udev_queue_get_failed_list_entry(struct udev_queue *udev_queue)
{
errno = ENOSYS;
return NULL;
errno = ENOSYS;
return NULL;
}
+55 -55
View File
@@ -24,86 +24,86 @@ security_context_t selinux_prev_scontext;
void udev_selinux_init(struct udev *udev)
{
/* record the present security context */
selinux_enabled = (is_selinux_enabled() > 0);
info(udev, "selinux=%i\n", selinux_enabled);
if (!selinux_enabled)
return;
matchpathcon_init_prefix(NULL, udev_get_dev_path(udev));
if (getfscreatecon(&selinux_prev_scontext) < 0) {
err(udev, "getfscreatecon failed\n");
selinux_prev_scontext = NULL;
}
/* record the present security context */
selinux_enabled = (is_selinux_enabled() > 0);
info(udev, "selinux=%i\n", selinux_enabled);
if (!selinux_enabled)
return;
matchpathcon_init_prefix(NULL, udev_get_dev_path(udev));
if (getfscreatecon(&selinux_prev_scontext) < 0) {
err(udev, "getfscreatecon failed\n");
selinux_prev_scontext = NULL;
}
}
void udev_selinux_exit(struct udev *udev)
{
if (!selinux_enabled)
return;
freecon(selinux_prev_scontext);
selinux_prev_scontext = NULL;
if (!selinux_enabled)
return;
freecon(selinux_prev_scontext);
selinux_prev_scontext = NULL;
}
void udev_selinux_lsetfilecon(struct udev *udev, const char *file, unsigned int mode)
{
security_context_t scontext = NULL;
security_context_t scontext = NULL;
if (!selinux_enabled)
return;
if (matchpathcon(file, mode, &scontext) < 0) {
err(udev, "matchpathcon(%s) failed\n", file);
return;
}
if (lsetfilecon(file, scontext) < 0)
err(udev, "setfilecon %s failed: %m\n", file);
freecon(scontext);
if (!selinux_enabled)
return;
if (matchpathcon(file, mode, &scontext) < 0) {
err(udev, "matchpathcon(%s) failed\n", file);
return;
}
if (lsetfilecon(file, scontext) < 0)
err(udev, "setfilecon %s failed: %m\n", file);
freecon(scontext);
}
void udev_selinux_setfscreatecon(struct udev *udev, const char *file, unsigned int mode)
{
security_context_t scontext = NULL;
security_context_t scontext = NULL;
if (!selinux_enabled)
return;
if (!selinux_enabled)
return;
if (matchpathcon(file, mode, &scontext) < 0) {
err(udev, "matchpathcon(%s) failed\n", file);
return;
}
if (setfscreatecon(scontext) < 0)
err(udev, "setfscreatecon %s failed: %m\n", file);
freecon(scontext);
if (matchpathcon(file, mode, &scontext) < 0) {
err(udev, "matchpathcon(%s) failed\n", file);
return;
}
if (setfscreatecon(scontext) < 0)
err(udev, "setfscreatecon %s failed: %m\n", file);
freecon(scontext);
}
void udev_selinux_resetfscreatecon(struct udev *udev)
{
if (!selinux_enabled)
return;
if (setfscreatecon(selinux_prev_scontext) < 0)
err(udev, "setfscreatecon failed: %m\n");
if (!selinux_enabled)
return;
if (setfscreatecon(selinux_prev_scontext) < 0)
err(udev, "setfscreatecon failed: %m\n");
}
void udev_selinux_setfscreateconat(struct udev *udev, int dfd, const char *file, unsigned int mode)
{
char filename[UTIL_PATH_SIZE];
char filename[UTIL_PATH_SIZE];
if (!selinux_enabled)
return;
if (!selinux_enabled)
return;
/* resolve relative filename */
if (file[0] != '/') {
char procfd[UTIL_PATH_SIZE];
char target[UTIL_PATH_SIZE];
ssize_t len;
/* resolve relative filename */
if (file[0] != '/') {
char procfd[UTIL_PATH_SIZE];
char target[UTIL_PATH_SIZE];
ssize_t len;
snprintf(procfd, sizeof(procfd), "/proc/%u/fd/%u", getpid(), dfd);
len = readlink(procfd, target, sizeof(target));
if (len <= 0 || len == sizeof(target))
return;
target[len] = '\0';
snprintf(procfd, sizeof(procfd), "/proc/%u/fd/%u", getpid(), dfd);
len = readlink(procfd, target, sizeof(target));
if (len <= 0 || len == sizeof(target))
return;
target[len] = '\0';
util_strscpyl(filename, sizeof(filename), target, "/", file, NULL);
file = filename;
}
udev_selinux_setfscreatecon(udev, file, mode);
util_strscpyl(filename, sizeof(filename), target, "/", file, NULL);
file = filename;
}
udev_selinux_setfscreatecon(udev, file, mode);
}
+166 -166
View File
@@ -26,217 +26,217 @@
static int create_path(struct udev *udev, const char *path, bool selinux)
{
char p[UTIL_PATH_SIZE];
char *pos;
struct stat stats;
int err;
char p[UTIL_PATH_SIZE];
char *pos;
struct stat stats;
int err;
util_strscpy(p, sizeof(p), path);
pos = strrchr(p, '/');
if (pos == NULL)
return 0;
while (pos != p && pos[-1] == '/')
pos--;
if (pos == p)
return 0;
pos[0] = '\0';
util_strscpy(p, sizeof(p), path);
pos = strrchr(p, '/');
if (pos == NULL)
return 0;
while (pos != p && pos[-1] == '/')
pos--;
if (pos == p)
return 0;
pos[0] = '\0';
dbg(udev, "stat '%s'\n", p);
if (stat(p, &stats) == 0) {
if ((stats.st_mode & S_IFMT) == S_IFDIR)
return 0;
else
return -ENOTDIR;
}
dbg(udev, "stat '%s'\n", p);
if (stat(p, &stats) == 0) {
if ((stats.st_mode & S_IFMT) == S_IFDIR)
return 0;
else
return -ENOTDIR;
}
err = util_create_path(udev, p);
if (err != 0)
return err;
err = util_create_path(udev, p);
if (err != 0)
return err;
dbg(udev, "mkdir '%s'\n", p);
if (selinux)
udev_selinux_setfscreatecon(udev, p, S_IFDIR|0755);
err = mkdir(p, 0755);
if (err != 0) {
err = -errno;
if (err == -EEXIST && stat(p, &stats) == 0) {
if ((stats.st_mode & S_IFMT) == S_IFDIR)
err = 0;
else
err = -ENOTDIR;
}
}
if (selinux)
udev_selinux_resetfscreatecon(udev);
return err;
dbg(udev, "mkdir '%s'\n", p);
if (selinux)
udev_selinux_setfscreatecon(udev, p, S_IFDIR|0755);
err = mkdir(p, 0755);
if (err != 0) {
err = -errno;
if (err == -EEXIST && stat(p, &stats) == 0) {
if ((stats.st_mode & S_IFMT) == S_IFDIR)
err = 0;
else
err = -ENOTDIR;
}
}
if (selinux)
udev_selinux_resetfscreatecon(udev);
return err;
}
int util_create_path(struct udev *udev, const char *path)
{
return create_path(udev, path, false);
return create_path(udev, path, false);
}
int util_create_path_selinux(struct udev *udev, const char *path)
{
return create_path(udev, path, true);
return create_path(udev, path, true);
}
int util_delete_path(struct udev *udev, const char *path)
{
char p[UTIL_PATH_SIZE];
char *pos;
int err = 0;
char p[UTIL_PATH_SIZE];
char *pos;
int err = 0;
if (path[0] == '/')
while(path[1] == '/')
path++;
util_strscpy(p, sizeof(p), path);
pos = strrchr(p, '/');
if (pos == p || pos == NULL)
return 0;
if (path[0] == '/')
while(path[1] == '/')
path++;
util_strscpy(p, sizeof(p), path);
pos = strrchr(p, '/');
if (pos == p || pos == NULL)
return 0;
for (;;) {
*pos = '\0';
pos = strrchr(p, '/');
for (;;) {
*pos = '\0';
pos = strrchr(p, '/');
/* don't remove the last one */
if ((pos == p) || (pos == NULL))
break;
/* don't remove the last one */
if ((pos == p) || (pos == NULL))
break;
err = rmdir(p);
if (err < 0) {
if (errno == ENOENT)
err = 0;
break;
}
}
return err;
err = rmdir(p);
if (err < 0) {
if (errno == ENOENT)
err = 0;
break;
}
}
return err;
}
uid_t util_lookup_user(struct udev *udev, const char *user)
{
char *endptr;
size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
char buf[buflen];
struct passwd pwbuf;
struct passwd *pw;
uid_t uid;
char *endptr;
size_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
char buf[buflen];
struct passwd pwbuf;
struct passwd *pw;
uid_t uid;
if (strcmp(user, "root") == 0)
return 0;
uid = strtoul(user, &endptr, 10);
if (endptr[0] == '\0')
return uid;
if (strcmp(user, "root") == 0)
return 0;
uid = strtoul(user, &endptr, 10);
if (endptr[0] == '\0')
return uid;
errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
if (pw != NULL)
return pw->pw_uid;
if (errno == 0 || errno == ENOENT || errno == ESRCH)
err(udev, "specified user '%s' unknown\n", user);
else
err(udev, "error resolving user '%s': %m\n", user);
return 0;
errno = getpwnam_r(user, &pwbuf, buf, buflen, &pw);
if (pw != NULL)
return pw->pw_uid;
if (errno == 0 || errno == ENOENT || errno == ESRCH)
err(udev, "specified user '%s' unknown\n", user);
else
err(udev, "error resolving user '%s': %m\n", user);
return 0;
}
gid_t util_lookup_group(struct udev *udev, const char *group)
{
char *endptr;
size_t buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
char *buf;
struct group grbuf;
struct group *gr;
gid_t gid = 0;
char *endptr;
size_t buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
char *buf;
struct group grbuf;
struct group *gr;
gid_t gid = 0;
if (strcmp(group, "root") == 0)
return 0;
gid = strtoul(group, &endptr, 10);
if (endptr[0] == '\0')
return gid;
buf = NULL;
gid = 0;
for (;;) {
char *newbuf;
if (strcmp(group, "root") == 0)
return 0;
gid = strtoul(group, &endptr, 10);
if (endptr[0] == '\0')
return gid;
buf = NULL;
gid = 0;
for (;;) {
char *newbuf;
newbuf = realloc(buf, buflen);
if (!newbuf)
break;
buf = newbuf;
errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
if (gr != NULL) {
gid = gr->gr_gid;
} else if (errno == ERANGE) {
buflen *= 2;
continue;
} else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
err(udev, "specified group '%s' unknown\n", group);
} else {
err(udev, "error resolving group '%s': %m\n", group);
}
break;
}
free(buf);
return gid;
newbuf = realloc(buf, buflen);
if (!newbuf)
break;
buf = newbuf;
errno = getgrnam_r(group, &grbuf, buf, buflen, &gr);
if (gr != NULL) {
gid = gr->gr_gid;
} else if (errno == ERANGE) {
buflen *= 2;
continue;
} else if (errno == 0 || errno == ENOENT || errno == ESRCH) {
err(udev, "specified group '%s' unknown\n", group);
} else {
err(udev, "error resolving group '%s': %m\n", group);
}
break;
}
free(buf);
return gid;
}
/* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
int util_resolve_subsys_kernel(struct udev *udev, const char *string,
char *result, size_t maxsize, int read_value)
char *result, size_t maxsize, int read_value)
{
char temp[UTIL_PATH_SIZE];
char *subsys;
char *sysname;
struct udev_device *dev;
char *attr;
char temp[UTIL_PATH_SIZE];
char *subsys;
char *sysname;
struct udev_device *dev;
char *attr;
if (string[0] != '[')
return -1;
if (string[0] != '[')
return -1;
util_strscpy(temp, sizeof(temp), string);
util_strscpy(temp, sizeof(temp), string);
subsys = &temp[1];
subsys = &temp[1];
sysname = strchr(subsys, '/');
if (sysname == NULL)
return -1;
sysname[0] = '\0';
sysname = &sysname[1];
sysname = strchr(subsys, '/');
if (sysname == NULL)
return -1;
sysname[0] = '\0';
sysname = &sysname[1];
attr = strchr(sysname, ']');
if (attr == NULL)
return -1;
attr[0] = '\0';
attr = &attr[1];
if (attr[0] == '/')
attr = &attr[1];
if (attr[0] == '\0')
attr = NULL;
attr = strchr(sysname, ']');
if (attr == NULL)
return -1;
attr[0] = '\0';
attr = &attr[1];
if (attr[0] == '/')
attr = &attr[1];
if (attr[0] == '\0')
attr = NULL;
if (read_value && attr == NULL)
return -1;
if (read_value && attr == NULL)
return -1;
dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
if (dev == NULL)
return -1;
dev = udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
if (dev == NULL)
return -1;
if (read_value) {
const char *val;
if (read_value) {
const char *val;
val = udev_device_get_sysattr_value(dev, attr);
if (val != NULL)
util_strscpy(result, maxsize, val);
else
result[0] = '\0';
info(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
} else {
size_t l;
char *s;
val = udev_device_get_sysattr_value(dev, attr);
if (val != NULL)
util_strscpy(result, maxsize, val);
else
result[0] = '\0';
info(udev, "value '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
} else {
size_t l;
char *s;
s = result;
l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
if (attr != NULL)
util_strpcpyl(&s, l, "/", attr, NULL);
info(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
}
udev_device_unref(dev);
return 0;
s = result;
l = util_strpcpyl(&s, maxsize, udev_device_get_syspath(dev), NULL);
if (attr != NULL)
util_strpcpyl(&s, l, "/", attr, NULL);
info(udev, "path '[%s/%s]%s' is '%s'\n", subsys, sysname, attr, result);
}
udev_device_unref(dev);
return 0;
}
+358 -358
View File
@@ -31,131 +31,131 @@
ssize_t util_get_sys_core_link_value(struct udev *udev, const char *slink, const char *syspath, char *value, size_t size)
{
char path[UTIL_PATH_SIZE];
char target[UTIL_PATH_SIZE];
ssize_t len;
const char *pos;
char path[UTIL_PATH_SIZE];
char target[UTIL_PATH_SIZE];
ssize_t len;
const char *pos;
util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
len = readlink(path, target, sizeof(target));
if (len <= 0 || len == (ssize_t)sizeof(target))
return -1;
target[len] = '\0';
pos = strrchr(target, '/');
if (pos == NULL)
return -1;
pos = &pos[1];
dbg(udev, "resolved link to: '%s'\n", pos);
return util_strscpy(value, size, pos);
util_strscpyl(path, sizeof(path), syspath, "/", slink, NULL);
len = readlink(path, target, sizeof(target));
if (len <= 0 || len == (ssize_t)sizeof(target))
return -1;
target[len] = '\0';
pos = strrchr(target, '/');
if (pos == NULL)
return -1;
pos = &pos[1];
dbg(udev, "resolved link to: '%s'\n", pos);
return util_strscpy(value, size, pos);
}
int util_resolve_sys_link(struct udev *udev, char *syspath, size_t size)
{
char link_target[UTIL_PATH_SIZE];
char link_target[UTIL_PATH_SIZE];
ssize_t len;
int i;
int back;
char *base;
ssize_t len;
int i;
int back;
char *base;
len = readlink(syspath, link_target, sizeof(link_target));
if (len <= 0 || len == (ssize_t)sizeof(link_target))
return -1;
link_target[len] = '\0';
dbg(udev, "path link '%s' points to '%s'\n", syspath, link_target);
len = readlink(syspath, link_target, sizeof(link_target));
if (len <= 0 || len == (ssize_t)sizeof(link_target))
return -1;
link_target[len] = '\0';
dbg(udev, "path link '%s' points to '%s'\n", syspath, link_target);
for (back = 0; strncmp(&link_target[back * 3], "../", 3) == 0; back++)
;
dbg(udev, "base '%s', tail '%s', back %i\n", syspath, &link_target[back * 3], back);
for (i = 0; i <= back; i++) {
base = strrchr(syspath, '/');
if (base == NULL)
return -1;
base[0] = '\0';
}
dbg(udev, "after moving back '%s'\n", syspath);
util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
return 0;
for (back = 0; strncmp(&link_target[back * 3], "../", 3) == 0; back++)
;
dbg(udev, "base '%s', tail '%s', back %i\n", syspath, &link_target[back * 3], back);
for (i = 0; i <= back; i++) {
base = strrchr(syspath, '/');
if (base == NULL)
return -1;
base[0] = '\0';
}
dbg(udev, "after moving back '%s'\n", syspath);
util_strscpyl(base, size - (base - syspath), "/", &link_target[back * 3], NULL);
return 0;
}
int util_log_priority(const char *priority)
{
char *endptr;
int prio;
char *endptr;
int prio;
prio = strtol(priority, &endptr, 10);
if (endptr[0] == '\0' || isspace(endptr[0]))
return prio;
if (strncmp(priority, "err", 3) == 0)
return LOG_ERR;
if (strncmp(priority, "info", 4) == 0)
return LOG_INFO;
if (strncmp(priority, "debug", 5) == 0)
return LOG_DEBUG;
return 0;
prio = strtol(priority, &endptr, 10);
if (endptr[0] == '\0' || isspace(endptr[0]))
return prio;
if (strncmp(priority, "err", 3) == 0)
return LOG_ERR;
if (strncmp(priority, "info", 4) == 0)
return LOG_INFO;
if (strncmp(priority, "debug", 5) == 0)
return LOG_DEBUG;
return 0;
}
size_t util_path_encode(const char *src, char *dest, size_t size)
{
size_t i, j;
size_t i, j;
for (i = 0, j = 0; src[i] != '\0'; i++) {
if (src[i] == '/') {
if (j+4 >= size) {
j = 0;
break;
}
memcpy(&dest[j], "\\x2f", 4);
j += 4;
} else if (src[i] == '\\') {
if (j+4 >= size) {
j = 0;
break;
}
memcpy(&dest[j], "\\x5c", 4);
j += 4;
} else {
if (j+1 >= size) {
j = 0;
break;
}
dest[j] = src[i];
j++;
}
}
dest[j] = '\0';
return j;
for (i = 0, j = 0; src[i] != '\0'; i++) {
if (src[i] == '/') {
if (j+4 >= size) {
j = 0;
break;
}
memcpy(&dest[j], "\\x2f", 4);
j += 4;
} else if (src[i] == '\\') {
if (j+4 >= size) {
j = 0;
break;
}
memcpy(&dest[j], "\\x5c", 4);
j += 4;
} else {
if (j+1 >= size) {
j = 0;
break;
}
dest[j] = src[i];
j++;
}
}
dest[j] = '\0';
return j;
}
size_t util_path_decode(char *s)
{
size_t i, j;
size_t i, j;
for (i = 0, j = 0; s[i] != '\0'; j++) {
if (memcmp(&s[i], "\\x2f", 4) == 0) {
s[j] = '/';
i += 4;
} else if (memcmp(&s[i], "\\x5c", 4) == 0) {
s[j] = '\\';
i += 4;
} else {
s[j] = s[i];
i++;
}
}
s[j] = '\0';
return j;
for (i = 0, j = 0; s[i] != '\0'; j++) {
if (memcmp(&s[i], "\\x2f", 4) == 0) {
s[j] = '/';
i += 4;
} else if (memcmp(&s[i], "\\x5c", 4) == 0) {
s[j] = '\\';
i += 4;
} else {
s[j] = s[i];
i++;
}
}
s[j] = '\0';
return j;
}
void util_remove_trailing_chars(char *path, char c)
{
size_t len;
size_t len;
if (path == NULL)
return;
len = strlen(path);
while (len > 0 && path[len-1] == c)
path[--len] = '\0';
if (path == NULL)
return;
len = strlen(path);
while (len > 0 && path[len-1] == c)
path[--len] = '\0';
}
/*
@@ -165,268 +165,268 @@ void util_remove_trailing_chars(char *path, char c)
*/
size_t util_strpcpy(char **dest, size_t size, const char *src)
{
size_t len;
size_t len;
len = strlen(src);
if (len >= size) {
if (size > 1)
*dest = mempcpy(*dest, src, size-1);
size = 0;
*dest[0] = '\0';
} else {
if (len > 0) {
*dest = mempcpy(*dest, src, len);
size -= len;
}
*dest[0] = '\0';
}
return size;
len = strlen(src);
if (len >= size) {
if (size > 1)
*dest = mempcpy(*dest, src, size-1);
size = 0;
*dest[0] = '\0';
} else {
if (len > 0) {
*dest = mempcpy(*dest, src, len);
size -= len;
}
*dest[0] = '\0';
}
return size;
}
/* concatenates list of strings, moves dest forward */
size_t util_strpcpyl(char **dest, size_t size, const char *src, ...)
{
va_list va;
va_list va;
va_start(va, src);
do {
size = util_strpcpy(dest, size, src);
src = va_arg(va, char *);
} while (src != NULL);
va_end(va);
va_start(va, src);
do {
size = util_strpcpy(dest, size, src);
src = va_arg(va, char *);
} while (src != NULL);
va_end(va);
return size;
return size;
}
/* copies string */
size_t util_strscpy(char *dest, size_t size, const char *src)
{
char *s;
char *s;
s = dest;
return util_strpcpy(&s, size, src);
s = dest;
return util_strpcpy(&s, size, src);
}
/* concatenates list of strings */
size_t util_strscpyl(char *dest, size_t size, const char *src, ...)
{
va_list va;
char *s;
va_list va;
char *s;
va_start(va, src);
s = dest;
do {
size = util_strpcpy(&s, size, src);
src = va_arg(va, char *);
} while (src != NULL);
va_end(va);
va_start(va, src);
s = dest;
do {
size = util_strpcpy(&s, size, src);
src = va_arg(va, char *);
} while (src != NULL);
va_end(va);
return size;
return size;
}
/* count of characters used to encode one unicode char */
static int utf8_encoded_expected_len(const char *str)
{
unsigned char c = (unsigned char)str[0];
unsigned char c = (unsigned char)str[0];
if (c < 0x80)
return 1;
if ((c & 0xe0) == 0xc0)
return 2;
if ((c & 0xf0) == 0xe0)
return 3;
if ((c & 0xf8) == 0xf0)
return 4;
if ((c & 0xfc) == 0xf8)
return 5;
if ((c & 0xfe) == 0xfc)
return 6;
return 0;
if (c < 0x80)
return 1;
if ((c & 0xe0) == 0xc0)
return 2;
if ((c & 0xf0) == 0xe0)
return 3;
if ((c & 0xf8) == 0xf0)
return 4;
if ((c & 0xfc) == 0xf8)
return 5;
if ((c & 0xfe) == 0xfc)
return 6;
return 0;
}
/* decode one unicode char */
static int utf8_encoded_to_unichar(const char *str)
{
int unichar;
int len;
int i;
int unichar;
int len;
int i;
len = utf8_encoded_expected_len(str);
switch (len) {
case 1:
return (int)str[0];
case 2:
unichar = str[0] & 0x1f;
break;
case 3:
unichar = (int)str[0] & 0x0f;
break;
case 4:
unichar = (int)str[0] & 0x07;
break;
case 5:
unichar = (int)str[0] & 0x03;
break;
case 6:
unichar = (int)str[0] & 0x01;
break;
default:
return -1;
}
len = utf8_encoded_expected_len(str);
switch (len) {
case 1:
return (int)str[0];
case 2:
unichar = str[0] & 0x1f;
break;
case 3:
unichar = (int)str[0] & 0x0f;
break;
case 4:
unichar = (int)str[0] & 0x07;
break;
case 5:
unichar = (int)str[0] & 0x03;
break;
case 6:
unichar = (int)str[0] & 0x01;
break;
default:
return -1;
}
for (i = 1; i < len; i++) {
if (((int)str[i] & 0xc0) != 0x80)
return -1;
unichar <<= 6;
unichar |= (int)str[i] & 0x3f;
}
for (i = 1; i < len; i++) {
if (((int)str[i] & 0xc0) != 0x80)
return -1;
unichar <<= 6;
unichar |= (int)str[i] & 0x3f;
}
return unichar;
return unichar;
}
/* expected size used to encode one unicode char */
static int utf8_unichar_to_encoded_len(int unichar)
{
if (unichar < 0x80)
return 1;
if (unichar < 0x800)
return 2;
if (unichar < 0x10000)
return 3;
if (unichar < 0x200000)
return 4;
if (unichar < 0x4000000)
return 5;
return 6;
if (unichar < 0x80)
return 1;
if (unichar < 0x800)
return 2;
if (unichar < 0x10000)
return 3;
if (unichar < 0x200000)
return 4;
if (unichar < 0x4000000)
return 5;
return 6;
}
/* check if unicode char has a valid numeric range */
static int utf8_unichar_valid_range(int unichar)
{
if (unichar > 0x10ffff)
return 0;
if ((unichar & 0xfffff800) == 0xd800)
return 0;
if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
return 0;
if ((unichar & 0xffff) == 0xffff)
return 0;
return 1;
if (unichar > 0x10ffff)
return 0;
if ((unichar & 0xfffff800) == 0xd800)
return 0;
if ((unichar > 0xfdcf) && (unichar < 0xfdf0))
return 0;
if ((unichar & 0xffff) == 0xffff)
return 0;
return 1;
}
/* validate one encoded unicode char and return its length */
static int utf8_encoded_valid_unichar(const char *str)
{
int len;
int unichar;
int i;
int len;
int unichar;
int i;
len = utf8_encoded_expected_len(str);
if (len == 0)
return -1;
len = utf8_encoded_expected_len(str);
if (len == 0)
return -1;
/* ascii is valid */
if (len == 1)
return 1;
/* ascii is valid */
if (len == 1)
return 1;
/* check if expected encoded chars are available */
for (i = 0; i < len; i++)
if ((str[i] & 0x80) != 0x80)
return -1;
/* check if expected encoded chars are available */
for (i = 0; i < len; i++)
if ((str[i] & 0x80) != 0x80)
return -1;
unichar = utf8_encoded_to_unichar(str);
unichar = utf8_encoded_to_unichar(str);
/* check if encoded length matches encoded value */
if (utf8_unichar_to_encoded_len(unichar) != len)
return -1;
/* check if encoded length matches encoded value */
if (utf8_unichar_to_encoded_len(unichar) != len)
return -1;
/* check if value has valid range */
if (!utf8_unichar_valid_range(unichar))
return -1;
/* check if value has valid range */
if (!utf8_unichar_valid_range(unichar))
return -1;
return len;
return len;
}
int util_replace_whitespace(const char *str, char *to, size_t len)
{
size_t i, j;
size_t i, j;
/* strip trailing whitespace */
len = strnlen(str, len);
while (len && isspace(str[len-1]))
len--;
/* strip trailing whitespace */
len = strnlen(str, len);
while (len && isspace(str[len-1]))
len--;
/* strip leading whitespace */
i = 0;
while (isspace(str[i]) && (i < len))
i++;
/* strip leading whitespace */
i = 0;
while (isspace(str[i]) && (i < len))
i++;
j = 0;
while (i < len) {
/* substitute multiple whitespace with a single '_' */
if (isspace(str[i])) {
while (isspace(str[i]))
i++;
to[j++] = '_';
}
to[j++] = str[i++];
}
to[j] = '\0';
return 0;
j = 0;
while (i < len) {
/* substitute multiple whitespace with a single '_' */
if (isspace(str[i])) {
while (isspace(str[i]))
i++;
to[j++] = '_';
}
to[j++] = str[i++];
}
to[j] = '\0';
return 0;
}
static int is_whitelisted(char c, const char *white)
{
if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
strchr("#+-.:=@_", c) != NULL ||
(white != NULL && strchr(white, c) != NULL))
return 1;
return 0;
if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
strchr("#+-.:=@_", c) != NULL ||
(white != NULL && strchr(white, c) != NULL))
return 1;
return 0;
}
/* allow chars in whitelist, plain ascii, hex-escaping and valid utf8 */
int util_replace_chars(char *str, const char *white)
{
size_t i = 0;
int replaced = 0;
size_t i = 0;
int replaced = 0;
while (str[i] != '\0') {
int len;
while (str[i] != '\0') {
int len;
if (is_whitelisted(str[i], white)) {
i++;
continue;
}
if (is_whitelisted(str[i], white)) {
i++;
continue;
}
/* accept hex encoding */
if (str[i] == '\\' && str[i+1] == 'x') {
i += 2;
continue;
}
/* accept hex encoding */
if (str[i] == '\\' && str[i+1] == 'x') {
i += 2;
continue;
}
/* accept valid utf8 */
len = utf8_encoded_valid_unichar(&str[i]);
if (len > 1) {
i += len;
continue;
}
/* accept valid utf8 */
len = utf8_encoded_valid_unichar(&str[i]);
if (len > 1) {
i += len;
continue;
}
/* if space is allowed, replace whitespace with ordinary space */
if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
str[i] = ' ';
i++;
replaced++;
continue;
}
/* if space is allowed, replace whitespace with ordinary space */
if (isspace(str[i]) && white != NULL && strchr(white, ' ') != NULL) {
str[i] = ' ';
i++;
replaced++;
continue;
}
/* everything else is replaced with '_' */
str[i] = '_';
i++;
replaced++;
}
return replaced;
/* everything else is replaced with '_' */
str[i] = '_';
i++;
replaced++;
}
return replaced;
}
/**
@@ -443,39 +443,39 @@ int util_replace_chars(char *str, const char *white)
**/
UDEV_EXPORT int udev_util_encode_string(const char *str, char *str_enc, size_t len)
{
size_t i, j;
size_t i, j;
if (str == NULL || str_enc == NULL)
return -1;
if (str == NULL || str_enc == NULL)
return -1;
for (i = 0, j = 0; str[i] != '\0'; i++) {
int seqlen;
for (i = 0, j = 0; str[i] != '\0'; i++) {
int seqlen;
seqlen = utf8_encoded_valid_unichar(&str[i]);
if (seqlen > 1) {
if (len-j < (size_t)seqlen)
goto err;
memcpy(&str_enc[j], &str[i], seqlen);
j += seqlen;
i += (seqlen-1);
} else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
if (len-j < 4)
goto err;
sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
j += 4;
} else {
if (len-j < 1)
goto err;
str_enc[j] = str[i];
j++;
}
}
if (len-j < 1)
goto err;
str_enc[j] = '\0';
return 0;
seqlen = utf8_encoded_valid_unichar(&str[i]);
if (seqlen > 1) {
if (len-j < (size_t)seqlen)
goto err;
memcpy(&str_enc[j], &str[i], seqlen);
j += seqlen;
i += (seqlen-1);
} else if (str[i] == '\\' || !is_whitelisted(str[i], NULL)) {
if (len-j < 4)
goto err;
sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
j += 4;
} else {
if (len-j < 1)
goto err;
str_enc[j] = str[i];
j++;
}
}
if (len-j < 1)
goto err;
str_enc[j] = '\0';
return 0;
err:
return -1;
return -1;
}
/*
@@ -487,82 +487,82 @@ err:
*/
static unsigned int murmur_hash2(const char *key, int len, unsigned int seed)
{
/*
* 'm' and 'r' are mixing constants generated offline.
* They're not really 'magic', they just happen to work well.
*/
const unsigned int m = 0x5bd1e995;
const int r = 24;
/*
* 'm' and 'r' are mixing constants generated offline.
* They're not really 'magic', they just happen to work well.
*/
const unsigned int m = 0x5bd1e995;
const int r = 24;
/* initialize the hash to a 'random' value */
unsigned int h = seed ^ len;
/* initialize the hash to a 'random' value */
unsigned int h = seed ^ len;
/* mix 4 bytes at a time into the hash */
const unsigned char * data = (const unsigned char *)key;
/* mix 4 bytes at a time into the hash */
const unsigned char * data = (const unsigned char *)key;
while(len >= 4) {
unsigned int k = *(unsigned int *)data;
while(len >= 4) {
unsigned int k = *(unsigned int *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
data += 4;
len -= 4;
}
/* handle the last few bytes of the input array */
switch(len) {
case 3:
h ^= data[2] << 16;
case 2:
h ^= data[1] << 8;
case 1:
h ^= data[0];
h *= m;
};
/* handle the last few bytes of the input array */
switch(len) {
case 3:
h ^= data[2] << 16;
case 2:
h ^= data[1] << 8;
case 1:
h ^= data[0];
h *= m;
};
/* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
h ^= h >> 13;
h *= m;
h ^= h >> 15;
/* do a few final mixes of the hash to ensure the last few bytes are well-incorporated */
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
return h;
}
unsigned int util_string_hash32(const char *str)
{
return murmur_hash2(str, strlen(str), 0);
return murmur_hash2(str, strlen(str), 0);
}
/* get a bunch of bit numbers out of the hash, and set the bits in our bit field */
uint64_t util_string_bloom64(const char *str)
{
uint64_t bits = 0;
unsigned int hash = util_string_hash32(str);
uint64_t bits = 0;
unsigned int hash = util_string_hash32(str);
bits |= 1LLU << (hash & 63);
bits |= 1LLU << ((hash >> 6) & 63);
bits |= 1LLU << ((hash >> 12) & 63);
bits |= 1LLU << ((hash >> 18) & 63);
return bits;
bits |= 1LLU << (hash & 63);
bits |= 1LLU << ((hash >> 6) & 63);
bits |= 1LLU << ((hash >> 12) & 63);
bits |= 1LLU << ((hash >> 18) & 63);
return bits;
}
#define USEC_PER_SEC 1000000ULL
#define NSEC_PER_USEC 1000ULL
unsigned long long ts_usec(const struct timespec *ts)
{
return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
(unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
return (unsigned long long) ts->tv_sec * USEC_PER_SEC +
(unsigned long long) ts->tv_nsec / NSEC_PER_USEC;
}
unsigned long long now_usec(void)
{
struct timespec ts;
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
return 0;
return ts_usec(&ts);
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
return 0;
return ts_usec(&ts);
}
+224 -224
View File
@@ -36,38 +36,38 @@
* Opaque object representing the library context.
*/
struct udev {
int refcount;
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args);
void *userdata;
char *sys_path;
char *dev_path;
char *rules_path[4];
unsigned long long rules_path_ts[4];
int rules_path_count;
char *run_path;
struct udev_list properties_list;
int log_priority;
int refcount;
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args);
void *userdata;
char *sys_path;
char *dev_path;
char *rules_path[4];
unsigned long long rules_path_ts[4];
int rules_path_count;
char *run_path;
struct udev_list properties_list;
int log_priority;
};
void udev_log(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, ...)
int priority, const char *file, int line, const char *fn,
const char *format, ...)
{
va_list args;
va_list args;
va_start(args, format);
udev->log_fn(udev, priority, file, line, fn, format, args);
va_end(args);
va_start(args, format);
udev->log_fn(udev, priority, file, line, fn, format, args);
va_end(args);
}
static void log_stderr(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args)
int priority, const char *file, int line, const char *fn,
const char *format, va_list args)
{
fprintf(stderr, "libudev: %s: ", fn);
vfprintf(stderr, format, args);
fprintf(stderr, "libudev: %s: ", fn);
vfprintf(stderr, format, args);
}
/**
@@ -81,9 +81,9 @@ static void log_stderr(struct udev *udev,
**/
UDEV_EXPORT void *udev_get_userdata(struct udev *udev)
{
if (udev == NULL)
return NULL;
return udev->userdata;
if (udev == NULL)
return NULL;
return udev->userdata;
}
/**
@@ -95,17 +95,17 @@ UDEV_EXPORT void *udev_get_userdata(struct udev *udev)
**/
UDEV_EXPORT void udev_set_userdata(struct udev *udev, void *userdata)
{
if (udev == NULL)
return;
udev->userdata = userdata;
if (udev == NULL)
return;
udev->userdata = userdata;
}
static char *set_value(char **s, const char *v)
{
free(*s);
*s = strdup(v);
util_remove_trailing_chars(*s, '/');
return *s;
free(*s);
*s = strdup(v);
util_remove_trailing_chars(*s, '/');
return *s;
}
/**
@@ -121,171 +121,171 @@ static char *set_value(char **s, const char *v)
**/
UDEV_EXPORT struct udev *udev_new(void)
{
struct udev *udev;
const char *env;
char *config_file = NULL;
FILE *f;
struct udev *udev;
const char *env;
char *config_file = NULL;
FILE *f;
udev = calloc(1, sizeof(struct udev));
if (udev == NULL)
return NULL;
udev->refcount = 1;
udev->log_fn = log_stderr;
udev->log_priority = LOG_ERR;
udev_list_init(udev, &udev->properties_list, true);
udev = calloc(1, sizeof(struct udev));
if (udev == NULL)
return NULL;
udev->refcount = 1;
udev->log_fn = log_stderr;
udev->log_priority = LOG_ERR;
udev_list_init(udev, &udev->properties_list, true);
/* custom config file */
env = getenv("UDEV_CONFIG_FILE");
if (env != NULL) {
if (set_value(&config_file, env) == NULL)
goto err;
udev_add_property(udev, "UDEV_CONFIG_FILE", config_file);
}
/* custom config file */
env = getenv("UDEV_CONFIG_FILE");
if (env != NULL) {
if (set_value(&config_file, env) == NULL)
goto err;
udev_add_property(udev, "UDEV_CONFIG_FILE", config_file);
}
/* default config file */
if (config_file == NULL)
config_file = strdup(SYSCONFDIR "/udev/udev.conf");
if (config_file == NULL)
goto err;
/* default config file */
if (config_file == NULL)
config_file = strdup(SYSCONFDIR "/udev/udev.conf");
if (config_file == NULL)
goto err;
f = fopen(config_file, "re");
if (f != NULL) {
char line[UTIL_LINE_SIZE];
int line_nr = 0;
f = fopen(config_file, "re");
if (f != NULL) {
char line[UTIL_LINE_SIZE];
int line_nr = 0;
while (fgets(line, sizeof(line), f)) {
size_t len;
char *key;
char *val;
while (fgets(line, sizeof(line), f)) {
size_t len;
char *key;
char *val;
line_nr++;
line_nr++;
/* find key */
key = line;
while (isspace(key[0]))
key++;
/* find key */
key = line;
while (isspace(key[0]))
key++;
/* comment or empty line */
if (key[0] == '#' || key[0] == '\0')
continue;
/* comment or empty line */
if (key[0] == '#' || key[0] == '\0')
continue;
/* split key/value */
val = strchr(key, '=');
if (val == NULL) {
err(udev, "missing <key>=<value> in '%s'[%i], skip line\n", config_file, line_nr);
continue;
}
val[0] = '\0';
val++;
/* split key/value */
val = strchr(key, '=');
if (val == NULL) {
err(udev, "missing <key>=<value> in '%s'[%i], skip line\n", config_file, line_nr);
continue;
}
val[0] = '\0';
val++;
/* find value */
while (isspace(val[0]))
val++;
/* find value */
while (isspace(val[0]))
val++;
/* terminate key */
len = strlen(key);
if (len == 0)
continue;
while (isspace(key[len-1]))
len--;
key[len] = '\0';
/* terminate key */
len = strlen(key);
if (len == 0)
continue;
while (isspace(key[len-1]))
len--;
key[len] = '\0';
/* terminate value */
len = strlen(val);
if (len == 0)
continue;
while (isspace(val[len-1]))
len--;
val[len] = '\0';
/* terminate value */
len = strlen(val);
if (len == 0)
continue;
while (isspace(val[len-1]))
len--;
val[len] = '\0';
if (len == 0)
continue;
if (len == 0)
continue;
/* unquote */
if (val[0] == '"' || val[0] == '\'') {
if (val[len-1] != val[0]) {
err(udev, "inconsistent quoting in '%s'[%i], skip line\n", config_file, line_nr);
continue;
}
val[len-1] = '\0';
val++;
}
/* unquote */
if (val[0] == '"' || val[0] == '\'') {
if (val[len-1] != val[0]) {
err(udev, "inconsistent quoting in '%s'[%i], skip line\n", config_file, line_nr);
continue;
}
val[len-1] = '\0';
val++;
}
if (strcmp(key, "udev_log") == 0) {
udev_set_log_priority(udev, util_log_priority(val));
continue;
}
if (strcmp(key, "udev_root") == 0) {
set_value(&udev->dev_path, val);
continue;
}
if (strcmp(key, "udev_run") == 0) {
set_value(&udev->run_path, val);
continue;
}
if (strcmp(key, "udev_sys") == 0) {
set_value(&udev->sys_path, val);
continue;
}
if (strcmp(key, "udev_rules") == 0) {
set_value(&udev->rules_path[0], val);
udev->rules_path_count = 1;
continue;
}
}
fclose(f);
}
if (strcmp(key, "udev_log") == 0) {
udev_set_log_priority(udev, util_log_priority(val));
continue;
}
if (strcmp(key, "udev_root") == 0) {
set_value(&udev->dev_path, val);
continue;
}
if (strcmp(key, "udev_run") == 0) {
set_value(&udev->run_path, val);
continue;
}
if (strcmp(key, "udev_sys") == 0) {
set_value(&udev->sys_path, val);
continue;
}
if (strcmp(key, "udev_rules") == 0) {
set_value(&udev->rules_path[0], val);
udev->rules_path_count = 1;
continue;
}
}
fclose(f);
}
/* environment overwrites config */
env = getenv("UDEV_LOG");
if (env != NULL)
udev_set_log_priority(udev, util_log_priority(env));
/* environment overwrites config */
env = getenv("UDEV_LOG");
if (env != NULL)
udev_set_log_priority(udev, util_log_priority(env));
/* set defaults */
if (udev->dev_path == NULL)
if (set_value(&udev->dev_path, "/dev") == NULL)
goto err;
/* set defaults */
if (udev->dev_path == NULL)
if (set_value(&udev->dev_path, "/dev") == NULL)
goto err;
if (udev->sys_path == NULL)
if (set_value(&udev->sys_path, "/sys") == NULL)
goto err;
if (udev->sys_path == NULL)
if (set_value(&udev->sys_path, "/sys") == NULL)
goto err;
if (udev->run_path == NULL)
if (set_value(&udev->run_path, "/run/udev") == NULL)
goto err;
if (udev->run_path == NULL)
if (set_value(&udev->run_path, "/run/udev") == NULL)
goto err;
if (udev->rules_path[0] == NULL) {
/* /usr/lib/udev -- system rules */
udev->rules_path[0] = strdup(PKGLIBEXECDIR "/rules.d");
if (!udev->rules_path[0])
goto err;
if (udev->rules_path[0] == NULL) {
/* /usr/lib/udev -- system rules */
udev->rules_path[0] = strdup(PKGLIBEXECDIR "/rules.d");
if (!udev->rules_path[0])
goto err;
/* /etc/udev -- local administration rules */
udev->rules_path[1] = strdup(SYSCONFDIR "/udev/rules.d");
if (!udev->rules_path[1])
goto err;
/* /etc/udev -- local administration rules */
udev->rules_path[1] = strdup(SYSCONFDIR "/udev/rules.d");
if (!udev->rules_path[1])
goto err;
/* /run/udev -- runtime rules */
if (asprintf(&udev->rules_path[2], "%s/rules.d", udev->run_path) < 0)
goto err;
/* /run/udev -- runtime rules */
if (asprintf(&udev->rules_path[2], "%s/rules.d", udev->run_path) < 0)
goto err;
udev->rules_path_count = 3;
}
udev->rules_path_count = 3;
}
dbg(udev, "context %p created\n", udev);
dbg(udev, "log_priority=%d\n", udev->log_priority);
dbg(udev, "config_file='%s'\n", config_file);
dbg(udev, "dev_path='%s'\n", udev->dev_path);
dbg(udev, "sys_path='%s'\n", udev->sys_path);
dbg(udev, "run_path='%s'\n", udev->run_path);
dbg(udev, "rules_path='%s':'%s':'%s'\n", udev->rules_path[0], udev->rules_path[1], udev->rules_path[2]);
free(config_file);
return udev;
dbg(udev, "context %p created\n", udev);
dbg(udev, "log_priority=%d\n", udev->log_priority);
dbg(udev, "config_file='%s'\n", config_file);
dbg(udev, "dev_path='%s'\n", udev->dev_path);
dbg(udev, "sys_path='%s'\n", udev->sys_path);
dbg(udev, "run_path='%s'\n", udev->run_path);
dbg(udev, "rules_path='%s':'%s':'%s'\n", udev->rules_path[0], udev->rules_path[1], udev->rules_path[2]);
free(config_file);
return udev;
err:
free(config_file);
err(udev, "context creation failed\n");
udev_unref(udev);
return NULL;
free(config_file);
err(udev, "context creation failed\n");
udev_unref(udev);
return NULL;
}
/**
@@ -298,10 +298,10 @@ err:
**/
UDEV_EXPORT struct udev *udev_ref(struct udev *udev)
{
if (udev == NULL)
return NULL;
udev->refcount++;
return udev;
if (udev == NULL)
return NULL;
udev->refcount++;
return udev;
}
/**
@@ -314,20 +314,20 @@ UDEV_EXPORT struct udev *udev_ref(struct udev *udev)
**/
UDEV_EXPORT void udev_unref(struct udev *udev)
{
if (udev == NULL)
return;
udev->refcount--;
if (udev->refcount > 0)
return;
udev_list_cleanup(&udev->properties_list);
free(udev->dev_path);
free(udev->sys_path);
free(udev->rules_path[0]);
free(udev->rules_path[1]);
free(udev->rules_path[2]);
free(udev->run_path);
dbg(udev, "context %p released\n", udev);
free(udev);
if (udev == NULL)
return;
udev->refcount--;
if (udev->refcount > 0)
return;
udev_list_cleanup(&udev->properties_list);
free(udev->dev_path);
free(udev->sys_path);
free(udev->rules_path[0]);
free(udev->rules_path[1]);
free(udev->rules_path[2]);
free(udev->run_path);
dbg(udev, "context %p released\n", udev);
free(udev);
}
/**
@@ -341,12 +341,12 @@ UDEV_EXPORT void udev_unref(struct udev *udev)
*
**/
UDEV_EXPORT void udev_set_log_fn(struct udev *udev,
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args))
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args))
{
udev->log_fn = log_fn;
info(udev, "custom logging function %p registered\n", log_fn);
udev->log_fn = log_fn;
info(udev, "custom logging function %p registered\n", log_fn);
}
/**
@@ -360,7 +360,7 @@ UDEV_EXPORT void udev_set_log_fn(struct udev *udev,
**/
UDEV_EXPORT int udev_get_log_priority(struct udev *udev)
{
return udev->log_priority;
return udev->log_priority;
}
/**
@@ -373,19 +373,19 @@ UDEV_EXPORT int udev_get_log_priority(struct udev *udev)
**/
UDEV_EXPORT void udev_set_log_priority(struct udev *udev, int priority)
{
char num[32];
char num[32];
udev->log_priority = priority;
snprintf(num, sizeof(num), "%u", udev->log_priority);
udev_add_property(udev, "UDEV_LOG", num);
udev->log_priority = priority;
snprintf(num, sizeof(num), "%u", udev->log_priority);
udev_add_property(udev, "UDEV_LOG", num);
}
int udev_get_rules_path(struct udev *udev, char **path[], unsigned long long *stamp_usec[])
{
*path = udev->rules_path;
if (stamp_usec)
*stamp_usec = udev->rules_path_ts;
return udev->rules_path_count;
*path = udev->rules_path;
if (stamp_usec)
*stamp_usec = udev->rules_path_ts;
return udev->rules_path_count;
}
/**
@@ -400,9 +400,9 @@ int udev_get_rules_path(struct udev *udev, char **path[], unsigned long long *st
**/
UDEV_EXPORT const char *udev_get_sys_path(struct udev *udev)
{
if (udev == NULL)
return NULL;
return udev->sys_path;
if (udev == NULL)
return NULL;
return udev->sys_path;
}
/**
@@ -417,9 +417,9 @@ UDEV_EXPORT const char *udev_get_sys_path(struct udev *udev)
**/
UDEV_EXPORT const char *udev_get_dev_path(struct udev *udev)
{
if (udev == NULL)
return NULL;
return udev->dev_path;
if (udev == NULL)
return NULL;
return udev->dev_path;
}
/**
@@ -432,26 +432,26 @@ UDEV_EXPORT const char *udev_get_dev_path(struct udev *udev)
**/
UDEV_EXPORT const char *udev_get_run_path(struct udev *udev)
{
if (udev == NULL)
return NULL;
return udev->run_path;
if (udev == NULL)
return NULL;
return udev->run_path;
}
struct udev_list_entry *udev_add_property(struct udev *udev, const char *key, const char *value)
{
if (value == NULL) {
struct udev_list_entry *list_entry;
if (value == NULL) {
struct udev_list_entry *list_entry;
list_entry = udev_get_properties_list_entry(udev);
list_entry = udev_list_entry_get_by_name(list_entry, key);
if (list_entry != NULL)
udev_list_entry_delete(list_entry);
return NULL;
}
return udev_list_entry_add(&udev->properties_list, key, value);
list_entry = udev_get_properties_list_entry(udev);
list_entry = udev_list_entry_get_by_name(list_entry, key);
if (list_entry != NULL)
udev_list_entry_delete(list_entry);
return NULL;
}
return udev_list_entry_add(&udev->properties_list, key, value);
}
struct udev_list_entry *udev_get_properties_list_entry(struct udev *udev)
{
return udev_list_get_entry(&udev->properties_list);
return udev_list_get_entry(&udev->properties_list);
}
+9 -9
View File
@@ -31,9 +31,9 @@ struct udev *udev_ref(struct udev *udev);
void udev_unref(struct udev *udev);
struct udev *udev_new(void);
void udev_set_log_fn(struct udev *udev,
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args));
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args));
int udev_get_log_priority(struct udev *udev);
void udev_set_log_priority(struct udev *udev, int priority);
const char *udev_get_sys_path(struct udev *udev);
@@ -60,9 +60,9 @@ const char *udev_list_entry_get_value(struct udev_list_entry *list_entry);
* Helper to iterate over all entries of a list.
*/
#define udev_list_entry_foreach(list_entry, first_entry) \
for (list_entry = first_entry; \
list_entry != NULL; \
list_entry = udev_list_entry_get_next(list_entry))
for (list_entry = first_entry; \
list_entry != NULL; \
list_entry = udev_list_entry_get_next(list_entry))
/*
* udev_device
@@ -80,7 +80,7 @@ struct udev_device *udev_device_new_from_environment(struct udev *udev);
/* udev_device_get_parent_*() does not take a reference on the returned device, it is automatically unref'd with the parent */
struct udev_device *udev_device_get_parent(struct udev_device *udev_device);
struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device,
const char *subsystem, const char *devtype);
const char *subsystem, const char *devtype);
/* retrieve device properties */
const char *udev_device_get_devpath(struct udev_device *udev_device);
const char *udev_device_get_subsystem(struct udev_device *udev_device);
@@ -123,7 +123,7 @@ int udev_monitor_get_fd(struct udev_monitor *udev_monitor);
struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor);
/* in-kernel socket filters to select messages that get delivered to a listener */
int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor,
const char *subsystem, const char *devtype);
const char *subsystem, const char *devtype);
int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag);
int udev_monitor_filter_update(struct udev_monitor *udev_monitor);
int udev_monitor_filter_remove(struct udev_monitor *udev_monitor);
@@ -171,7 +171,7 @@ int udev_queue_get_udev_is_active(struct udev_queue *udev_queue);
int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue);
int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum);
int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
unsigned long long int start, unsigned long long int end);
unsigned long long int start, unsigned long long int end);
struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue);
/*
+374 -374
View File
@@ -25,477 +25,477 @@
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static void log_fn(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args)
int priority, const char *file, int line, const char *fn,
const char *format, va_list args)
{
printf("test-libudev: %s %s:%d ", fn, file, line);
vprintf(format, args);
printf("test-libudev: %s %s:%d ", fn, file, line);
vprintf(format, args);
}
static void print_device(struct udev_device *device)
{
const char *str;
dev_t devnum;
int count;
struct udev_list_entry *list_entry;
const char *str;
dev_t devnum;
int count;
struct udev_list_entry *list_entry;
printf("*** device: %p ***\n", device);
str = udev_device_get_action(device);
if (str != NULL)
printf("action: '%s'\n", str);
printf("*** device: %p ***\n", device);
str = udev_device_get_action(device);
if (str != NULL)
printf("action: '%s'\n", str);
str = udev_device_get_syspath(device);
printf("syspath: '%s'\n", str);
str = udev_device_get_syspath(device);
printf("syspath: '%s'\n", str);
str = udev_device_get_sysname(device);
printf("sysname: '%s'\n", str);
str = udev_device_get_sysname(device);
printf("sysname: '%s'\n", str);
str = udev_device_get_sysnum(device);
if (str != NULL)
printf("sysnum: '%s'\n", str);
str = udev_device_get_sysnum(device);
if (str != NULL)
printf("sysnum: '%s'\n", str);
str = udev_device_get_devpath(device);
printf("devpath: '%s'\n", str);
str = udev_device_get_devpath(device);
printf("devpath: '%s'\n", str);
str = udev_device_get_subsystem(device);
if (str != NULL)
printf("subsystem: '%s'\n", str);
str = udev_device_get_subsystem(device);
if (str != NULL)
printf("subsystem: '%s'\n", str);
str = udev_device_get_devtype(device);
if (str != NULL)
printf("devtype: '%s'\n", str);
str = udev_device_get_devtype(device);
if (str != NULL)
printf("devtype: '%s'\n", str);
str = udev_device_get_driver(device);
if (str != NULL)
printf("driver: '%s'\n", str);
str = udev_device_get_driver(device);
if (str != NULL)
printf("driver: '%s'\n", str);
str = udev_device_get_devnode(device);
if (str != NULL)
printf("devname: '%s'\n", str);
str = udev_device_get_devnode(device);
if (str != NULL)
printf("devname: '%s'\n", str);
devnum = udev_device_get_devnum(device);
if (major(devnum) > 0)
printf("devnum: %u:%u\n", major(devnum), minor(devnum));
devnum = udev_device_get_devnum(device);
if (major(devnum) > 0)
printf("devnum: %u:%u\n", major(devnum), minor(devnum));
count = 0;
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
printf("link: '%s'\n", udev_list_entry_get_name(list_entry));
count++;
}
if (count > 0)
printf("found %i links\n", count);
count = 0;
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
printf("link: '%s'\n", udev_list_entry_get_name(list_entry));
count++;
}
if (count > 0)
printf("found %i links\n", count);
count = 0;
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device)) {
printf("property: '%s=%s'\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
count++;
}
if (count > 0)
printf("found %i properties\n", count);
count = 0;
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device)) {
printf("property: '%s=%s'\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
count++;
}
if (count > 0)
printf("found %i properties\n", count);
str = udev_device_get_property_value(device, "MAJOR");
if (str != NULL)
printf("MAJOR: '%s'\n", str);
str = udev_device_get_property_value(device, "MAJOR");
if (str != NULL)
printf("MAJOR: '%s'\n", str);
str = udev_device_get_sysattr_value(device, "dev");
if (str != NULL)
printf("attr{dev}: '%s'\n", str);
str = udev_device_get_sysattr_value(device, "dev");
if (str != NULL)
printf("attr{dev}: '%s'\n", str);
printf("\n");
printf("\n");
}
static int test_device(struct udev *udev, const char *syspath)
{
struct udev_device *device;
struct udev_device *device;
printf("looking at device: %s\n", syspath);
device = udev_device_new_from_syspath(udev, syspath);
if (device == NULL) {
printf("no device found\n");
return -1;
}
print_device(device);
udev_device_unref(device);
return 0;
printf("looking at device: %s\n", syspath);
device = udev_device_new_from_syspath(udev, syspath);
if (device == NULL) {
printf("no device found\n");
return -1;
}
print_device(device);
udev_device_unref(device);
return 0;
}
static int test_device_parents(struct udev *udev, const char *syspath)
{
struct udev_device *device;
struct udev_device *device_parent;
struct udev_device *device;
struct udev_device *device_parent;
printf("looking at device: %s\n", syspath);
device = udev_device_new_from_syspath(udev, syspath);
if (device == NULL)
return -1;
printf("looking at device: %s\n", syspath);
device = udev_device_new_from_syspath(udev, syspath);
if (device == NULL)
return -1;
printf("looking at parents\n");
device_parent = device;
do {
print_device(device_parent);
device_parent = udev_device_get_parent(device_parent);
} while (device_parent != NULL);
printf("looking at parents\n");
device_parent = device;
do {
print_device(device_parent);
device_parent = udev_device_get_parent(device_parent);
} while (device_parent != NULL);
printf("looking at parents again\n");
device_parent = device;
do {
print_device(device_parent);
device_parent = udev_device_get_parent(device_parent);
} while (device_parent != NULL);
udev_device_unref(device);
printf("looking at parents again\n");
device_parent = device;
do {
print_device(device_parent);
device_parent = udev_device_get_parent(device_parent);
} while (device_parent != NULL);
udev_device_unref(device);
return 0;
return 0;
}
static int test_device_devnum(struct udev *udev)
{
dev_t devnum = makedev(1, 3);
struct udev_device *device;
dev_t devnum = makedev(1, 3);
struct udev_device *device;
printf("looking up device: %u:%u\n", major(devnum), minor(devnum));
device = udev_device_new_from_devnum(udev, 'c', devnum);
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
return 0;
printf("looking up device: %u:%u\n", major(devnum), minor(devnum));
device = udev_device_new_from_devnum(udev, 'c', devnum);
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
return 0;
}
static int test_device_subsys_name(struct udev *udev)
{
struct udev_device *device;
struct udev_device *device;
printf("looking up device: 'block':'sda'\n");
device = udev_device_new_from_subsystem_sysname(udev, "block", "sda");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'block':'sda'\n");
device = udev_device_new_from_subsystem_sysname(udev, "block", "sda");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'subsystem':'pci'\n");
device = udev_device_new_from_subsystem_sysname(udev, "subsystem", "pci");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'subsystem':'pci'\n");
device = udev_device_new_from_subsystem_sysname(udev, "subsystem", "pci");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'drivers':'scsi:sd'\n");
device = udev_device_new_from_subsystem_sysname(udev, "drivers", "scsi:sd");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'drivers':'scsi:sd'\n");
device = udev_device_new_from_subsystem_sysname(udev, "drivers", "scsi:sd");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
printf("looking up device: 'module':'printk'\n");
device = udev_device_new_from_subsystem_sysname(udev, "module", "printk");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
return 0;
printf("looking up device: 'module':'printk'\n");
device = udev_device_new_from_subsystem_sysname(udev, "module", "printk");
if (device == NULL)
return -1;
print_device(device);
udev_device_unref(device);
return 0;
}
static int test_enumerate_print_list(struct udev_enumerate *enumerate)
{
struct udev_list_entry *list_entry;
int count = 0;
struct udev_list_entry *list_entry;
int count = 0;
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
struct udev_device *device;
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device != NULL) {
printf("device: '%s' (%s)\n",
udev_device_get_syspath(device),
udev_device_get_subsystem(device));
udev_device_unref(device);
count++;
}
}
printf("found %i devices\n\n", count);
return count;
device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
udev_list_entry_get_name(list_entry));
if (device != NULL) {
printf("device: '%s' (%s)\n",
udev_device_get_syspath(device),
udev_device_get_subsystem(device));
udev_device_unref(device);
count++;
}
}
printf("found %i devices\n\n", count);
return count;
}
static int test_monitor(struct udev *udev)
{
struct udev_monitor *udev_monitor = NULL;
int fd_ep;
int fd_udev = -1;
struct epoll_event ep_udev, ep_stdin;
struct udev_monitor *udev_monitor = NULL;
int fd_ep;
int fd_udev = -1;
struct epoll_event ep_udev, ep_stdin;
fd_ep = epoll_create1(EPOLL_CLOEXEC);
if (fd_ep < 0) {
printf("error creating epoll fd: %m\n");
goto out;
}
fd_ep = epoll_create1(EPOLL_CLOEXEC);
if (fd_ep < 0) {
printf("error creating epoll fd: %m\n");
goto out;
}
udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
if (udev_monitor == NULL) {
printf("no socket\n");
goto out;
}
fd_udev = udev_monitor_get_fd(udev_monitor);
udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
if (udev_monitor == NULL) {
printf("no socket\n");
goto out;
}
fd_udev = udev_monitor_get_fd(udev_monitor);
if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "block", NULL) < 0 ||
udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "tty", NULL) < 0 ||
udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "usb", "usb_device") < 0) {
printf("filter failed\n");
goto out;
}
if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "block", NULL) < 0 ||
udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "tty", NULL) < 0 ||
udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "usb", "usb_device") < 0) {
printf("filter failed\n");
goto out;
}
if (udev_monitor_enable_receiving(udev_monitor) < 0) {
printf("bind failed\n");
goto out;
}
if (udev_monitor_enable_receiving(udev_monitor) < 0) {
printf("bind failed\n");
goto out;
}
memset(&ep_udev, 0, sizeof(struct epoll_event));
ep_udev.events = EPOLLIN;
ep_udev.data.fd = fd_udev;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
printf("fail to add fd to epoll: %m\n");
goto out;
}
memset(&ep_udev, 0, sizeof(struct epoll_event));
ep_udev.events = EPOLLIN;
ep_udev.data.fd = fd_udev;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
printf("fail to add fd to epoll: %m\n");
goto out;
}
memset(&ep_stdin, 0, sizeof(struct epoll_event));
ep_stdin.events = EPOLLIN;
ep_stdin.data.fd = STDIN_FILENO;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, STDIN_FILENO, &ep_stdin) < 0) {
printf("fail to add fd to epoll: %m\n");
goto out;
}
memset(&ep_stdin, 0, sizeof(struct epoll_event));
ep_stdin.events = EPOLLIN;
ep_stdin.data.fd = STDIN_FILENO;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, STDIN_FILENO, &ep_stdin) < 0) {
printf("fail to add fd to epoll: %m\n");
goto out;
}
for (;;) {
int fdcount;
struct epoll_event ev[4];
struct udev_device *device;
int i;
for (;;) {
int fdcount;
struct epoll_event ev[4];
struct udev_device *device;
int i;
printf("waiting for events from udev, press ENTER to exit\n");
fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
printf("epoll fd count: %i\n", fdcount);
printf("waiting for events from udev, press ENTER to exit\n");
fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
printf("epoll fd count: %i\n", fdcount);
for (i = 0; i < fdcount; i++) {
if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
device = udev_monitor_receive_device(udev_monitor);
if (device == NULL) {
printf("no device from socket\n");
continue;
}
print_device(device);
udev_device_unref(device);
} else if (ev[i].data.fd == STDIN_FILENO && ev[i].events & EPOLLIN) {
printf("exiting loop\n");
goto out;
}
}
}
for (i = 0; i < fdcount; i++) {
if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
device = udev_monitor_receive_device(udev_monitor);
if (device == NULL) {
printf("no device from socket\n");
continue;
}
print_device(device);
udev_device_unref(device);
} else if (ev[i].data.fd == STDIN_FILENO && ev[i].events & EPOLLIN) {
printf("exiting loop\n");
goto out;
}
}
}
out:
if (fd_ep >= 0)
close(fd_ep);
udev_monitor_unref(udev_monitor);
return 0;
if (fd_ep >= 0)
close(fd_ep);
udev_monitor_unref(udev_monitor);
return 0;
}
static int test_queue(struct udev *udev)
{
struct udev_queue *udev_queue;
unsigned long long int seqnum;
struct udev_list_entry *list_entry;
struct udev_queue *udev_queue;
unsigned long long int seqnum;
struct udev_list_entry *list_entry;
udev_queue = udev_queue_new(udev);
if (udev_queue == NULL)
return -1;
seqnum = udev_queue_get_kernel_seqnum(udev_queue);
printf("seqnum kernel: %llu\n", seqnum);
seqnum = udev_queue_get_udev_seqnum(udev_queue);
printf("seqnum udev : %llu\n", seqnum);
udev_queue = udev_queue_new(udev);
if (udev_queue == NULL)
return -1;
seqnum = udev_queue_get_kernel_seqnum(udev_queue);
printf("seqnum kernel: %llu\n", seqnum);
seqnum = udev_queue_get_udev_seqnum(udev_queue);
printf("seqnum udev : %llu\n", seqnum);
if (udev_queue_get_queue_is_empty(udev_queue))
printf("queue is empty\n");
printf("get queue list\n");
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
printf("\n");
printf("get queue list again\n");
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
printf("\n");
if (udev_queue_get_queue_is_empty(udev_queue))
printf("queue is empty\n");
printf("get queue list\n");
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
printf("\n");
printf("get queue list again\n");
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf("queued: '%s' [%s]\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
printf("\n");
list_entry = udev_queue_get_queued_list_entry(udev_queue);
if (list_entry != NULL) {
printf("event [%llu] is queued\n", seqnum);
seqnum = strtoull(udev_list_entry_get_value(list_entry), NULL, 10);
if (udev_queue_get_seqnum_is_finished(udev_queue, seqnum))
printf("event [%llu] is not finished\n", seqnum);
else
printf("event [%llu] is finished\n", seqnum);
}
printf("\n");
udev_queue_unref(udev_queue);
return 0;
list_entry = udev_queue_get_queued_list_entry(udev_queue);
if (list_entry != NULL) {
printf("event [%llu] is queued\n", seqnum);
seqnum = strtoull(udev_list_entry_get_value(list_entry), NULL, 10);
if (udev_queue_get_seqnum_is_finished(udev_queue, seqnum))
printf("event [%llu] is not finished\n", seqnum);
else
printf("event [%llu] is finished\n", seqnum);
}
printf("\n");
udev_queue_unref(udev_queue);
return 0;
}
static int test_enumerate(struct udev *udev, const char *subsystem)
{
struct udev_enumerate *udev_enumerate;
struct udev_enumerate *udev_enumerate;
printf("enumerate '%s'\n", subsystem == NULL ? "<all>" : subsystem);
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, subsystem);
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate '%s'\n", subsystem == NULL ? "<all>" : subsystem);
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, subsystem);
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'net' + duplicated scan + null + zero\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, "net");
udev_enumerate_scan_devices(udev_enumerate);
udev_enumerate_scan_devices(udev_enumerate);
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'net' + duplicated scan + null + zero\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, "net");
udev_enumerate_scan_devices(udev_enumerate);
udev_enumerate_scan_devices(udev_enumerate);
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/null");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_add_syspath(udev_enumerate, "/sys/class/mem/zero");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'block'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate,"block");
udev_enumerate_add_match_is_initialized(udev_enumerate);
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'block'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate,"block");
udev_enumerate_add_match_is_initialized(udev_enumerate);
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'not block'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_nomatch_subsystem(udev_enumerate, "block");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'not block'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_nomatch_subsystem(udev_enumerate, "block");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'pci, mem, vc'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, "pci");
udev_enumerate_add_match_subsystem(udev_enumerate, "mem");
udev_enumerate_add_match_subsystem(udev_enumerate, "vc");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'pci, mem, vc'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_subsystem(udev_enumerate, "pci");
udev_enumerate_add_match_subsystem(udev_enumerate, "mem");
udev_enumerate_add_match_subsystem(udev_enumerate, "vc");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'subsystem'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_scan_subsystems(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'subsystem'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_scan_subsystems(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
printf("enumerate 'property IF_FS_*=filesystem'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_property(udev_enumerate, "ID_FS*", "filesystem");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
return 0;
printf("enumerate 'property IF_FS_*=filesystem'\n");
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_add_match_property(udev_enumerate, "ID_FS*", "filesystem");
udev_enumerate_scan_devices(udev_enumerate);
test_enumerate_print_list(udev_enumerate);
udev_enumerate_unref(udev_enumerate);
return 0;
}
int main(int argc, char *argv[])
{
struct udev *udev = NULL;
static const struct option options[] = {
{ "syspath", required_argument, NULL, 'p' },
{ "subsystem", required_argument, NULL, 's' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
{}
};
const char *syspath = "/devices/virtual/mem/null";
const char *subsystem = NULL;
char path[1024];
const char *str;
struct udev *udev = NULL;
static const struct option options[] = {
{ "syspath", required_argument, NULL, 'p' },
{ "subsystem", required_argument, NULL, 's' },
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
{}
};
const char *syspath = "/devices/virtual/mem/null";
const char *subsystem = NULL;
char path[1024];
const char *str;
udev = udev_new();
printf("context: %p\n", udev);
if (udev == NULL) {
printf("no context\n");
return 1;
}
udev_set_log_fn(udev, log_fn);
printf("set log: %p\n", log_fn);
udev = udev_new();
printf("context: %p\n", udev);
if (udev == NULL) {
printf("no context\n");
return 1;
}
udev_set_log_fn(udev, log_fn);
printf("set log: %p\n", log_fn);
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "+p:s:dhV", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "+p:s:dhV", options, NULL);
if (option == -1)
break;
switch (option) {
case 'p':
syspath = optarg;
break;
case 's':
subsystem = optarg;
break;
case 'd':
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
printf("--debug --syspath= --subsystem= --help\n");
goto out;
case 'V':
printf("%s\n", VERSION);
goto out;
default:
goto out;
}
}
switch (option) {
case 'p':
syspath = optarg;
break;
case 's':
subsystem = optarg;
break;
case 'd':
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
printf("--debug --syspath= --subsystem= --help\n");
goto out;
case 'V':
printf("%s\n", VERSION);
goto out;
default:
goto out;
}
}
str = udev_get_sys_path(udev);
printf("sys_path: '%s'\n", str);
str = udev_get_dev_path(udev);
printf("dev_path: '%s'\n", str);
str = udev_get_sys_path(udev);
printf("sys_path: '%s'\n", str);
str = udev_get_dev_path(udev);
printf("dev_path: '%s'\n", str);
/* add sys path if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0) {
snprintf(path, sizeof(path), "%s%s", udev_get_sys_path(udev), syspath);
syspath = path;
}
/* add sys path if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0) {
snprintf(path, sizeof(path), "%s%s", udev_get_sys_path(udev), syspath);
syspath = path;
}
test_device(udev, syspath);
test_device_devnum(udev);
test_device_subsys_name(udev);
test_device_parents(udev, syspath);
test_device(udev, syspath);
test_device_devnum(udev);
test_device_subsys_name(udev);
test_device_parents(udev, syspath);
test_enumerate(udev, subsystem);
test_enumerate(udev, subsystem);
test_queue(udev);
test_queue(udev);
test_monitor(udev);
test_monitor(udev);
out:
udev_unref(udev);
return 0;
udev_unref(udev);
return 0;
}
+71 -71
View File
@@ -31,91 +31,91 @@
#include "udev.h"
void udev_main_log(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args) {}
const char *file, int line, const char *fn,
const char *format, va_list args) {}
int main(int argc, char *argv[])
{
struct udev *udev;
struct udev_event *event = NULL;
struct udev_device *dev = NULL;
struct udev_rules *rules = NULL;
char syspath[UTIL_PATH_SIZE];
const char *devpath;
const char *action;
sigset_t mask, sigmask_orig;
int err = -EINVAL;
struct udev *udev;
struct udev_event *event = NULL;
struct udev_device *dev = NULL;
struct udev_rules *rules = NULL;
char syspath[UTIL_PATH_SIZE];
const char *devpath;
const char *action;
sigset_t mask, sigmask_orig;
int err = -EINVAL;
udev = udev_new();
if (udev == NULL)
exit(1);
info(udev, "version %s\n", VERSION);
udev_selinux_init(udev);
udev = udev_new();
if (udev == NULL)
exit(1);
info(udev, "version %s\n", VERSION);
udev_selinux_init(udev);
sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
action = argv[1];
if (action == NULL) {
err(udev, "action missing\n");
goto out;
}
action = argv[1];
if (action == NULL) {
err(udev, "action missing\n");
goto out;
}
devpath = argv[2];
if (devpath == NULL) {
err(udev, "devpath missing\n");
goto out;
}
devpath = argv[2];
if (devpath == NULL) {
err(udev, "devpath missing\n");
goto out;
}
rules = udev_rules_new(udev, 1);
rules = udev_rules_new(udev, 1);
util_strscpyl(syspath, sizeof(syspath), udev_get_sys_path(udev), devpath, NULL);
dev = udev_device_new_from_syspath(udev, syspath);
if (dev == NULL) {
info(udev, "unknown device '%s'\n", devpath);
goto out;
}
util_strscpyl(syspath, sizeof(syspath), udev_get_sys_path(udev), devpath, NULL);
dev = udev_device_new_from_syspath(udev, syspath);
if (dev == NULL) {
info(udev, "unknown device '%s'\n", devpath);
goto out;
}
udev_device_set_action(dev, action);
event = udev_event_new(dev);
udev_device_set_action(dev, action);
event = udev_event_new(dev);
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (event->fd_signal < 0) {
fprintf(stderr, "error creating signalfd\n");
goto out;
}
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (event->fd_signal < 0) {
fprintf(stderr, "error creating signalfd\n");
goto out;
}
/* do what devtmpfs usually provides us */
if (udev_device_get_devnode(dev) != NULL) {
mode_t mode;
/* do what devtmpfs usually provides us */
if (udev_device_get_devnode(dev) != NULL) {
mode_t mode;
if (strcmp(udev_device_get_subsystem(dev), "block") == 0)
mode |= S_IFBLK;
else
mode |= S_IFCHR;
if (strcmp(udev_device_get_subsystem(dev), "block") == 0)
mode |= S_IFBLK;
else
mode |= S_IFCHR;
if (strcmp(action, "remove") != 0) {
util_create_path(udev, udev_device_get_devnode(dev));
mknod(udev_device_get_devnode(dev), mode, udev_device_get_devnum(dev));
} else {
unlink(udev_device_get_devnode(dev));
util_delete_path(udev, udev_device_get_devnode(dev));
}
}
if (strcmp(action, "remove") != 0) {
util_create_path(udev, udev_device_get_devnode(dev));
mknod(udev_device_get_devnode(dev), mode, udev_device_get_devnum(dev));
} else {
unlink(udev_device_get_devnode(dev));
util_delete_path(udev, udev_device_get_devnode(dev));
}
}
err = udev_event_execute_rules(event, rules, &sigmask_orig);
if (err == 0)
udev_event_execute_run(event, NULL);
err = udev_event_execute_rules(event, rules, &sigmask_orig);
if (err == 0)
udev_event_execute_run(event, NULL);
out:
if (event != NULL && event->fd_signal >= 0)
close(event->fd_signal);
udev_event_unref(event);
udev_device_unref(dev);
udev_rules_unref(rules);
udev_selinux_exit(udev);
udev_unref(udev);
if (err != 0)
return 1;
return 0;
if (event != NULL && event->fd_signal >= 0)
close(event->fd_signal);
udev_event_unref(event);
udev_device_unref(dev);
udev_rules_unref(rules);
udev_selinux_exit(udev);
udev_unref(udev);
if (err != 0)
return 1;
return 0;
}
+128 -128
View File
@@ -33,175 +33,175 @@
static void print_property(struct udev_device *dev, bool test, const char *name, const char *value)
{
char s[265];
char s[265];
s[0] = '\0';
s[0] = '\0';
if (!strcmp(name, "TYPE")) {
udev_builtin_add_property(dev, test, "ID_FS_TYPE", value);
if (!strcmp(name, "TYPE")) {
udev_builtin_add_property(dev, test, "ID_FS_TYPE", value);
} else if (!strcmp(name, "USAGE")) {
udev_builtin_add_property(dev, test, "ID_FS_USAGE", value);
} else if (!strcmp(name, "USAGE")) {
udev_builtin_add_property(dev, test, "ID_FS_USAGE", value);
} else if (!strcmp(name, "VERSION")) {
udev_builtin_add_property(dev, test, "ID_FS_VERSION", value);
} else if (!strcmp(name, "VERSION")) {
udev_builtin_add_property(dev, test, "ID_FS_VERSION", value);
} else if (!strcmp(name, "UUID")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_ENC", s);
} else if (!strcmp(name, "UUID")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_ENC", s);
} else if (!strcmp(name, "UUID_SUB")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB_ENC", s);
} else if (!strcmp(name, "UUID_SUB")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_UUID_SUB_ENC", s);
} else if (!strcmp(name, "LABEL")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_LABEL", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_LABEL_ENC", s);
} else if (!strcmp(name, "LABEL")) {
blkid_safe_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_LABEL", s);
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "ID_FS_LABEL_ENC", s);
} else if (!strcmp(name, "PTTYPE")) {
udev_builtin_add_property(dev, test, "ID_PART_TABLE_TYPE", value);
} else if (!strcmp(name, "PTTYPE")) {
udev_builtin_add_property(dev, test, "ID_PART_TABLE_TYPE", value);
} else if (!strcmp(name, "PART_ENTRY_NAME")) {
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "PART_ENTRY_NAME", s);
} else if (!strcmp(name, "PART_ENTRY_NAME")) {
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "PART_ENTRY_NAME", s);
} else if (!strcmp(name, "PART_ENTRY_TYPE")) {
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "PART_ENTRY_TYPE", s);
} else if (!strcmp(name, "PART_ENTRY_TYPE")) {
blkid_encode_string(value, s, sizeof(s));
udev_builtin_add_property(dev, test, "PART_ENTRY_TYPE", s);
} else if (!strncmp(name, "PART_ENTRY_", 11)) {
util_strscpyl(s, sizeof(s), "ID_", name, NULL);
udev_builtin_add_property(dev, test, name, value);
}
} else if (!strncmp(name, "PART_ENTRY_", 11)) {
util_strscpyl(s, sizeof(s), "ID_", name, NULL);
udev_builtin_add_property(dev, test, name, value);
}
}
static int probe_superblocks(blkid_probe pr)
{
struct stat st;
int rc;
struct stat st;
int rc;
if (fstat(blkid_probe_get_fd(pr), &st))
return -1;
if (fstat(blkid_probe_get_fd(pr), &st))
return -1;
blkid_probe_enable_partitions(pr, 1);
blkid_probe_enable_partitions(pr, 1);
if (!S_ISCHR(st.st_mode) && blkid_probe_get_size(pr) <= 1024 * 1440 &&
blkid_probe_is_wholedisk(pr)) {
/*
* check if the small disk is partitioned, if yes then
* don't probe for filesystems.
*/
blkid_probe_enable_superblocks(pr, 0);
if (!S_ISCHR(st.st_mode) && blkid_probe_get_size(pr) <= 1024 * 1440 &&
blkid_probe_is_wholedisk(pr)) {
/*
* check if the small disk is partitioned, if yes then
* don't probe for filesystems.
*/
blkid_probe_enable_superblocks(pr, 0);
rc = blkid_do_fullprobe(pr);
if (rc < 0)
return rc; /* -1 = error, 1 = nothing, 0 = succes */
rc = blkid_do_fullprobe(pr);
if (rc < 0)
return rc; /* -1 = error, 1 = nothing, 0 = succes */
if (blkid_probe_lookup_value(pr, "PTTYPE", NULL, NULL) == 0)
return 0; /* partition table detected */
}
if (blkid_probe_lookup_value(pr, "PTTYPE", NULL, NULL) == 0)
return 0; /* partition table detected */
}
blkid_probe_set_partitions_flags(pr, BLKID_PARTS_ENTRY_DETAILS);
blkid_probe_enable_superblocks(pr, 1);
blkid_probe_set_partitions_flags(pr, BLKID_PARTS_ENTRY_DETAILS);
blkid_probe_enable_superblocks(pr, 1);
return blkid_do_safeprobe(pr);
return blkid_do_safeprobe(pr);
}
static int builtin_blkid(struct udev_device *dev, int argc, char *argv[], bool test)
{
struct udev *udev = udev_device_get_udev(dev);
int64_t offset = 0;
bool noraid = false;
int fd = -1;
blkid_probe pr;
const char *data;
const char *name;
int nvals;
int i;
size_t len;
int err = 0;
struct udev *udev = udev_device_get_udev(dev);
int64_t offset = 0;
bool noraid = false;
int fd = -1;
blkid_probe pr;
const char *data;
const char *name;
int nvals;
int i;
size_t len;
int err = 0;
static const struct option options[] = {
{ "offset", optional_argument, NULL, 'o' },
{ "noraid", no_argument, NULL, 'R' },
{}
};
static const struct option options[] = {
{ "offset", optional_argument, NULL, 'o' },
{ "noraid", no_argument, NULL, 'R' },
{}
};
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "oR", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "oR", options, NULL);
if (option == -1)
break;
switch (option) {
case 'o':
offset = strtoull(optarg, NULL, 0);
break;
case 'R':
noraid = true;
break;
}
}
switch (option) {
case 'o':
offset = strtoull(optarg, NULL, 0);
break;
case 'R':
noraid = true;
break;
}
}
pr = blkid_new_probe();
if (!pr) {
err = -ENOMEM;
return EXIT_FAILURE;
}
pr = blkid_new_probe();
if (!pr) {
err = -ENOMEM;
return EXIT_FAILURE;
}
blkid_probe_set_superblocks_flags(pr,
BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID |
BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE |
BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION);
blkid_probe_set_superblocks_flags(pr,
BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID |
BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE |
BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION);
if (noraid)
blkid_probe_filter_superblocks_usage(pr, BLKID_FLTR_NOTIN, BLKID_USAGE_RAID);
if (noraid)
blkid_probe_filter_superblocks_usage(pr, BLKID_FLTR_NOTIN, BLKID_USAGE_RAID);
fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "error: %s: %m\n", udev_device_get_devnode(dev));
goto out;
}
fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "error: %s: %m\n", udev_device_get_devnode(dev));
goto out;
}
err = blkid_probe_set_device(pr, fd, offset, 0);
if (err < 0)
goto out;
err = blkid_probe_set_device(pr, fd, offset, 0);
if (err < 0)
goto out;
info(udev, "probe %s %sraid offset=%llu\n",
udev_device_get_devnode(dev),
noraid ? "no" : "", (unsigned long long) offset);
info(udev, "probe %s %sraid offset=%llu\n",
udev_device_get_devnode(dev),
noraid ? "no" : "", (unsigned long long) offset);
err = probe_superblocks(pr);
if (err < 0)
goto out;
err = probe_superblocks(pr);
if (err < 0)
goto out;
nvals = blkid_probe_numof_values(pr);
for (i = 0; i < nvals; i++) {
if (blkid_probe_get_value(pr, i, &name, &data, &len))
continue;
len = strnlen((char *) data, len);
print_property(dev, test, name, (char *) data);
}
nvals = blkid_probe_numof_values(pr);
for (i = 0; i < nvals; i++) {
if (blkid_probe_get_value(pr, i, &name, &data, &len))
continue;
len = strnlen((char *) data, len);
print_property(dev, test, name, (char *) data);
}
blkid_free_probe(pr);
blkid_free_probe(pr);
out:
if (fd > 0)
close(fd);
if (err < 0)
return EXIT_FAILURE;
return EXIT_SUCCESS;
if (fd > 0)
close(fd);
if (err < 0)
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
const struct udev_builtin udev_builtin_blkid = {
.name = "blkid",
.cmd = builtin_blkid,
.help = "filesystem and partition probing",
.run_once = true,
.name = "blkid",
.cmd = builtin_blkid,
.help = "filesystem and partition probing",
.run_once = true,
};
+109 -109
View File
@@ -29,140 +29,140 @@
static bool set_loading(struct udev *udev, char *loadpath, const char *state)
{
FILE *ldfile;
FILE *ldfile;
ldfile = fopen(loadpath, "we");
if (ldfile == NULL) {
err(udev, "error: can not open '%s'\n", loadpath);
return false;
};
fprintf(ldfile, "%s\n", state);
fclose(ldfile);
return true;
ldfile = fopen(loadpath, "we");
if (ldfile == NULL) {
err(udev, "error: can not open '%s'\n", loadpath);
return false;
};
fprintf(ldfile, "%s\n", state);
fclose(ldfile);
return true;
}
static bool copy_firmware(struct udev *udev, const char *source, const char *target, size_t size)
{
char *buf;
FILE *fsource = NULL, *ftarget = NULL;
bool ret = false;
char *buf;
FILE *fsource = NULL, *ftarget = NULL;
bool ret = false;
buf = malloc(size);
if (buf == NULL) {
err(udev,"No memory available to load firmware file");
return false;
}
buf = malloc(size);
if (buf == NULL) {
err(udev,"No memory available to load firmware file");
return false;
}
info(udev, "writing '%s' (%zi) to '%s'\n", source, size, target);
info(udev, "writing '%s' (%zi) to '%s'\n", source, size, target);
fsource = fopen(source, "re");
if (fsource == NULL)
goto exit;
ftarget = fopen(target, "we");
if (ftarget == NULL)
goto exit;
if (fread(buf, size, 1, fsource) != 1)
goto exit;
if (fwrite(buf, size, 1, ftarget) == 1)
ret = true;
fsource = fopen(source, "re");
if (fsource == NULL)
goto exit;
ftarget = fopen(target, "we");
if (ftarget == NULL)
goto exit;
if (fread(buf, size, 1, fsource) != 1)
goto exit;
if (fwrite(buf, size, 1, ftarget) == 1)
ret = true;
exit:
if (ftarget != NULL)
fclose(ftarget);
if (fsource != NULL)
fclose(fsource);
free(buf);
return ret;
if (ftarget != NULL)
fclose(ftarget);
if (fsource != NULL)
fclose(fsource);
free(buf);
return ret;
}
static int builtin_firmware(struct udev_device *dev, int argc, char *argv[], bool test)
{
struct udev *udev = udev_device_get_udev(dev);
static const char *searchpath[] = { FIRMWARE_PATH };
char fwencpath[UTIL_PATH_SIZE];
char misspath[UTIL_PATH_SIZE];
char loadpath[UTIL_PATH_SIZE];
char datapath[UTIL_PATH_SIZE];
char fwpath[UTIL_PATH_SIZE];
const char *firmware;
FILE *fwfile;
struct utsname kernel;
struct stat statbuf;
unsigned int i;
int rc = EXIT_SUCCESS;
struct udev *udev = udev_device_get_udev(dev);
static const char *searchpath[] = { FIRMWARE_PATH };
char fwencpath[UTIL_PATH_SIZE];
char misspath[UTIL_PATH_SIZE];
char loadpath[UTIL_PATH_SIZE];
char datapath[UTIL_PATH_SIZE];
char fwpath[UTIL_PATH_SIZE];
const char *firmware;
FILE *fwfile;
struct utsname kernel;
struct stat statbuf;
unsigned int i;
int rc = EXIT_SUCCESS;
firmware = udev_device_get_property_value(dev, "FIRMWARE");
if (firmware == NULL) {
err(udev, "firmware parameter missing\n\n");
rc = EXIT_FAILURE;
goto exit;
}
firmware = udev_device_get_property_value(dev, "FIRMWARE");
if (firmware == NULL) {
err(udev, "firmware parameter missing\n\n");
rc = EXIT_FAILURE;
goto exit;
}
/* lookup firmware file */
uname(&kernel);
for (i = 0; i < ARRAY_SIZE(searchpath); i++) {
util_strscpyl(fwpath, sizeof(fwpath), searchpath[i], kernel.release, "/", firmware, NULL);
dbg(udev, "trying %s\n", fwpath);
fwfile = fopen(fwpath, "re");
if (fwfile != NULL)
break;
/* lookup firmware file */
uname(&kernel);
for (i = 0; i < ARRAY_SIZE(searchpath); i++) {
util_strscpyl(fwpath, sizeof(fwpath), searchpath[i], kernel.release, "/", firmware, NULL);
dbg(udev, "trying %s\n", fwpath);
fwfile = fopen(fwpath, "re");
if (fwfile != NULL)
break;
util_strscpyl(fwpath, sizeof(fwpath), searchpath[i], firmware, NULL);
dbg(udev, "trying %s\n", fwpath);
fwfile = fopen(fwpath, "re");
if (fwfile != NULL)
break;
}
util_strscpyl(fwpath, sizeof(fwpath), searchpath[i], firmware, NULL);
dbg(udev, "trying %s\n", fwpath);
fwfile = fopen(fwpath, "re");
if (fwfile != NULL)
break;
}
util_path_encode(firmware, fwencpath, sizeof(fwencpath));
util_strscpyl(misspath, sizeof(misspath), udev_get_run_path(udev), "/firmware-missing/", fwencpath, NULL);
util_strscpyl(loadpath, sizeof(loadpath), udev_device_get_syspath(dev), "/loading", NULL);
util_path_encode(firmware, fwencpath, sizeof(fwencpath));
util_strscpyl(misspath, sizeof(misspath), udev_get_run_path(udev), "/firmware-missing/", fwencpath, NULL);
util_strscpyl(loadpath, sizeof(loadpath), udev_device_get_syspath(dev), "/loading", NULL);
if (fwfile == NULL) {
int err;
if (fwfile == NULL) {
int err;
/* This link indicates the missing firmware file and the associated device */
info(udev, "did not find firmware file '%s'\n", firmware);
do {
err = util_create_path(udev, misspath);
if (err != 0 && err != -ENOENT)
break;
err = symlink(udev_device_get_devpath(dev), misspath);
if (err != 0)
err = -errno;
} while (err == -ENOENT);
rc = EXIT_FAILURE;
set_loading(udev, loadpath, "-1");
goto exit;
}
/* This link indicates the missing firmware file and the associated device */
info(udev, "did not find firmware file '%s'\n", firmware);
do {
err = util_create_path(udev, misspath);
if (err != 0 && err != -ENOENT)
break;
err = symlink(udev_device_get_devpath(dev), misspath);
if (err != 0)
err = -errno;
} while (err == -ENOENT);
rc = EXIT_FAILURE;
set_loading(udev, loadpath, "-1");
goto exit;
}
if (stat(fwpath, &statbuf) < 0 || statbuf.st_size == 0) {
rc = EXIT_FAILURE;
goto exit;
}
if (unlink(misspath) == 0)
util_delete_path(udev, misspath);
if (stat(fwpath, &statbuf) < 0 || statbuf.st_size == 0) {
rc = EXIT_FAILURE;
goto exit;
}
if (unlink(misspath) == 0)
util_delete_path(udev, misspath);
if (!set_loading(udev, loadpath, "1"))
goto exit;
if (!set_loading(udev, loadpath, "1"))
goto exit;
util_strscpyl(datapath, sizeof(datapath), udev_device_get_syspath(dev), "/data", NULL);
if (!copy_firmware(udev, fwpath, datapath, statbuf.st_size)) {
err(udev, "error sending firmware '%s' to device\n", firmware);
set_loading(udev, loadpath, "-1");
rc = EXIT_FAILURE;
goto exit;
};
util_strscpyl(datapath, sizeof(datapath), udev_device_get_syspath(dev), "/data", NULL);
if (!copy_firmware(udev, fwpath, datapath, statbuf.st_size)) {
err(udev, "error sending firmware '%s' to device\n", firmware);
set_loading(udev, loadpath, "-1");
rc = EXIT_FAILURE;
goto exit;
};
set_loading(udev, loadpath, "0");
set_loading(udev, loadpath, "0");
exit:
if (fwfile)
fclose(fwfile);
return rc;
if (fwfile)
fclose(fwfile);
return rc;
}
const struct udev_builtin udev_builtin_firmware = {
.name = "firmware",
.cmd = builtin_firmware,
.help = "kernel firmware loader",
.run_once = true,
.name = "firmware",
.cmd = builtin_firmware,
.help = "kernel firmware loader",
.run_once = true,
};
+138 -138
View File
@@ -28,220 +28,220 @@
#include "udev.h"
static int get_id_attr(
struct udev_device *parent,
const char *name,
uint16_t *value) {
struct udev_device *parent,
const char *name,
uint16_t *value) {
const char *t;
unsigned u;
const char *t;
unsigned u;
if (!(t = udev_device_get_sysattr_value(parent, name))) {
fprintf(stderr, "%s lacks %s.\n", udev_device_get_syspath(parent), name);
return -1;
}
if (!(t = udev_device_get_sysattr_value(parent, name))) {
fprintf(stderr, "%s lacks %s.\n", udev_device_get_syspath(parent), name);
return -1;
}
if (!strncmp(t, "0x", 2))
t += 2;
if (!strncmp(t, "0x", 2))
t += 2;
if (sscanf(t, "%04x", &u) != 1 || u > 0xFFFFU) {
fprintf(stderr, "Failed to parse %s on %s.\n", name, udev_device_get_syspath(parent));
return -1;
}
if (sscanf(t, "%04x", &u) != 1 || u > 0xFFFFU) {
fprintf(stderr, "Failed to parse %s on %s.\n", name, udev_device_get_syspath(parent));
return -1;
}
*value = (uint16_t) u;
return 0;
*value = (uint16_t) u;
return 0;
}
static int get_vid_pid(
struct udev_device *parent,
const char *vendor_attr,
const char *product_attr,
uint16_t *vid,
uint16_t *pid) {
struct udev_device *parent,
const char *vendor_attr,
const char *product_attr,
uint16_t *vid,
uint16_t *pid) {
if (get_id_attr(parent, vendor_attr, vid) < 0)
return -1;
else if (*vid <= 0) {
fprintf(stderr, "Invalid vendor id.\n");
return -1;
}
if (get_id_attr(parent, vendor_attr, vid) < 0)
return -1;
else if (*vid <= 0) {
fprintf(stderr, "Invalid vendor id.\n");
return -1;
}
if (get_id_attr(parent, product_attr, pid) < 0)
return -1;
if (get_id_attr(parent, product_attr, pid) < 0)
return -1;
return 0;
return 0;
}
static void rstrip(char *n) {
size_t i;
size_t i;
for (i = strlen(n); i > 0 && isspace(n[i-1]); i--)
n[i-1] = 0;
for (i = strlen(n); i > 0 && isspace(n[i-1]); i--)
n[i-1] = 0;
}
#define HEXCHARS "0123456789abcdefABCDEF"
#define WHITESPACE " \t\n\r"
static int lookup_vid_pid(const char *database,
uint16_t vid, uint16_t pid,
char **vendor, char **product)
uint16_t vid, uint16_t pid,
char **vendor, char **product)
{
FILE *f;
int ret = -1;
int found_vendor = 0;
char *line = NULL;
FILE *f;
int ret = -1;
int found_vendor = 0;
char *line = NULL;
*vendor = *product = NULL;
*vendor = *product = NULL;
if (!(f = fopen(database, "rme"))) {
fprintf(stderr, "Failed to open database file '%s': %s\n", database, strerror(errno));
return -1;
}
if (!(f = fopen(database, "rme"))) {
fprintf(stderr, "Failed to open database file '%s': %s\n", database, strerror(errno));
return -1;
}
for (;;) {
size_t n;
for (;;) {
size_t n;
if (getline(&line, &n, f) < 0)
break;
if (getline(&line, &n, f) < 0)
break;
rstrip(line);
rstrip(line);
if (line[0] == '#' || line[0] == 0)
continue;
if (line[0] == '#' || line[0] == 0)
continue;
if (strspn(line, HEXCHARS) == 4) {
unsigned u;
if (strspn(line, HEXCHARS) == 4) {
unsigned u;
if (found_vendor)
break;
if (found_vendor)
break;
if (sscanf(line, "%04x", &u) == 1 && u == vid) {
char *t;
if (sscanf(line, "%04x", &u) == 1 && u == vid) {
char *t;
t = line+4;
t += strspn(t, WHITESPACE);
t = line+4;
t += strspn(t, WHITESPACE);
if (!(*vendor = strdup(t))) {
fprintf(stderr, "Out of memory.\n");
goto finish;
}
if (!(*vendor = strdup(t))) {
fprintf(stderr, "Out of memory.\n");
goto finish;
}
found_vendor = 1;
}
found_vendor = 1;
}
continue;
}
continue;
}
if (found_vendor && line[0] == '\t' && strspn(line+1, HEXCHARS) == 4) {
unsigned u;
if (found_vendor && line[0] == '\t' && strspn(line+1, HEXCHARS) == 4) {
unsigned u;
if (sscanf(line+1, "%04x", &u) == 1 && u == pid) {
char *t;
if (sscanf(line+1, "%04x", &u) == 1 && u == pid) {
char *t;
t = line+5;
t += strspn(t, WHITESPACE);
t = line+5;
t += strspn(t, WHITESPACE);
if (!(*product = strdup(t))) {
fprintf(stderr, "Out of memory.\n");
goto finish;
}
if (!(*product = strdup(t))) {
fprintf(stderr, "Out of memory.\n");
goto finish;
}
break;
}
}
}
break;
}
}
}
ret = 0;
ret = 0;
finish:
free(line);
fclose(f);
free(line);
fclose(f);
if (ret < 0) {
free(*product);
free(*vendor);
if (ret < 0) {
free(*product);
free(*vendor);
*product = *vendor = NULL;
}
*product = *vendor = NULL;
}
return ret;
return ret;
}
static struct udev_device *find_device(struct udev_device *dev, const char *subsys, const char *devtype)
{
const char *str;
const char *str;
str = udev_device_get_subsystem(dev);
if (str == NULL)
goto try_parent;
if (strcmp(str, subsys) != 0)
goto try_parent;
str = udev_device_get_subsystem(dev);
if (str == NULL)
goto try_parent;
if (strcmp(str, subsys) != 0)
goto try_parent;
if (devtype != NULL) {
str = udev_device_get_devtype(dev);
if (str == NULL)
goto try_parent;
if (strcmp(str, devtype) != 0)
goto try_parent;
}
return dev;
if (devtype != NULL) {
str = udev_device_get_devtype(dev);
if (str == NULL)
goto try_parent;
if (strcmp(str, devtype) != 0)
goto try_parent;
}
return dev;
try_parent:
return udev_device_get_parent_with_subsystem_devtype(dev, subsys, devtype);
return udev_device_get_parent_with_subsystem_devtype(dev, subsys, devtype);
}
static int builtin_db(struct udev_device *dev, bool test,
const char *database,
const char *vendor_attr, const char *product_attr,
const char *subsys, const char *devtype)
const char *database,
const char *vendor_attr, const char *product_attr,
const char *subsys, const char *devtype)
{
struct udev_device *parent;
uint16_t vid = 0, pid = 0;
char *vendor = NULL, *product = NULL;
struct udev_device *parent;
uint16_t vid = 0, pid = 0;
char *vendor = NULL, *product = NULL;
parent = find_device(dev, subsys, devtype);
if (!parent) {
fprintf(stderr, "Failed to find device.\n");
goto finish;
}
parent = find_device(dev, subsys, devtype);
if (!parent) {
fprintf(stderr, "Failed to find device.\n");
goto finish;
}
if (get_vid_pid(parent, vendor_attr, product_attr, &vid, &pid) < 0)
goto finish;
if (get_vid_pid(parent, vendor_attr, product_attr, &vid, &pid) < 0)
goto finish;
if (lookup_vid_pid(database, vid, pid, &vendor, &product) < 0)
goto finish;
if (lookup_vid_pid(database, vid, pid, &vendor, &product) < 0)
goto finish;
if (vendor)
udev_builtin_add_property(dev, test, "ID_VENDOR_FROM_DATABASE", vendor);
if (product)
udev_builtin_add_property(dev, test, "ID_MODEL_FROM_DATABASE", product);
if (vendor)
udev_builtin_add_property(dev, test, "ID_VENDOR_FROM_DATABASE", vendor);
if (product)
udev_builtin_add_property(dev, test, "ID_MODEL_FROM_DATABASE", product);
finish:
free(vendor);
free(product);
return 0;
free(vendor);
free(product);
return 0;
}
static int builtin_usb_db(struct udev_device *dev, int argc, char *argv[], bool test)
{
return builtin_db(dev, test, USB_DATABASE, "idVendor", "idProduct", "usb", "usb_device");
return builtin_db(dev, test, USB_DATABASE, "idVendor", "idProduct", "usb", "usb_device");
}
static int builtin_pci_db(struct udev_device *dev, int argc, char *argv[], bool test)
{
return builtin_db(dev, test, PCI_DATABASE, "vendor", "device", "pci", NULL);
return builtin_db(dev, test, PCI_DATABASE, "vendor", "device", "pci", NULL);
}
const struct udev_builtin udev_builtin_usb_db = {
.name = "usb-db",
.cmd = builtin_usb_db,
.help = "USB vendor/product database",
.run_once = true,
.name = "usb-db",
.cmd = builtin_usb_db,
.help = "USB vendor/product database",
.run_once = true,
};
const struct udev_builtin udev_builtin_pci_db = {
.name = "pci-db",
.cmd = builtin_pci_db,
.help = "PCI vendor/product database",
.run_once = true,
.name = "pci-db",
.cmd = builtin_pci_db,
.help = "PCI vendor/product database",
.run_once = true,
};
+138 -138
View File
@@ -45,174 +45,174 @@
* @param bitmask: Output array which has a sizeof of bitmask_size
*/
static void get_cap_mask(struct udev_device *dev,
struct udev_device *pdev, const char* attr,
unsigned long *bitmask, size_t bitmask_size,
bool test)
struct udev_device *pdev, const char* attr,
unsigned long *bitmask, size_t bitmask_size,
bool test)
{
struct udev *udev = udev_device_get_udev(dev);
char text[4096];
unsigned i;
char* word;
unsigned long val;
struct udev *udev = udev_device_get_udev(dev);
char text[4096];
unsigned i;
char* word;
unsigned long val;
snprintf(text, sizeof(text), "%s", udev_device_get_sysattr_value(pdev, attr));
info(udev, "%s raw kernel attribute: %s\n", attr, text);
snprintf(text, sizeof(text), "%s", udev_device_get_sysattr_value(pdev, attr));
info(udev, "%s raw kernel attribute: %s\n", attr, text);
memset (bitmask, 0, bitmask_size);
i = 0;
while ((word = strrchr(text, ' ')) != NULL) {
val = strtoul (word+1, NULL, 16);
if (i < bitmask_size/sizeof(unsigned long))
bitmask[i] = val;
else
info(udev, "ignoring %s block %lX which is larger than maximum size\n", attr, val);
*word = '\0';
++i;
}
val = strtoul (text, NULL, 16);
if (i < bitmask_size / sizeof(unsigned long))
bitmask[i] = val;
else
info(udev, "ignoring %s block %lX which is larger than maximum size\n", attr, val);
memset (bitmask, 0, bitmask_size);
i = 0;
while ((word = strrchr(text, ' ')) != NULL) {
val = strtoul (word+1, NULL, 16);
if (i < bitmask_size/sizeof(unsigned long))
bitmask[i] = val;
else
info(udev, "ignoring %s block %lX which is larger than maximum size\n", attr, val);
*word = '\0';
++i;
}
val = strtoul (text, NULL, 16);
if (i < bitmask_size / sizeof(unsigned long))
bitmask[i] = val;
else
info(udev, "ignoring %s block %lX which is larger than maximum size\n", attr, val);
if (test) {
/* printf pattern with the right unsigned long number of hex chars */
snprintf(text, sizeof(text), " bit %%4u: %%0%zilX\n", 2 * sizeof(unsigned long));
info(udev, "%s decoded bit map:\n", attr);
val = bitmask_size / sizeof (unsigned long);
/* skip over leading zeros */
while (bitmask[val-1] == 0 && val > 0)
--val;
for (i = 0; i < val; ++i)
info(udev, text, i * BITS_PER_LONG, bitmask[i]);
}
if (test) {
/* printf pattern with the right unsigned long number of hex chars */
snprintf(text, sizeof(text), " bit %%4u: %%0%zilX\n", 2 * sizeof(unsigned long));
info(udev, "%s decoded bit map:\n", attr);
val = bitmask_size / sizeof (unsigned long);
/* skip over leading zeros */
while (bitmask[val-1] == 0 && val > 0)
--val;
for (i = 0; i < val; ++i)
info(udev, text, i * BITS_PER_LONG, bitmask[i]);
}
}
/* pointer devices */
static void test_pointers (struct udev_device *dev,
const unsigned long* bitmask_ev,
const unsigned long* bitmask_abs,
const unsigned long* bitmask_key,
const unsigned long* bitmask_rel,
bool test)
const unsigned long* bitmask_ev,
const unsigned long* bitmask_abs,
const unsigned long* bitmask_key,
const unsigned long* bitmask_rel,
bool test)
{
int is_mouse = 0;
int is_touchpad = 0;
int is_mouse = 0;
int is_touchpad = 0;
if (!test_bit (EV_KEY, bitmask_ev)) {
if (test_bit (EV_ABS, bitmask_ev) &&
test_bit (ABS_X, bitmask_abs) &&
test_bit (ABS_Y, bitmask_abs) &&
test_bit (ABS_Z, bitmask_abs))
udev_builtin_add_property(dev, test, "ID_INPUT_ACCELEROMETER", "1");
return;
}
if (!test_bit (EV_KEY, bitmask_ev)) {
if (test_bit (EV_ABS, bitmask_ev) &&
test_bit (ABS_X, bitmask_abs) &&
test_bit (ABS_Y, bitmask_abs) &&
test_bit (ABS_Z, bitmask_abs))
udev_builtin_add_property(dev, test, "ID_INPUT_ACCELEROMETER", "1");
return;
}
if (test_bit (EV_ABS, bitmask_ev) &&
test_bit (ABS_X, bitmask_abs) && test_bit (ABS_Y, bitmask_abs)) {
if (test_bit (BTN_STYLUS, bitmask_key) || test_bit (BTN_TOOL_PEN, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_TABLET", "1");
else if (test_bit (BTN_TOOL_FINGER, bitmask_key) && !test_bit (BTN_TOOL_PEN, bitmask_key))
is_touchpad = 1;
else if (test_bit (BTN_TRIGGER, bitmask_key) ||
test_bit (BTN_A, bitmask_key) ||
test_bit (BTN_1, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_JOYSTICK", "1");
else if (test_bit (BTN_MOUSE, bitmask_key))
/* This path is taken by VMware's USB mouse, which has
* absolute axes, but no touch/pressure button. */
is_mouse = 1;
else if (test_bit (BTN_TOUCH, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHSCREEN", "1");
}
if (test_bit (EV_ABS, bitmask_ev) &&
test_bit (ABS_X, bitmask_abs) && test_bit (ABS_Y, bitmask_abs)) {
if (test_bit (BTN_STYLUS, bitmask_key) || test_bit (BTN_TOOL_PEN, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_TABLET", "1");
else if (test_bit (BTN_TOOL_FINGER, bitmask_key) && !test_bit (BTN_TOOL_PEN, bitmask_key))
is_touchpad = 1;
else if (test_bit (BTN_TRIGGER, bitmask_key) ||
test_bit (BTN_A, bitmask_key) ||
test_bit (BTN_1, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_JOYSTICK", "1");
else if (test_bit (BTN_MOUSE, bitmask_key))
/* This path is taken by VMware's USB mouse, which has
* absolute axes, but no touch/pressure button. */
is_mouse = 1;
else if (test_bit (BTN_TOUCH, bitmask_key))
udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHSCREEN", "1");
}
if (test_bit (EV_REL, bitmask_ev) &&
test_bit (REL_X, bitmask_rel) && test_bit (REL_Y, bitmask_rel) &&
test_bit (BTN_MOUSE, bitmask_key))
is_mouse = 1;
if (test_bit (EV_REL, bitmask_ev) &&
test_bit (REL_X, bitmask_rel) && test_bit (REL_Y, bitmask_rel) &&
test_bit (BTN_MOUSE, bitmask_key))
is_mouse = 1;
if (is_mouse)
udev_builtin_add_property(dev, test, "ID_INPUT_MOUSE", "1");
if (is_touchpad)
udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHPAD", "1");
if (is_mouse)
udev_builtin_add_property(dev, test, "ID_INPUT_MOUSE", "1");
if (is_touchpad)
udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHPAD", "1");
}
/* key like devices */
static void test_key (struct udev_device *dev,
const unsigned long* bitmask_ev,
const unsigned long* bitmask_key,
bool test)
const unsigned long* bitmask_ev,
const unsigned long* bitmask_key,
bool test)
{
struct udev *udev = udev_device_get_udev(dev);
unsigned i;
unsigned long found;
unsigned long mask;
struct udev *udev = udev_device_get_udev(dev);
unsigned i;
unsigned long found;
unsigned long mask;
/* do we have any KEY_* capability? */
if (!test_bit (EV_KEY, bitmask_ev)) {
info(udev, "test_key: no EV_KEY capability\n");
return;
}
/* do we have any KEY_* capability? */
if (!test_bit (EV_KEY, bitmask_ev)) {
info(udev, "test_key: no EV_KEY capability\n");
return;
}
/* only consider KEY_* here, not BTN_* */
found = 0;
for (i = 0; i < BTN_MISC/BITS_PER_LONG; ++i) {
found |= bitmask_key[i];
info(udev, "test_key: checking bit block %lu for any keys; found=%i\n", i*BITS_PER_LONG, found > 0);
}
/* If there are no keys in the lower block, check the higher block */
if (!found) {
for (i = KEY_OK; i < BTN_TRIGGER_HAPPY; ++i) {
if (test_bit (i, bitmask_key)) {
info(udev, "test_key: Found key %x in high block\n", i);
found = 1;
break;
}
}
}
/* only consider KEY_* here, not BTN_* */
found = 0;
for (i = 0; i < BTN_MISC/BITS_PER_LONG; ++i) {
found |= bitmask_key[i];
info(udev, "test_key: checking bit block %lu for any keys; found=%i\n", i*BITS_PER_LONG, found > 0);
}
/* If there are no keys in the lower block, check the higher block */
if (!found) {
for (i = KEY_OK; i < BTN_TRIGGER_HAPPY; ++i) {
if (test_bit (i, bitmask_key)) {
info(udev, "test_key: Found key %x in high block\n", i);
found = 1;
break;
}
}
}
if (found > 0)
udev_builtin_add_property(dev, test, "ID_INPUT_KEY", "1");
if (found > 0)
udev_builtin_add_property(dev, test, "ID_INPUT_KEY", "1");
/* the first 32 bits are ESC, numbers, and Q to D; if we have all of
* those, consider it a full keyboard; do not test KEY_RESERVED, though */
mask = 0xFFFFFFFE;
if ((bitmask_key[0] & mask) == mask)
udev_builtin_add_property(dev, test, "ID_INPUT_KEYBOARD", "1");
/* the first 32 bits are ESC, numbers, and Q to D; if we have all of
* those, consider it a full keyboard; do not test KEY_RESERVED, though */
mask = 0xFFFFFFFE;
if ((bitmask_key[0] & mask) == mask)
udev_builtin_add_property(dev, test, "ID_INPUT_KEYBOARD", "1");
}
static int builtin_input_id(struct udev_device *dev, int argc, char *argv[], bool test)
{
struct udev_device *pdev;
unsigned long bitmask_ev[NBITS(EV_MAX)];
unsigned long bitmask_abs[NBITS(ABS_MAX)];
unsigned long bitmask_key[NBITS(KEY_MAX)];
unsigned long bitmask_rel[NBITS(REL_MAX)];
struct udev_device *pdev;
unsigned long bitmask_ev[NBITS(EV_MAX)];
unsigned long bitmask_abs[NBITS(ABS_MAX)];
unsigned long bitmask_key[NBITS(KEY_MAX)];
unsigned long bitmask_rel[NBITS(REL_MAX)];
/* walk up the parental chain until we find the real input device; the
* argument is very likely a subdevice of this, like eventN */
pdev = dev;
while (pdev != NULL && udev_device_get_sysattr_value(pdev, "capabilities/ev") == NULL)
pdev = udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL);
/* walk up the parental chain until we find the real input device; the
* argument is very likely a subdevice of this, like eventN */
pdev = dev;
while (pdev != NULL && udev_device_get_sysattr_value(pdev, "capabilities/ev") == NULL)
pdev = udev_device_get_parent_with_subsystem_devtype(pdev, "input", NULL);
/* not an "input" class device */
if (pdev == NULL)
return EXIT_SUCCESS;
/* not an "input" class device */
if (pdev == NULL)
return EXIT_SUCCESS;
/* Use this as a flag that input devices were detected, so that this
* program doesn't need to be called more than once per device */
udev_builtin_add_property(dev, test, "ID_INPUT", "1");
get_cap_mask(dev, pdev, "capabilities/ev", bitmask_ev, sizeof(bitmask_ev), test);
get_cap_mask(dev, pdev, "capabilities/abs", bitmask_abs, sizeof(bitmask_abs), test);
get_cap_mask(dev, pdev, "capabilities/rel", bitmask_rel, sizeof(bitmask_rel), test);
get_cap_mask(dev, pdev, "capabilities/key", bitmask_key, sizeof(bitmask_key), test);
test_pointers(dev, bitmask_ev, bitmask_abs, bitmask_key, bitmask_rel, test);
test_key(dev, bitmask_ev, bitmask_key, test);
return EXIT_SUCCESS;
/* Use this as a flag that input devices were detected, so that this
* program doesn't need to be called more than once per device */
udev_builtin_add_property(dev, test, "ID_INPUT", "1");
get_cap_mask(dev, pdev, "capabilities/ev", bitmask_ev, sizeof(bitmask_ev), test);
get_cap_mask(dev, pdev, "capabilities/abs", bitmask_abs, sizeof(bitmask_abs), test);
get_cap_mask(dev, pdev, "capabilities/rel", bitmask_rel, sizeof(bitmask_rel), test);
get_cap_mask(dev, pdev, "capabilities/key", bitmask_key, sizeof(bitmask_key), test);
test_pointers(dev, bitmask_ev, bitmask_abs, bitmask_key, bitmask_rel, test);
test_key(dev, bitmask_ev, bitmask_key, test);
return EXIT_SUCCESS;
}
const struct udev_builtin udev_builtin_input_id = {
.name = "input_id",
.cmd = builtin_input_id,
.help = "input device properties",
.name = "input_id",
.cmd = builtin_input_id,
.help = "input device properties",
};
+69 -69
View File
@@ -35,114 +35,114 @@ static struct kmod_ctx *ctx;
static int load_module(struct udev *udev, const char *alias)
{
struct kmod_list *list = NULL;
struct kmod_list *listb = NULL;
struct kmod_list *l;
int err;
struct kmod_list *list = NULL;
struct kmod_list *listb = NULL;
struct kmod_list *l;
int err;
err = kmod_module_new_from_lookup(ctx, alias, &list);
if (err < 0)
return err;
err = kmod_module_new_from_lookup(ctx, alias, &list);
if (err < 0)
return err;
err = kmod_module_get_filtered_blacklist(ctx, list, &listb);
if (err < 0)
return err;
err = kmod_module_get_filtered_blacklist(ctx, list, &listb);
if (err < 0)
return err;
if (list == NULL)
info(udev, "no module matches '%s'\n", alias);
else if (listb == NULL)
info(udev, "modules matching '%s' are blacklisted\n", alias);
if (list == NULL)
info(udev, "no module matches '%s'\n", alias);
else if (listb == NULL)
info(udev, "modules matching '%s' are blacklisted\n", alias);
kmod_list_foreach(l, listb) {
struct kmod_module *mod = kmod_module_get_module(l);
kmod_list_foreach(l, listb) {
struct kmod_module *mod = kmod_module_get_module(l);
err = kmod_module_probe_insert_module(mod, 0, NULL, NULL, NULL);
if (err >=0 )
info(udev, "inserted '%s'\n", kmod_module_get_name(mod));
else
info(udev, "failed to insert '%s'\n", kmod_module_get_name(mod));
err = kmod_module_probe_insert_module(mod, 0, NULL, NULL, NULL);
if (err >=0 )
info(udev, "inserted '%s'\n", kmod_module_get_name(mod));
else
info(udev, "failed to insert '%s'\n", kmod_module_get_name(mod));
kmod_module_unref(mod);
}
kmod_module_unref(mod);
}
kmod_module_unref_list(list);
kmod_module_unref_list(listb);
return err;
kmod_module_unref_list(list);
kmod_module_unref_list(listb);
return err;
}
static void udev_kmod_log(void *data, int priority, const char *file, int line,
const char *fn, const char *format, va_list args)
const char *fn, const char *format, va_list args)
{
udev_main_log(data, priority, file, line, fn, format, args);
udev_main_log(data, priority, file, line, fn, format, args);
}
/* needs to re-instantiate the context after a reload */
static int builtin_kmod(struct udev_device *dev, int argc, char *argv[], bool test)
{
struct udev *udev = udev_device_get_udev(dev);
int i;
struct udev *udev = udev_device_get_udev(dev);
int i;
if (!ctx) {
ctx = kmod_new(NULL, NULL);
if (!ctx)
return -ENOMEM;
if (!ctx) {
ctx = kmod_new(NULL, NULL);
if (!ctx)
return -ENOMEM;
info(udev, "load module index\n");
kmod_set_log_fn(ctx, udev_kmod_log, udev);
kmod_load_resources(ctx);
}
info(udev, "load module index\n");
kmod_set_log_fn(ctx, udev_kmod_log, udev);
kmod_load_resources(ctx);
}
if (argc < 3 || strcmp(argv[1], "load")) {
err(udev, "expect: %s load <module>\n", argv[0]);
return EXIT_FAILURE;
}
if (argc < 3 || strcmp(argv[1], "load")) {
err(udev, "expect: %s load <module>\n", argv[0]);
return EXIT_FAILURE;
}
for (i = 2; argv[i]; i++) {
info(udev, "execute '%s' '%s'\n", argv[1], argv[i]);
load_module(udev, argv[i]);
}
for (i = 2; argv[i]; i++) {
info(udev, "execute '%s' '%s'\n", argv[1], argv[i]);
load_module(udev, argv[i]);
}
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}
/* called at udev startup */
static int builtin_kmod_init(struct udev *udev)
{
if (ctx)
return 0;
if (ctx)
return 0;
ctx = kmod_new(NULL, NULL);
if (!ctx)
return -ENOMEM;
ctx = kmod_new(NULL, NULL);
if (!ctx)
return -ENOMEM;
info(udev, "load module index\n");
kmod_set_log_fn(ctx, udev_kmod_log, udev);
kmod_load_resources(ctx);
return 0;
info(udev, "load module index\n");
kmod_set_log_fn(ctx, udev_kmod_log, udev);
kmod_load_resources(ctx);
return 0;
}
/* called on udev shutdown and reload request */
static void builtin_kmod_exit(struct udev *udev)
{
info(udev, "unload module index\n");
ctx = kmod_unref(ctx);
info(udev, "unload module index\n");
ctx = kmod_unref(ctx);
}
/* called every couple of seconds during event activity; 'true' if config has changed */
static bool builtin_kmod_validate(struct udev *udev)
{
info(udev, "validate module index\n");
if (kmod_validate_resources(ctx) != KMOD_RESOURCES_OK)
return true;
return false;
info(udev, "validate module index\n");
if (kmod_validate_resources(ctx) != KMOD_RESOURCES_OK)
return true;
return false;
}
const struct udev_builtin udev_builtin_kmod = {
.name = "kmod",
.cmd = builtin_kmod,
.init = builtin_kmod_init,
.exit = builtin_kmod_exit,
.validate = builtin_kmod_validate,
.help = "kernel module loader",
.run_once = false,
.name = "kmod",
.cmd = builtin_kmod,
.init = builtin_kmod_init,
.exit = builtin_kmod_exit,
.validate = builtin_kmod_validate,
.help = "kernel module loader",
.run_once = false,
};
+340 -340
View File
@@ -34,30 +34,30 @@
static int path_prepend(char **path, const char *fmt, ...)
{
va_list va;
char *pre;
int err = 0;
va_list va;
char *pre;
int err = 0;
va_start(va, fmt);
err = vasprintf(&pre, fmt, va);
va_end(va);
if (err < 0)
goto out;
va_start(va, fmt);
err = vasprintf(&pre, fmt, va);
va_end(va);
if (err < 0)
goto out;
if (*path != NULL) {
char *new;
if (*path != NULL) {
char *new;
err = asprintf(&new, "%s-%s", pre, *path);
free(pre);
if (err < 0)
goto out;
free(*path);
*path = new;
} else {
*path = pre;
}
err = asprintf(&new, "%s-%s", pre, *path);
free(pre);
if (err < 0)
goto out;
free(*path);
*path = new;
} else {
*path = pre;
}
out:
return err;
return err;
}
/*
@@ -66,422 +66,422 @@ out:
*/
static int format_lun_number(struct udev_device *dev, char **path)
{
unsigned long lun = strtoul(udev_device_get_sysnum(dev), NULL, 10);
unsigned long lun = strtoul(udev_device_get_sysnum(dev), NULL, 10);
/* address method 0, peripheral device addressing with bus id of zero */
if (lun < 256)
return path_prepend(path, "lun-%d", lun);
/* handle all other lun addressing methods by using a variant of the original lun format */
return path_prepend(path, "lun-0x%04x%04x00000000", (lun & 0xffff), (lun >> 16) & 0xffff);
/* address method 0, peripheral device addressing with bus id of zero */
if (lun < 256)
return path_prepend(path, "lun-%d", lun);
/* handle all other lun addressing methods by using a variant of the original lun format */
return path_prepend(path, "lun-0x%04x%04x00000000", (lun & 0xffff), (lun >> 16) & 0xffff);
}
static struct udev_device *skip_subsystem(struct udev_device *dev, const char *subsys)
{
struct udev_device *parent = dev;
struct udev_device *parent = dev;
while (parent != NULL) {
const char *subsystem;
while (parent != NULL) {
const char *subsystem;
subsystem = udev_device_get_subsystem(parent);
if (subsystem == NULL || strcmp(subsystem, subsys) != 0)
break;
dev = parent;
parent = udev_device_get_parent(parent);
}
return dev;
subsystem = udev_device_get_subsystem(parent);
if (subsystem == NULL || strcmp(subsystem, subsys) != 0)
break;
dev = parent;
parent = udev_device_get_parent(parent);
}
return dev;
}
static struct udev_device *handle_scsi_fibre_channel(struct udev_device *parent, char **path)
{
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *targetdev;
struct udev_device *fcdev = NULL;
const char *port;
char *lun = NULL;;
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *targetdev;
struct udev_device *fcdev = NULL;
const char *port;
char *lun = NULL;;
targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
if (targetdev == NULL)
return NULL;
targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
if (targetdev == NULL)
return NULL;
fcdev = udev_device_new_from_subsystem_sysname(udev, "fc_transport", udev_device_get_sysname(targetdev));
if (fcdev == NULL)
return NULL;
port = udev_device_get_sysattr_value(fcdev, "port_name");
if (port == NULL) {
parent = NULL;
goto out;
}
fcdev = udev_device_new_from_subsystem_sysname(udev, "fc_transport", udev_device_get_sysname(targetdev));
if (fcdev == NULL)
return NULL;
port = udev_device_get_sysattr_value(fcdev, "port_name");
if (port == NULL) {
parent = NULL;
goto out;
}
format_lun_number(parent, &lun);
path_prepend(path, "fc-%s-%s", port, lun);
if (lun)
free(lun);
format_lun_number(parent, &lun);
path_prepend(path, "fc-%s-%s", port, lun);
if (lun)
free(lun);
out:
udev_device_unref(fcdev);
return parent;
udev_device_unref(fcdev);
return parent;
}
static struct udev_device *handle_scsi_sas(struct udev_device *parent, char **path)
{
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *targetdev;
struct udev_device *target_parent;
struct udev_device *sasdev;
const char *sas_address;
char *lun = NULL;
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *targetdev;
struct udev_device *target_parent;
struct udev_device *sasdev;
const char *sas_address;
char *lun = NULL;
targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
if (targetdev == NULL)
return NULL;
targetdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_target");
if (targetdev == NULL)
return NULL;
target_parent = udev_device_get_parent(targetdev);
if (target_parent == NULL)
return NULL;
target_parent = udev_device_get_parent(targetdev);
if (target_parent == NULL)
return NULL;
sasdev = udev_device_new_from_subsystem_sysname(udev, "sas_device",
udev_device_get_sysname(target_parent));
if (sasdev == NULL)
return NULL;
sasdev = udev_device_new_from_subsystem_sysname(udev, "sas_device",
udev_device_get_sysname(target_parent));
if (sasdev == NULL)
return NULL;
sas_address = udev_device_get_sysattr_value(sasdev, "sas_address");
if (sas_address == NULL) {
parent = NULL;
goto out;
}
sas_address = udev_device_get_sysattr_value(sasdev, "sas_address");
if (sas_address == NULL) {
parent = NULL;
goto out;
}
format_lun_number(parent, &lun);
path_prepend(path, "sas-%s-%s", sas_address, lun);
if (lun)
free(lun);
format_lun_number(parent, &lun);
path_prepend(path, "sas-%s-%s", sas_address, lun);
if (lun)
free(lun);
out:
udev_device_unref(sasdev);
return parent;
udev_device_unref(sasdev);
return parent;
}
static struct udev_device *handle_scsi_iscsi(struct udev_device *parent, char **path)
{
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *transportdev;
struct udev_device *sessiondev = NULL;
const char *target;
char *connname;
struct udev_device *conndev = NULL;
const char *addr;
const char *port;
char *lun = NULL;
struct udev *udev = udev_device_get_udev(parent);
struct udev_device *transportdev;
struct udev_device *sessiondev = NULL;
const char *target;
char *connname;
struct udev_device *conndev = NULL;
const char *addr;
const char *port;
char *lun = NULL;
/* find iscsi session */
transportdev = parent;
for (;;) {
transportdev = udev_device_get_parent(transportdev);
if (transportdev == NULL)
return NULL;
if (strncmp(udev_device_get_sysname(transportdev), "session", 7) == 0)
break;
}
/* find iscsi session */
transportdev = parent;
for (;;) {
transportdev = udev_device_get_parent(transportdev);
if (transportdev == NULL)
return NULL;
if (strncmp(udev_device_get_sysname(transportdev), "session", 7) == 0)
break;
}
/* find iscsi session device */
sessiondev = udev_device_new_from_subsystem_sysname(udev, "iscsi_session", udev_device_get_sysname(transportdev));
if (sessiondev == NULL)
return NULL;
target = udev_device_get_sysattr_value(sessiondev, "targetname");
if (target == NULL) {
parent = NULL;
goto out;
}
/* find iscsi session device */
sessiondev = udev_device_new_from_subsystem_sysname(udev, "iscsi_session", udev_device_get_sysname(transportdev));
if (sessiondev == NULL)
return NULL;
target = udev_device_get_sysattr_value(sessiondev, "targetname");
if (target == NULL) {
parent = NULL;
goto out;
}
if (asprintf(&connname, "connection%s:0", udev_device_get_sysnum(transportdev)) < 0) {
parent = NULL;
goto out;
}
conndev = udev_device_new_from_subsystem_sysname(udev, "iscsi_connection", connname);
free(connname);
if (conndev == NULL) {
parent = NULL;
goto out;
}
addr = udev_device_get_sysattr_value(conndev, "persistent_address");
port = udev_device_get_sysattr_value(conndev, "persistent_port");
if (addr == NULL || port == NULL) {
parent = NULL;
goto out;
}
if (asprintf(&connname, "connection%s:0", udev_device_get_sysnum(transportdev)) < 0) {
parent = NULL;
goto out;
}
conndev = udev_device_new_from_subsystem_sysname(udev, "iscsi_connection", connname);
free(connname);
if (conndev == NULL) {
parent = NULL;
goto out;
}
addr = udev_device_get_sysattr_value(conndev, "persistent_address");
port = udev_device_get_sysattr_value(conndev, "persistent_port");
if (addr == NULL || port == NULL) {
parent = NULL;
goto out;
}
format_lun_number(parent, &lun);
path_prepend(path, "ip-%s:%s-iscsi-%s-%s", addr, port, target, lun);
if (lun)
free(lun);
format_lun_number(parent, &lun);
path_prepend(path, "ip-%s:%s-iscsi-%s-%s", addr, port, target, lun);
if (lun)
free(lun);
out:
udev_device_unref(sessiondev);
udev_device_unref(conndev);
return parent;
udev_device_unref(sessiondev);
udev_device_unref(conndev);
return parent;
}
static struct udev_device *handle_scsi_default(struct udev_device *parent, char **path)
{
struct udev_device *hostdev;
int host, bus, target, lun;
const char *name;
char *base;
char *pos;
DIR *dir;
struct dirent *dent;
int basenum;
struct udev_device *hostdev;
int host, bus, target, lun;
const char *name;
char *base;
char *pos;
DIR *dir;
struct dirent *dent;
int basenum;
hostdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_host");
if (hostdev == NULL)
return NULL;
hostdev = udev_device_get_parent_with_subsystem_devtype(parent, "scsi", "scsi_host");
if (hostdev == NULL)
return NULL;
name = udev_device_get_sysname(parent);
if (sscanf(name, "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4)
return NULL;
name = udev_device_get_sysname(parent);
if (sscanf(name, "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4)
return NULL;
/* rebase host offset to get the local relative number */
basenum = -1;
base = strdup(udev_device_get_syspath(hostdev));
if (base == NULL)
return NULL;
pos = strrchr(base, '/');
if (pos == NULL) {
parent = NULL;
goto out;
}
pos[0] = '\0';
dir = opendir(base);
if (dir == NULL) {
parent = NULL;
goto out;
}
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
char *rest;
int i;
/* rebase host offset to get the local relative number */
basenum = -1;
base = strdup(udev_device_get_syspath(hostdev));
if (base == NULL)
return NULL;
pos = strrchr(base, '/');
if (pos == NULL) {
parent = NULL;
goto out;
}
pos[0] = '\0';
dir = opendir(base);
if (dir == NULL) {
parent = NULL;
goto out;
}
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
char *rest;
int i;
if (dent->d_name[0] == '.')
continue;
if (dent->d_type != DT_DIR && dent->d_type != DT_LNK)
continue;
if (strncmp(dent->d_name, "host", 4) != 0)
continue;
i = strtoul(&dent->d_name[4], &rest, 10);
if (rest[0] != '\0')
continue;
if (basenum == -1 || i < basenum)
basenum = i;
}
closedir(dir);
if (basenum == -1) {
parent = NULL;
goto out;
}
host -= basenum;
if (dent->d_name[0] == '.')
continue;
if (dent->d_type != DT_DIR && dent->d_type != DT_LNK)
continue;
if (strncmp(dent->d_name, "host", 4) != 0)
continue;
i = strtoul(&dent->d_name[4], &rest, 10);
if (rest[0] != '\0')
continue;
if (basenum == -1 || i < basenum)
basenum = i;
}
closedir(dir);
if (basenum == -1) {
parent = NULL;
goto out;
}
host -= basenum;
path_prepend(path, "scsi-%u:%u:%u:%u", host, bus, target, lun);
path_prepend(path, "scsi-%u:%u:%u:%u", host, bus, target, lun);
out:
free(base);
return hostdev;
free(base);
return hostdev;
}
static struct udev_device *handle_scsi(struct udev_device *parent, char **path)
{
const char *devtype;
const char *name;
const char *id;
const char *devtype;
const char *name;
const char *id;
devtype = udev_device_get_devtype(parent);
if (devtype == NULL || strcmp(devtype, "scsi_device") != 0)
return parent;
devtype = udev_device_get_devtype(parent);
if (devtype == NULL || strcmp(devtype, "scsi_device") != 0)
return parent;
/* firewire */
id = udev_device_get_sysattr_value(parent, "ieee1394_id");
if (id != NULL) {
parent = skip_subsystem(parent, "scsi");
path_prepend(path, "ieee1394-0x%s", id);
goto out;
}
/* firewire */
id = udev_device_get_sysattr_value(parent, "ieee1394_id");
if (id != NULL) {
parent = skip_subsystem(parent, "scsi");
path_prepend(path, "ieee1394-0x%s", id);
goto out;
}
/* lousy scsi sysfs does not have a "subsystem" for the transport */
name = udev_device_get_syspath(parent);
/* lousy scsi sysfs does not have a "subsystem" for the transport */
name = udev_device_get_syspath(parent);
if (strstr(name, "/rport-") != NULL) {
parent = handle_scsi_fibre_channel(parent, path);
goto out;
}
if (strstr(name, "/rport-") != NULL) {
parent = handle_scsi_fibre_channel(parent, path);
goto out;
}
if (strstr(name, "/end_device-") != NULL) {
parent = handle_scsi_sas(parent, path);
goto out;
}
if (strstr(name, "/end_device-") != NULL) {
parent = handle_scsi_sas(parent, path);
goto out;
}
if (strstr(name, "/session") != NULL) {
parent = handle_scsi_iscsi(parent, path);
goto out;
}
if (strstr(name, "/session") != NULL) {
parent = handle_scsi_iscsi(parent, path);
goto out;
}
parent = handle_scsi_default(parent, path);
parent = handle_scsi_default(parent, path);
out:
return parent;
return parent;
}
static void handle_scsi_tape(struct udev_device *dev, char **path)
{
const char *name;
const char *name;
/* must be the last device in the syspath */
if (*path != NULL)
return;
/* must be the last device in the syspath */
if (*path != NULL)
return;
name = udev_device_get_sysname(dev);
if (strncmp(name, "nst", 3) == 0 && strchr("lma", name[3]) != NULL)
path_prepend(path, "nst%c", name[3]);
else if (strncmp(name, "st", 2) == 0 && strchr("lma", name[2]) != NULL)
path_prepend(path, "st%c", name[2]);
name = udev_device_get_sysname(dev);
if (strncmp(name, "nst", 3) == 0 && strchr("lma", name[3]) != NULL)
path_prepend(path, "nst%c", name[3]);
else if (strncmp(name, "st", 2) == 0 && strchr("lma", name[2]) != NULL)
path_prepend(path, "st%c", name[2]);
}
static struct udev_device *handle_usb(struct udev_device *parent, char **path)
{
const char *devtype;
const char *str;
const char *port;
const char *devtype;
const char *str;
const char *port;
devtype = udev_device_get_devtype(parent);
if (devtype == NULL)
return parent;
if (strcmp(devtype, "usb_interface") != 0 && strcmp(devtype, "usb_device") != 0)
return parent;
devtype = udev_device_get_devtype(parent);
if (devtype == NULL)
return parent;
if (strcmp(devtype, "usb_interface") != 0 && strcmp(devtype, "usb_device") != 0)
return parent;
str = udev_device_get_sysname(parent);
port = strchr(str, '-');
if (port == NULL)
return parent;
port++;
str = udev_device_get_sysname(parent);
port = strchr(str, '-');
if (port == NULL)
return parent;
port++;
parent = skip_subsystem(parent, "usb");
path_prepend(path, "usb-0:%s", port);
return parent;
parent = skip_subsystem(parent, "usb");
path_prepend(path, "usb-0:%s", port);
return parent;
}
static struct udev_device *handle_cciss(struct udev_device *parent, char **path)
{
return NULL;
return NULL;
}
static struct udev_device *handle_ccw(struct udev_device *parent, struct udev_device *dev, char **path)
{
struct udev_device *scsi_dev;
struct udev_device *scsi_dev;
scsi_dev = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
if (scsi_dev != NULL) {
const char *wwpn;
const char *lun;
const char *hba_id;
scsi_dev = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
if (scsi_dev != NULL) {
const char *wwpn;
const char *lun;
const char *hba_id;
hba_id = udev_device_get_sysattr_value(scsi_dev, "hba_id");
wwpn = udev_device_get_sysattr_value(scsi_dev, "wwpn");
lun = udev_device_get_sysattr_value(scsi_dev, "fcp_lun");
if (hba_id != NULL && lun != NULL && wwpn != NULL) {
path_prepend(path, "ccw-%s-zfcp-%s:%s", hba_id, wwpn, lun);
goto out;
}
}
hba_id = udev_device_get_sysattr_value(scsi_dev, "hba_id");
wwpn = udev_device_get_sysattr_value(scsi_dev, "wwpn");
lun = udev_device_get_sysattr_value(scsi_dev, "fcp_lun");
if (hba_id != NULL && lun != NULL && wwpn != NULL) {
path_prepend(path, "ccw-%s-zfcp-%s:%s", hba_id, wwpn, lun);
goto out;
}
}
path_prepend(path, "ccw-%s", udev_device_get_sysname(parent));
path_prepend(path, "ccw-%s", udev_device_get_sysname(parent));
out:
parent = skip_subsystem(parent, "ccw");
return parent;
parent = skip_subsystem(parent, "ccw");
return parent;
}
static int builtin_path_id(struct udev_device *dev, int argc, char *argv[], bool test)
{
struct udev_device *parent;
char *path = NULL;
struct udev_device *parent;
char *path = NULL;
/* S390 ccw bus */
parent = udev_device_get_parent_with_subsystem_devtype(dev, "ccw", NULL);
if (parent != NULL) {
handle_ccw(parent, dev, &path);
goto out;
}
/* S390 ccw bus */
parent = udev_device_get_parent_with_subsystem_devtype(dev, "ccw", NULL);
if (parent != NULL) {
handle_ccw(parent, dev, &path);
goto out;
}
/* walk up the chain of devices and compose path */
parent = dev;
while (parent != NULL) {
const char *subsys;
/* walk up the chain of devices and compose path */
parent = dev;
while (parent != NULL) {
const char *subsys;
subsys = udev_device_get_subsystem(parent);
if (subsys == NULL) {
;
} else if (strcmp(subsys, "scsi_tape") == 0) {
handle_scsi_tape(parent, &path);
} else if (strcmp(subsys, "scsi") == 0) {
parent = handle_scsi(parent, &path);
} else if (strcmp(subsys, "cciss") == 0) {
handle_cciss(parent, &path);
} else if (strcmp(subsys, "usb") == 0) {
parent = handle_usb(parent, &path);
} else if (strcmp(subsys, "serio") == 0) {
path_prepend(&path, "serio-%s", udev_device_get_sysnum(parent));
parent = skip_subsystem(parent, "serio");
} else if (strcmp(subsys, "pci") == 0) {
path_prepend(&path, "pci-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "pci");
} else if (strcmp(subsys, "platform") == 0) {
path_prepend(&path, "platform-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "platform");
} else if (strcmp(subsys, "acpi") == 0) {
path_prepend(&path, "acpi-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "acpi");
} else if (strcmp(subsys, "xen") == 0) {
path_prepend(&path, "xen-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "xen");
} else if (strcmp(subsys, "virtio") == 0) {
path_prepend(&path, "virtio-pci-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "virtio");
}
subsys = udev_device_get_subsystem(parent);
if (subsys == NULL) {
;
} else if (strcmp(subsys, "scsi_tape") == 0) {
handle_scsi_tape(parent, &path);
} else if (strcmp(subsys, "scsi") == 0) {
parent = handle_scsi(parent, &path);
} else if (strcmp(subsys, "cciss") == 0) {
handle_cciss(parent, &path);
} else if (strcmp(subsys, "usb") == 0) {
parent = handle_usb(parent, &path);
} else if (strcmp(subsys, "serio") == 0) {
path_prepend(&path, "serio-%s", udev_device_get_sysnum(parent));
parent = skip_subsystem(parent, "serio");
} else if (strcmp(subsys, "pci") == 0) {
path_prepend(&path, "pci-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "pci");
} else if (strcmp(subsys, "platform") == 0) {
path_prepend(&path, "platform-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "platform");
} else if (strcmp(subsys, "acpi") == 0) {
path_prepend(&path, "acpi-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "acpi");
} else if (strcmp(subsys, "xen") == 0) {
path_prepend(&path, "xen-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "xen");
} else if (strcmp(subsys, "virtio") == 0) {
path_prepend(&path, "virtio-pci-%s", udev_device_get_sysname(parent));
parent = skip_subsystem(parent, "virtio");
}
parent = udev_device_get_parent(parent);
}
parent = udev_device_get_parent(parent);
}
out:
if (path != NULL) {
char tag[UTIL_NAME_SIZE];
size_t i;
const char *p;
if (path != NULL) {
char tag[UTIL_NAME_SIZE];
size_t i;
const char *p;
/* compose valid udev tag name */
for (p = path, i = 0; *p; p++) {
if ((*p >= '0' && *p <= '9') ||
(*p >= 'A' && *p <= 'Z') ||
(*p >= 'a' && *p <= 'z') ||
*p == '-') {
tag[i++] = *p;
continue;
}
/* compose valid udev tag name */
for (p = path, i = 0; *p; p++) {
if ((*p >= '0' && *p <= '9') ||
(*p >= 'A' && *p <= 'Z') ||
(*p >= 'a' && *p <= 'z') ||
*p == '-') {
tag[i++] = *p;
continue;
}
/* skip all leading '_' */
if (i == 0)
continue;
/* skip all leading '_' */
if (i == 0)
continue;
/* avoid second '_' */
if (tag[i-1] == '_')
continue;
/* avoid second '_' */
if (tag[i-1] == '_')
continue;
tag[i++] = '_';
}
/* strip trailing '_' */
while (i > 0 && tag[i-1] == '_')
i--;
tag[i] = '\0';
tag[i++] = '_';
}
/* strip trailing '_' */
while (i > 0 && tag[i-1] == '_')
i--;
tag[i] = '\0';
udev_builtin_add_property(dev, test, "ID_PATH", path);
udev_builtin_add_property(dev, test, "ID_PATH_TAG", tag);
free(path);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
udev_builtin_add_property(dev, test, "ID_PATH", path);
udev_builtin_add_property(dev, test, "ID_PATH_TAG", tag);
free(path);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
const struct udev_builtin udev_builtin_path_id = {
.name = "path_id",
.cmd = builtin_path_id,
.help = "compose persistent device path",
.run_once = true,
.name = "path_id",
.cmd = builtin_path_id,
.help = "compose persistent device path",
.run_once = true,
};
+367 -367
View File
@@ -33,193 +33,193 @@
static void set_usb_iftype(char *to, int if_class_num, size_t len)
{
char *type = "generic";
char *type = "generic";
switch (if_class_num) {
case 1:
type = "audio";
break;
case 2: /* CDC-Control */
break;
case 3:
type = "hid";
break;
case 5: /* Physical */
break;
case 6:
type = "media";
break;
case 7:
type = "printer";
break;
case 8:
type = "storage";
break;
case 9:
type = "hub";
break;
case 0x0a: /* CDC-Data */
break;
case 0x0b: /* Chip/Smart Card */
break;
case 0x0d: /* Content Security */
break;
case 0x0e:
type = "video";
break;
case 0xdc: /* Diagnostic Device */
break;
case 0xe0: /* Wireless Controller */
break;
case 0xfe: /* Application-specific */
break;
case 0xff: /* Vendor-specific */
break;
default:
break;
}
strncpy(to, type, len);
to[len-1] = '\0';
switch (if_class_num) {
case 1:
type = "audio";
break;
case 2: /* CDC-Control */
break;
case 3:
type = "hid";
break;
case 5: /* Physical */
break;
case 6:
type = "media";
break;
case 7:
type = "printer";
break;
case 8:
type = "storage";
break;
case 9:
type = "hub";
break;
case 0x0a: /* CDC-Data */
break;
case 0x0b: /* Chip/Smart Card */
break;
case 0x0d: /* Content Security */
break;
case 0x0e:
type = "video";
break;
case 0xdc: /* Diagnostic Device */
break;
case 0xe0: /* Wireless Controller */
break;
case 0xfe: /* Application-specific */
break;
case 0xff: /* Vendor-specific */
break;
default:
break;
}
strncpy(to, type, len);
to[len-1] = '\0';
}
static int set_usb_mass_storage_ifsubtype(char *to, const char *from, size_t len)
{
int type_num = 0;
char *eptr;
char *type = "generic";
int type_num = 0;
char *eptr;
char *type = "generic";
type_num = strtoul(from, &eptr, 0);
if (eptr != from) {
switch (type_num) {
case 2:
type = "atapi";
break;
case 3:
type = "tape";
break;
case 4: /* UFI */
case 5: /* SFF-8070i */
type = "floppy";
break;
case 1: /* RBC devices */
type = "rbc";
break;
case 6: /* Transparent SPC-2 devices */
type = "scsi";
break;
default:
break;
}
}
util_strscpy(to, len, type);
return type_num;
type_num = strtoul(from, &eptr, 0);
if (eptr != from) {
switch (type_num) {
case 2:
type = "atapi";
break;
case 3:
type = "tape";
break;
case 4: /* UFI */
case 5: /* SFF-8070i */
type = "floppy";
break;
case 1: /* RBC devices */
type = "rbc";
break;
case 6: /* Transparent SPC-2 devices */
type = "scsi";
break;
default:
break;
}
}
util_strscpy(to, len, type);
return type_num;
}
static void set_scsi_type(char *to, const char *from, size_t len)
{
int type_num;
char *eptr;
char *type = "generic";
int type_num;
char *eptr;
char *type = "generic";
type_num = strtoul(from, &eptr, 0);
if (eptr != from) {
switch (type_num) {
case 0:
case 0xe:
type = "disk";
break;
case 1:
type = "tape";
break;
case 4:
case 7:
case 0xf:
type = "optical";
break;
case 5:
type = "cd";
break;
default:
break;
}
}
util_strscpy(to, len, type);
type_num = strtoul(from, &eptr, 0);
if (eptr != from) {
switch (type_num) {
case 0:
case 0xe:
type = "disk";
break;
case 1:
type = "tape";
break;
case 4:
case 7:
case 0xf:
type = "optical";
break;
case 5:
type = "cd";
break;
default:
break;
}
}
util_strscpy(to, len, type);
}
#define USB_DT_DEVICE 0x01
#define USB_DT_INTERFACE 0x04
#define USB_DT_DEVICE 0x01
#define USB_DT_INTERFACE 0x04
static int dev_if_packed_info(struct udev_device *dev, char *ifs_str, size_t len)
{
char *filename = NULL;
int fd;
ssize_t size;
unsigned char buf[18 + 65535];
unsigned int pos, strpos;
struct usb_interface_descriptor {
u_int8_t bLength;
u_int8_t bDescriptorType;
u_int8_t bInterfaceNumber;
u_int8_t bAlternateSetting;
u_int8_t bNumEndpoints;
u_int8_t bInterfaceClass;
u_int8_t bInterfaceSubClass;
u_int8_t bInterfaceProtocol;
u_int8_t iInterface;
} __attribute__((packed));
int err = 0;
char *filename = NULL;
int fd;
ssize_t size;
unsigned char buf[18 + 65535];
unsigned int pos, strpos;
struct usb_interface_descriptor {
u_int8_t bLength;
u_int8_t bDescriptorType;
u_int8_t bInterfaceNumber;
u_int8_t bAlternateSetting;
u_int8_t bNumEndpoints;
u_int8_t bInterfaceClass;
u_int8_t bInterfaceSubClass;
u_int8_t bInterfaceProtocol;
u_int8_t iInterface;
} __attribute__((packed));
int err = 0;
if (asprintf(&filename, "%s/descriptors", udev_device_get_syspath(dev)) < 0) {
err = -1;
goto out;
}
fd = open(filename, O_RDONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "error opening USB device 'descriptors' file\n");
err = -1;
goto out;
}
size = read(fd, buf, sizeof(buf));
close(fd);
if (size < 18 || size == sizeof(buf)) {
err = -1;
goto out;
}
if (asprintf(&filename, "%s/descriptors", udev_device_get_syspath(dev)) < 0) {
err = -1;
goto out;
}
fd = open(filename, O_RDONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "error opening USB device 'descriptors' file\n");
err = -1;
goto out;
}
size = read(fd, buf, sizeof(buf));
close(fd);
if (size < 18 || size == sizeof(buf)) {
err = -1;
goto out;
}
pos = 0;
strpos = 0;
ifs_str[0] = '\0';
while (pos < sizeof(buf) && strpos+7 < len-2) {
struct usb_interface_descriptor *desc;
char if_str[8];
pos = 0;
strpos = 0;
ifs_str[0] = '\0';
while (pos < sizeof(buf) && strpos+7 < len-2) {
struct usb_interface_descriptor *desc;
char if_str[8];
desc = (struct usb_interface_descriptor *) &buf[pos];
if (desc->bLength < 3)
break;
pos += desc->bLength;
desc = (struct usb_interface_descriptor *) &buf[pos];
if (desc->bLength < 3)
break;
pos += desc->bLength;
if (desc->bDescriptorType != USB_DT_INTERFACE)
continue;
if (desc->bDescriptorType != USB_DT_INTERFACE)
continue;
if (snprintf(if_str, 8, ":%02x%02x%02x",
desc->bInterfaceClass,
desc->bInterfaceSubClass,
desc->bInterfaceProtocol) != 7)
continue;
if (snprintf(if_str, 8, ":%02x%02x%02x",
desc->bInterfaceClass,
desc->bInterfaceSubClass,
desc->bInterfaceProtocol) != 7)
continue;
if (strstr(ifs_str, if_str) != NULL)
continue;
if (strstr(ifs_str, if_str) != NULL)
continue;
memcpy(&ifs_str[strpos], if_str, 8),
strpos += 7;
}
if (strpos > 0) {
ifs_str[strpos++] = ':';
ifs_str[strpos++] = '\0';
}
memcpy(&ifs_str[strpos], if_str, 8),
strpos += 7;
}
if (strpos > 0) {
ifs_str[strpos++] = ':';
ifs_str[strpos++] = '\0';
}
out:
free(filename);
return err;
free(filename);
return err;
}
/*
@@ -241,242 +241,242 @@ out:
*/
static int builtin_usb_id(struct udev_device *dev, int argc, char *argv[], bool test)
{
char vendor_str[64];
char vendor_str_enc[256];
const char *vendor_id;
char model_str[64];
char model_str_enc[256];
const char *product_id;
char serial_str[UTIL_NAME_SIZE];
char packed_if_str[UTIL_NAME_SIZE];
char revision_str[64];
char type_str[64];
char instance_str[64];
const char *ifnum = NULL;
const char *driver = NULL;
char serial[256];
char vendor_str[64];
char vendor_str_enc[256];
const char *vendor_id;
char model_str[64];
char model_str_enc[256];
const char *product_id;
char serial_str[UTIL_NAME_SIZE];
char packed_if_str[UTIL_NAME_SIZE];
char revision_str[64];
char type_str[64];
char instance_str[64];
const char *ifnum = NULL;
const char *driver = NULL;
char serial[256];
struct udev *udev = udev_device_get_udev(dev);
struct udev_device *dev_interface = NULL;
struct udev_device *dev_usb = NULL;
const char *if_class, *if_subclass;
int if_class_num;
int protocol = 0;
size_t l;
char *s;
struct udev *udev = udev_device_get_udev(dev);
struct udev_device *dev_interface = NULL;
struct udev_device *dev_usb = NULL;
const char *if_class, *if_subclass;
int if_class_num;
int protocol = 0;
size_t l;
char *s;
vendor_str[0] = '\0';
model_str[0] = '\0';
serial_str[0] = '\0';
packed_if_str[0] = '\0';
revision_str[0] = '\0';
type_str[0] = '\0';
instance_str[0] = '\0';
vendor_str[0] = '\0';
model_str[0] = '\0';
serial_str[0] = '\0';
packed_if_str[0] = '\0';
revision_str[0] = '\0';
type_str[0] = '\0';
instance_str[0] = '\0';
dbg(udev, "syspath %s\n", udev_device_get_syspath(dev));
dbg(udev, "syspath %s\n", udev_device_get_syspath(dev));
/* shortcut, if we are called directly for a "usb_device" type */
if (udev_device_get_devtype(dev) != NULL && strcmp(udev_device_get_devtype(dev), "usb_device") == 0) {
dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str));
dev_usb = dev;
goto fallback;
}
/* shortcut, if we are called directly for a "usb_device" type */
if (udev_device_get_devtype(dev) != NULL && strcmp(udev_device_get_devtype(dev), "usb_device") == 0) {
dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str));
dev_usb = dev;
goto fallback;
}
/* usb interface directory */
dev_interface = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
if (dev_interface == NULL) {
info(udev, "unable to access usb_interface device of '%s'\n",
udev_device_get_syspath(dev));
return EXIT_FAILURE;
}
/* usb interface directory */
dev_interface = udev_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface");
if (dev_interface == NULL) {
info(udev, "unable to access usb_interface device of '%s'\n",
udev_device_get_syspath(dev));
return EXIT_FAILURE;
}
ifnum = udev_device_get_sysattr_value(dev_interface, "bInterfaceNumber");
driver = udev_device_get_sysattr_value(dev_interface, "driver");
ifnum = udev_device_get_sysattr_value(dev_interface, "bInterfaceNumber");
driver = udev_device_get_sysattr_value(dev_interface, "driver");
if_class = udev_device_get_sysattr_value(dev_interface, "bInterfaceClass");
if (!if_class) {
info(udev, "%s: cannot get bInterfaceClass attribute\n",
udev_device_get_sysname(dev));
return EXIT_FAILURE;
}
if_class = udev_device_get_sysattr_value(dev_interface, "bInterfaceClass");
if (!if_class) {
info(udev, "%s: cannot get bInterfaceClass attribute\n",
udev_device_get_sysname(dev));
return EXIT_FAILURE;
}
if_class_num = strtoul(if_class, NULL, 16);
if (if_class_num == 8) {
/* mass storage */
if_subclass = udev_device_get_sysattr_value(dev_interface, "bInterfaceSubClass");
if (if_subclass != NULL)
protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1);
} else {
set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1);
}
if_class_num = strtoul(if_class, NULL, 16);
if (if_class_num == 8) {
/* mass storage */
if_subclass = udev_device_get_sysattr_value(dev_interface, "bInterfaceSubClass");
if (if_subclass != NULL)
protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1);
} else {
set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1);
}
info(udev, "%s: if_class %d protocol %d\n",
udev_device_get_syspath(dev_interface), if_class_num, protocol);
info(udev, "%s: if_class %d protocol %d\n",
udev_device_get_syspath(dev_interface), if_class_num, protocol);
/* usb device directory */
dev_usb = udev_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device");
if (!dev_usb) {
info(udev, "unable to find parent 'usb' device of '%s'\n",
udev_device_get_syspath(dev));
return EXIT_FAILURE;
}
/* usb device directory */
dev_usb = udev_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device");
if (!dev_usb) {
info(udev, "unable to find parent 'usb' device of '%s'\n",
udev_device_get_syspath(dev));
return EXIT_FAILURE;
}
/* all interfaces of the device in a single string */
dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str));
/* all interfaces of the device in a single string */
dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str));
/* mass storage : SCSI or ATAPI */
if ((protocol == 6 || protocol == 2)) {
struct udev_device *dev_scsi;
const char *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev;
int host, bus, target, lun;
/* mass storage : SCSI or ATAPI */
if ((protocol == 6 || protocol == 2)) {
struct udev_device *dev_scsi;
const char *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev;
int host, bus, target, lun;
/* get scsi device */
dev_scsi = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
if (dev_scsi == NULL) {
info(udev, "unable to find parent 'scsi' device of '%s'\n",
udev_device_get_syspath(dev));
goto fallback;
}
if (sscanf(udev_device_get_sysname(dev_scsi), "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) {
info(udev, "invalid scsi device '%s'\n", udev_device_get_sysname(dev_scsi));
goto fallback;
}
/* get scsi device */
dev_scsi = udev_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device");
if (dev_scsi == NULL) {
info(udev, "unable to find parent 'scsi' device of '%s'\n",
udev_device_get_syspath(dev));
goto fallback;
}
if (sscanf(udev_device_get_sysname(dev_scsi), "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) {
info(udev, "invalid scsi device '%s'\n", udev_device_get_sysname(dev_scsi));
goto fallback;
}
/* Generic SPC-2 device */
scsi_vendor = udev_device_get_sysattr_value(dev_scsi, "vendor");
if (!scsi_vendor) {
info(udev, "%s: cannot get SCSI vendor attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
udev_util_encode_string(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc));
util_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1);
util_replace_chars(vendor_str, NULL);
/* Generic SPC-2 device */
scsi_vendor = udev_device_get_sysattr_value(dev_scsi, "vendor");
if (!scsi_vendor) {
info(udev, "%s: cannot get SCSI vendor attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
udev_util_encode_string(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc));
util_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1);
util_replace_chars(vendor_str, NULL);
scsi_model = udev_device_get_sysattr_value(dev_scsi, "model");
if (!scsi_model) {
info(udev, "%s: cannot get SCSI model attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
udev_util_encode_string(scsi_model, model_str_enc, sizeof(model_str_enc));
util_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1);
util_replace_chars(model_str, NULL);
scsi_model = udev_device_get_sysattr_value(dev_scsi, "model");
if (!scsi_model) {
info(udev, "%s: cannot get SCSI model attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
udev_util_encode_string(scsi_model, model_str_enc, sizeof(model_str_enc));
util_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1);
util_replace_chars(model_str, NULL);
scsi_type = udev_device_get_sysattr_value(dev_scsi, "type");
if (!scsi_type) {
info(udev, "%s: cannot get SCSI type attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
set_scsi_type(type_str, scsi_type, sizeof(type_str)-1);
scsi_type = udev_device_get_sysattr_value(dev_scsi, "type");
if (!scsi_type) {
info(udev, "%s: cannot get SCSI type attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
set_scsi_type(type_str, scsi_type, sizeof(type_str)-1);
scsi_rev = udev_device_get_sysattr_value(dev_scsi, "rev");
if (!scsi_rev) {
info(udev, "%s: cannot get SCSI revision attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
util_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1);
util_replace_chars(revision_str, NULL);
scsi_rev = udev_device_get_sysattr_value(dev_scsi, "rev");
if (!scsi_rev) {
info(udev, "%s: cannot get SCSI revision attribute\n",
udev_device_get_sysname(dev_scsi));
goto fallback;
}
util_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1);
util_replace_chars(revision_str, NULL);
/*
* some broken devices have the same identifiers
* for all luns, export the target:lun number
*/
sprintf(instance_str, "%d:%d", target, lun);
}
/*
* some broken devices have the same identifiers
* for all luns, export the target:lun number
*/
sprintf(instance_str, "%d:%d", target, lun);
}
fallback:
vendor_id = udev_device_get_sysattr_value(dev_usb, "idVendor");
product_id = udev_device_get_sysattr_value(dev_usb, "idProduct");
vendor_id = udev_device_get_sysattr_value(dev_usb, "idVendor");
product_id = udev_device_get_sysattr_value(dev_usb, "idProduct");
/* fallback to USB vendor & device */
if (vendor_str[0] == '\0') {
const char *usb_vendor = NULL;
/* fallback to USB vendor & device */
if (vendor_str[0] == '\0') {
const char *usb_vendor = NULL;
usb_vendor = udev_device_get_sysattr_value(dev_usb, "manufacturer");
if (!usb_vendor)
usb_vendor = vendor_id;
if (!usb_vendor) {
info(udev, "No USB vendor information available\n");
return EXIT_FAILURE;
}
udev_util_encode_string(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc));
util_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1);
util_replace_chars(vendor_str, NULL);
}
usb_vendor = udev_device_get_sysattr_value(dev_usb, "manufacturer");
if (!usb_vendor)
usb_vendor = vendor_id;
if (!usb_vendor) {
info(udev, "No USB vendor information available\n");
return EXIT_FAILURE;
}
udev_util_encode_string(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc));
util_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1);
util_replace_chars(vendor_str, NULL);
}
if (model_str[0] == '\0') {
const char *usb_model = NULL;
if (model_str[0] == '\0') {
const char *usb_model = NULL;
usb_model = udev_device_get_sysattr_value(dev_usb, "product");
if (!usb_model)
usb_model = product_id;
if (!usb_model) {
dbg(udev, "No USB model information available\n");
return EXIT_FAILURE;
}
udev_util_encode_string(usb_model, model_str_enc, sizeof(model_str_enc));
util_replace_whitespace(usb_model, model_str, sizeof(model_str)-1);
util_replace_chars(model_str, NULL);
}
usb_model = udev_device_get_sysattr_value(dev_usb, "product");
if (!usb_model)
usb_model = product_id;
if (!usb_model) {
dbg(udev, "No USB model information available\n");
return EXIT_FAILURE;
}
udev_util_encode_string(usb_model, model_str_enc, sizeof(model_str_enc));
util_replace_whitespace(usb_model, model_str, sizeof(model_str)-1);
util_replace_chars(model_str, NULL);
}
if (revision_str[0] == '\0') {
const char *usb_rev;
if (revision_str[0] == '\0') {
const char *usb_rev;
usb_rev = udev_device_get_sysattr_value(dev_usb, "bcdDevice");
if (usb_rev) {
util_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1);
util_replace_chars(revision_str, NULL);
}
}
usb_rev = udev_device_get_sysattr_value(dev_usb, "bcdDevice");
if (usb_rev) {
util_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1);
util_replace_chars(revision_str, NULL);
}
}
if (serial_str[0] == '\0') {
const char *usb_serial;
if (serial_str[0] == '\0') {
const char *usb_serial;
usb_serial = udev_device_get_sysattr_value(dev_usb, "serial");
if (usb_serial) {
util_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1);
util_replace_chars(serial_str, NULL);
}
}
usb_serial = udev_device_get_sysattr_value(dev_usb, "serial");
if (usb_serial) {
util_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1);
util_replace_chars(serial_str, NULL);
}
}
s = serial;
l = util_strpcpyl(&s, sizeof(serial), vendor_str, "_", model_str, NULL);
if (serial_str[0] != '\0')
l = util_strpcpyl(&s, l, "_", serial_str, NULL);
s = serial;
l = util_strpcpyl(&s, sizeof(serial), vendor_str, "_", model_str, NULL);
if (serial_str[0] != '\0')
l = util_strpcpyl(&s, l, "_", serial_str, NULL);
if (instance_str[0] != '\0')
util_strpcpyl(&s, l, "-", instance_str, NULL);
if (instance_str[0] != '\0')
util_strpcpyl(&s, l, "-", instance_str, NULL);
udev_builtin_add_property(dev, test, "ID_VENDOR", vendor_str);
udev_builtin_add_property(dev, test, "ID_VENDOR_ENC", vendor_str_enc);
udev_builtin_add_property(dev, test, "ID_VENDOR_ID", vendor_id);
udev_builtin_add_property(dev, test, "ID_MODEL", model_str);
udev_builtin_add_property(dev, test, "ID_MODEL_ENC", model_str_enc);
udev_builtin_add_property(dev, test, "ID_MODEL_ID", product_id);
udev_builtin_add_property(dev, test, "ID_REVISION", revision_str);
udev_builtin_add_property(dev, test, "ID_SERIAL", serial);
if (serial_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_SERIAL_SHORT", serial_str);
if (type_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_TYPE", type_str);
if (instance_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_INSTANCE", instance_str);
udev_builtin_add_property(dev, test, "ID_BUS", "usb");
if (packed_if_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_USB_INTERFACES", packed_if_str);
if (ifnum != NULL)
udev_builtin_add_property(dev, test, "ID_USB_INTERFACE_NUM", ifnum);
if (driver != NULL)
udev_builtin_add_property(dev, test, "ID_USB_DRIVER", driver);
return EXIT_SUCCESS;
udev_builtin_add_property(dev, test, "ID_VENDOR", vendor_str);
udev_builtin_add_property(dev, test, "ID_VENDOR_ENC", vendor_str_enc);
udev_builtin_add_property(dev, test, "ID_VENDOR_ID", vendor_id);
udev_builtin_add_property(dev, test, "ID_MODEL", model_str);
udev_builtin_add_property(dev, test, "ID_MODEL_ENC", model_str_enc);
udev_builtin_add_property(dev, test, "ID_MODEL_ID", product_id);
udev_builtin_add_property(dev, test, "ID_REVISION", revision_str);
udev_builtin_add_property(dev, test, "ID_SERIAL", serial);
if (serial_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_SERIAL_SHORT", serial_str);
if (type_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_TYPE", type_str);
if (instance_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_INSTANCE", instance_str);
udev_builtin_add_property(dev, test, "ID_BUS", "usb");
if (packed_if_str[0] != '\0')
udev_builtin_add_property(dev, test, "ID_USB_INTERFACES", packed_if_str);
if (ifnum != NULL)
udev_builtin_add_property(dev, test, "ID_USB_INTERFACE_NUM", ifnum);
if (driver != NULL)
udev_builtin_add_property(dev, test, "ID_USB_DRIVER", driver);
return EXIT_SUCCESS;
}
const struct udev_builtin udev_builtin_usb_id = {
.name = "usb_id",
.cmd = builtin_usb_id,
.help = "usb device properties",
.run_once = true,
.name = "usb_id",
.cmd = builtin_usb_id,
.help = "usb device properties",
.run_once = true,
};
+61 -61
View File
@@ -26,109 +26,109 @@
#include "udev.h"
static const struct udev_builtin *builtins[] = {
[UDEV_BUILTIN_BLKID] = &udev_builtin_blkid,
[UDEV_BUILTIN_FIRMWARE] = &udev_builtin_firmware,
[UDEV_BUILTIN_INPUT_ID] = &udev_builtin_input_id,
[UDEV_BUILTIN_KMOD] = &udev_builtin_kmod,
[UDEV_BUILTIN_PATH_ID] = &udev_builtin_path_id,
[UDEV_BUILTIN_PCI_DB] = &udev_builtin_pci_db,
[UDEV_BUILTIN_USB_DB] = &udev_builtin_usb_db,
[UDEV_BUILTIN_USB_ID] = &udev_builtin_usb_id,
[UDEV_BUILTIN_BLKID] = &udev_builtin_blkid,
[UDEV_BUILTIN_FIRMWARE] = &udev_builtin_firmware,
[UDEV_BUILTIN_INPUT_ID] = &udev_builtin_input_id,
[UDEV_BUILTIN_KMOD] = &udev_builtin_kmod,
[UDEV_BUILTIN_PATH_ID] = &udev_builtin_path_id,
[UDEV_BUILTIN_PCI_DB] = &udev_builtin_pci_db,
[UDEV_BUILTIN_USB_DB] = &udev_builtin_usb_db,
[UDEV_BUILTIN_USB_ID] = &udev_builtin_usb_id,
};
int udev_builtin_init(struct udev *udev)
{
unsigned int i;
int err;
unsigned int i;
int err;
for (i = 0; i < ARRAY_SIZE(builtins); i++) {
if (builtins[i]->init) {
err = builtins[i]->init(udev);
if (err < 0)
break;
}
}
return err;
for (i = 0; i < ARRAY_SIZE(builtins); i++) {
if (builtins[i]->init) {
err = builtins[i]->init(udev);
if (err < 0)
break;
}
}
return err;
}
void udev_builtin_exit(struct udev *udev)
{
unsigned int i;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (builtins[i]->exit)
builtins[i]->exit(udev);
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (builtins[i]->exit)
builtins[i]->exit(udev);
}
bool udev_builtin_validate(struct udev *udev)
{
unsigned int i;
bool change = false;
unsigned int i;
bool change = false;
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (builtins[i]->validate)
if (builtins[i]->validate(udev))
change = true;
return change;
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (builtins[i]->validate)
if (builtins[i]->validate(udev))
change = true;
return change;
}
void udev_builtin_list(struct udev *udev)
{
unsigned int i;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(builtins); i++)
fprintf(stderr, " %-12s %s\n", builtins[i]->name, builtins[i]->help);
for (i = 0; i < ARRAY_SIZE(builtins); i++)
fprintf(stderr, " %-12s %s\n", builtins[i]->name, builtins[i]->help);
}
const char *udev_builtin_name(enum udev_builtin_cmd cmd)
{
return builtins[cmd]->name;
return builtins[cmd]->name;
}
bool udev_builtin_run_once(enum udev_builtin_cmd cmd)
{
return builtins[cmd]->run_once;
return builtins[cmd]->run_once;
}
enum udev_builtin_cmd udev_builtin_lookup(const char *command)
{
char name[UTIL_PATH_SIZE];
enum udev_builtin_cmd i;
char *pos;
char name[UTIL_PATH_SIZE];
enum udev_builtin_cmd i;
char *pos;
util_strscpy(name, sizeof(name), command);
pos = strchr(name, ' ');
if (pos)
pos[0] = '\0';
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (strcmp(builtins[i]->name, name) == 0)
return i;
return UDEV_BUILTIN_MAX;
util_strscpy(name, sizeof(name), command);
pos = strchr(name, ' ');
if (pos)
pos[0] = '\0';
for (i = 0; i < ARRAY_SIZE(builtins); i++)
if (strcmp(builtins[i]->name, name) == 0)
return i;
return UDEV_BUILTIN_MAX;
}
int udev_builtin_run(struct udev_device *dev, enum udev_builtin_cmd cmd, const char *command, bool test)
{
char arg[UTIL_PATH_SIZE];
int argc;
char *argv[128];
char arg[UTIL_PATH_SIZE];
int argc;
char *argv[128];
optind = 0;
util_strscpy(arg, sizeof(arg), command);
udev_build_argv(udev_device_get_udev(dev), arg, &argc, argv);
return builtins[cmd]->cmd(dev, argc, argv, test);
optind = 0;
util_strscpy(arg, sizeof(arg), command);
udev_build_argv(udev_device_get_udev(dev), arg, &argc, argv);
return builtins[cmd]->cmd(dev, argc, argv, test);
}
int udev_builtin_add_property(struct udev_device *dev, bool test, const char *key, const char *val)
{
struct udev_list_entry *entry;
struct udev_list_entry *entry;
entry = udev_device_add_property(dev, key, val);
/* store in db, skip private keys */
if (key[0] != '.')
udev_list_entry_set_num(entry, true);
entry = udev_device_add_property(dev, key, val);
/* store in db, skip private keys */
if (key[0] != '.')
udev_list_entry_set_num(entry, true);
info(udev_device_get_udev(dev), "%s=%s\n", key, val);
if (test)
printf("%s=%s\n", key, val);
return 0;
info(udev_device_get_udev(dev), "%s=%s\n", key, val);
if (test)
printf("%s=%s\n", key, val);
return 0;
}
+298 -298
View File
@@ -23,472 +23,472 @@
#include "udev.h"
/* wire protocol magic must match */
#define UDEV_CTRL_MAGIC 0xdead1dea
#define UDEV_CTRL_MAGIC 0xdead1dea
enum udev_ctrl_msg_type {
UDEV_CTRL_UNKNOWN,
UDEV_CTRL_SET_LOG_LEVEL,
UDEV_CTRL_STOP_EXEC_QUEUE,
UDEV_CTRL_START_EXEC_QUEUE,
UDEV_CTRL_RELOAD,
UDEV_CTRL_SET_ENV,
UDEV_CTRL_SET_CHILDREN_MAX,
UDEV_CTRL_PING,
UDEV_CTRL_EXIT,
UDEV_CTRL_UNKNOWN,
UDEV_CTRL_SET_LOG_LEVEL,
UDEV_CTRL_STOP_EXEC_QUEUE,
UDEV_CTRL_START_EXEC_QUEUE,
UDEV_CTRL_RELOAD,
UDEV_CTRL_SET_ENV,
UDEV_CTRL_SET_CHILDREN_MAX,
UDEV_CTRL_PING,
UDEV_CTRL_EXIT,
};
struct udev_ctrl_msg_wire {
char version[16];
unsigned int magic;
enum udev_ctrl_msg_type type;
union {
int intval;
char buf[256];
};
char version[16];
unsigned int magic;
enum udev_ctrl_msg_type type;
union {
int intval;
char buf[256];
};
};
struct udev_ctrl_msg {
int refcount;
struct udev_ctrl_connection *conn;
struct udev_ctrl_msg_wire ctrl_msg_wire;
int refcount;
struct udev_ctrl_connection *conn;
struct udev_ctrl_msg_wire ctrl_msg_wire;
};
struct udev_ctrl {
int refcount;
struct udev *udev;
int sock;
struct sockaddr_un saddr;
socklen_t addrlen;
bool bound;
bool cleanup_socket;
bool connected;
int refcount;
struct udev *udev;
int sock;
struct sockaddr_un saddr;
socklen_t addrlen;
bool bound;
bool cleanup_socket;
bool connected;
};
struct udev_ctrl_connection {
int refcount;
struct udev_ctrl *uctrl;
int sock;
int refcount;
struct udev_ctrl *uctrl;
int sock;
};
struct udev_ctrl *udev_ctrl_new_from_fd(struct udev *udev, int fd)
{
struct udev_ctrl *uctrl;
struct udev_ctrl *uctrl;
uctrl = calloc(1, sizeof(struct udev_ctrl));
if (uctrl == NULL)
return NULL;
uctrl->refcount = 1;
uctrl->udev = udev;
uctrl = calloc(1, sizeof(struct udev_ctrl));
if (uctrl == NULL)
return NULL;
uctrl->refcount = 1;
uctrl->udev = udev;
if (fd < 0) {
uctrl->sock = socket(AF_LOCAL, SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
if (uctrl->sock < 0) {
err(udev, "error getting socket: %m\n");
udev_ctrl_unref(uctrl);
return NULL;
}
} else {
uctrl->bound = true;
uctrl->sock = fd;
}
if (fd < 0) {
uctrl->sock = socket(AF_LOCAL, SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
if (uctrl->sock < 0) {
err(udev, "error getting socket: %m\n");
udev_ctrl_unref(uctrl);
return NULL;
}
} else {
uctrl->bound = true;
uctrl->sock = fd;
}
uctrl->saddr.sun_family = AF_LOCAL;
util_strscpyl(uctrl->saddr.sun_path, sizeof(uctrl->saddr.sun_path),
uctrl->saddr.sun_family = AF_LOCAL;
util_strscpyl(uctrl->saddr.sun_path, sizeof(uctrl->saddr.sun_path),
udev_get_run_path(udev), "/control", NULL);
uctrl->addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(uctrl->saddr.sun_path);
return uctrl;
uctrl->addrlen = offsetof(struct sockaddr_un, sun_path) + strlen(uctrl->saddr.sun_path);
return uctrl;
}
struct udev_ctrl *udev_ctrl_new(struct udev *udev)
{
return udev_ctrl_new_from_fd(udev, -1);
return udev_ctrl_new_from_fd(udev, -1);
}
int udev_ctrl_enable_receiving(struct udev_ctrl *uctrl)
{
int err;
int err;
if (!uctrl->bound) {
err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
if (err < 0 && errno == EADDRINUSE) {
unlink(uctrl->saddr.sun_path);
err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
}
if (!uctrl->bound) {
err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
if (err < 0 && errno == EADDRINUSE) {
unlink(uctrl->saddr.sun_path);
err = bind(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen);
}
if (err < 0) {
err = -errno;
err(uctrl->udev, "bind failed: %m\n");
return err;
}
if (err < 0) {
err = -errno;
err(uctrl->udev, "bind failed: %m\n");
return err;
}
err = listen(uctrl->sock, 0);
if (err < 0) {
err = -errno;
err(uctrl->udev, "listen failed: %m\n");
return err;
}
err = listen(uctrl->sock, 0);
if (err < 0) {
err = -errno;
err(uctrl->udev, "listen failed: %m\n");
return err;
}
uctrl->bound = true;
uctrl->cleanup_socket = true;
}
return 0;
uctrl->bound = true;
uctrl->cleanup_socket = true;
}
return 0;
}
struct udev *udev_ctrl_get_udev(struct udev_ctrl *uctrl)
{
return uctrl->udev;
return uctrl->udev;
}
struct udev_ctrl *udev_ctrl_ref(struct udev_ctrl *uctrl)
{
if (uctrl == NULL)
return NULL;
uctrl->refcount++;
return uctrl;
if (uctrl == NULL)
return NULL;
uctrl->refcount++;
return uctrl;
}
struct udev_ctrl *udev_ctrl_unref(struct udev_ctrl *uctrl)
{
if (uctrl == NULL)
return NULL;
uctrl->refcount--;
if (uctrl->refcount > 0)
return uctrl;
if (uctrl->sock >= 0)
close(uctrl->sock);
free(uctrl);
return NULL;
if (uctrl == NULL)
return NULL;
uctrl->refcount--;
if (uctrl->refcount > 0)
return uctrl;
if (uctrl->sock >= 0)
close(uctrl->sock);
free(uctrl);
return NULL;
}
int udev_ctrl_cleanup(struct udev_ctrl *uctrl)
{
if (uctrl == NULL)
return 0;
if (uctrl->cleanup_socket)
unlink(uctrl->saddr.sun_path);
return 0;
if (uctrl == NULL)
return 0;
if (uctrl->cleanup_socket)
unlink(uctrl->saddr.sun_path);
return 0;
}
int udev_ctrl_get_fd(struct udev_ctrl *uctrl)
{
if (uctrl == NULL)
return -EINVAL;
return uctrl->sock;
if (uctrl == NULL)
return -EINVAL;
return uctrl->sock;
}
struct udev_ctrl_connection *udev_ctrl_get_connection(struct udev_ctrl *uctrl)
{
struct udev_ctrl_connection *conn;
struct ucred ucred;
socklen_t slen;
const int on = 1;
struct udev_ctrl_connection *conn;
struct ucred ucred;
socklen_t slen;
const int on = 1;
conn = calloc(1, sizeof(struct udev_ctrl_connection));
if (conn == NULL)
return NULL;
conn->refcount = 1;
conn->uctrl = uctrl;
conn = calloc(1, sizeof(struct udev_ctrl_connection));
if (conn == NULL)
return NULL;
conn->refcount = 1;
conn->uctrl = uctrl;
conn->sock = accept4(uctrl->sock, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK);
if (conn->sock < 0) {
if (errno != EINTR)
err(uctrl->udev, "unable to receive ctrl connection: %m\n");
goto err;
}
conn->sock = accept4(uctrl->sock, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK);
if (conn->sock < 0) {
if (errno != EINTR)
err(uctrl->udev, "unable to receive ctrl connection: %m\n");
goto err;
}
/* check peer credential of connection */
slen = sizeof(ucred);
if (getsockopt(conn->sock, SOL_SOCKET, SO_PEERCRED, &ucred, &slen) < 0) {
err(uctrl->udev, "unable to receive credentials of ctrl connection: %m\n");
goto err;
}
if (ucred.uid > 0) {
err(uctrl->udev, "sender uid=%i, message ignored\n", ucred.uid);
goto err;
}
/* check peer credential of connection */
slen = sizeof(ucred);
if (getsockopt(conn->sock, SOL_SOCKET, SO_PEERCRED, &ucred, &slen) < 0) {
err(uctrl->udev, "unable to receive credentials of ctrl connection: %m\n");
goto err;
}
if (ucred.uid > 0) {
err(uctrl->udev, "sender uid=%i, message ignored\n", ucred.uid);
goto err;
}
/* enable receiving of the sender credentials in the messages */
setsockopt(conn->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
udev_ctrl_ref(uctrl);
return conn;
/* enable receiving of the sender credentials in the messages */
setsockopt(conn->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
udev_ctrl_ref(uctrl);
return conn;
err:
if (conn->sock >= 0)
close(conn->sock);
free(conn);
return NULL;
if (conn->sock >= 0)
close(conn->sock);
free(conn);
return NULL;
}
struct udev_ctrl_connection *udev_ctrl_connection_ref(struct udev_ctrl_connection *conn)
{
if (conn == NULL)
return NULL;
conn->refcount++;
return conn;
if (conn == NULL)
return NULL;
conn->refcount++;
return conn;
}
struct udev_ctrl_connection *udev_ctrl_connection_unref(struct udev_ctrl_connection *conn)
{
if (conn == NULL)
return NULL;
conn->refcount--;
if (conn->refcount > 0)
return conn;
if (conn->sock >= 0)
close(conn->sock);
udev_ctrl_unref(conn->uctrl);
free(conn);
return NULL;
if (conn == NULL)
return NULL;
conn->refcount--;
if (conn->refcount > 0)
return conn;
if (conn->sock >= 0)
close(conn->sock);
udev_ctrl_unref(conn->uctrl);
free(conn);
return NULL;
}
static int ctrl_send(struct udev_ctrl *uctrl, enum udev_ctrl_msg_type type, int intval, const char *buf, int timeout)
{
struct udev_ctrl_msg_wire ctrl_msg_wire;
int err = 0;
struct udev_ctrl_msg_wire ctrl_msg_wire;
int err = 0;
memset(&ctrl_msg_wire, 0x00, sizeof(struct udev_ctrl_msg_wire));
strcpy(ctrl_msg_wire.version, "udev-" VERSION);
ctrl_msg_wire.magic = UDEV_CTRL_MAGIC;
ctrl_msg_wire.type = type;
memset(&ctrl_msg_wire, 0x00, sizeof(struct udev_ctrl_msg_wire));
strcpy(ctrl_msg_wire.version, "udev-" VERSION);
ctrl_msg_wire.magic = UDEV_CTRL_MAGIC;
ctrl_msg_wire.type = type;
if (buf != NULL)
util_strscpy(ctrl_msg_wire.buf, sizeof(ctrl_msg_wire.buf), buf);
else
ctrl_msg_wire.intval = intval;
if (buf != NULL)
util_strscpy(ctrl_msg_wire.buf, sizeof(ctrl_msg_wire.buf), buf);
else
ctrl_msg_wire.intval = intval;
if (!uctrl->connected) {
if (connect(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen) < 0) {
err = -errno;
goto out;
}
uctrl->connected = true;
}
if (send(uctrl->sock, &ctrl_msg_wire, sizeof(ctrl_msg_wire), 0) < 0) {
err = -errno;
goto out;
}
if (!uctrl->connected) {
if (connect(uctrl->sock, (struct sockaddr *)&uctrl->saddr, uctrl->addrlen) < 0) {
err = -errno;
goto out;
}
uctrl->connected = true;
}
if (send(uctrl->sock, &ctrl_msg_wire, sizeof(ctrl_msg_wire), 0) < 0) {
err = -errno;
goto out;
}
/* wait for peer message handling or disconnect */
for (;;) {
struct pollfd pfd[1];
int r;
/* wait for peer message handling or disconnect */
for (;;) {
struct pollfd pfd[1];
int r;
pfd[0].fd = uctrl->sock;
pfd[0].events = POLLIN;
r = poll(pfd, 1, timeout * 1000);
if (r < 0) {
if (errno == EINTR)
continue;
err = -errno;
break;
}
pfd[0].fd = uctrl->sock;
pfd[0].events = POLLIN;
r = poll(pfd, 1, timeout * 1000);
if (r < 0) {
if (errno == EINTR)
continue;
err = -errno;
break;
}
if (r > 0 && pfd[0].revents & POLLERR) {
err = -EIO;
break;
}
if (r > 0 && pfd[0].revents & POLLERR) {
err = -EIO;
break;
}
if (r == 0)
err = -ETIMEDOUT;
break;
}
if (r == 0)
err = -ETIMEDOUT;
break;
}
out:
return err;
return err;
}
int udev_ctrl_send_set_log_level(struct udev_ctrl *uctrl, int priority, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_SET_LOG_LEVEL, priority, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_SET_LOG_LEVEL, priority, NULL, timeout);
}
int udev_ctrl_send_stop_exec_queue(struct udev_ctrl *uctrl, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_STOP_EXEC_QUEUE, 0, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_STOP_EXEC_QUEUE, 0, NULL, timeout);
}
int udev_ctrl_send_start_exec_queue(struct udev_ctrl *uctrl, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_START_EXEC_QUEUE, 0, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_START_EXEC_QUEUE, 0, NULL, timeout);
}
int udev_ctrl_send_reload(struct udev_ctrl *uctrl, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_RELOAD, 0, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_RELOAD, 0, NULL, timeout);
}
int udev_ctrl_send_set_env(struct udev_ctrl *uctrl, const char *key, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_SET_ENV, 0, key, timeout);
return ctrl_send(uctrl, UDEV_CTRL_SET_ENV, 0, key, timeout);
}
int udev_ctrl_send_set_children_max(struct udev_ctrl *uctrl, int count, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_SET_CHILDREN_MAX, count, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_SET_CHILDREN_MAX, count, NULL, timeout);
}
int udev_ctrl_send_ping(struct udev_ctrl *uctrl, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_PING, 0, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_PING, 0, NULL, timeout);
}
int udev_ctrl_send_exit(struct udev_ctrl *uctrl, int timeout)
{
return ctrl_send(uctrl, UDEV_CTRL_EXIT, 0, NULL, timeout);
return ctrl_send(uctrl, UDEV_CTRL_EXIT, 0, NULL, timeout);
}
struct udev_ctrl_msg *udev_ctrl_receive_msg(struct udev_ctrl_connection *conn)
{
struct udev *udev = conn->uctrl->udev;
struct udev_ctrl_msg *uctrl_msg;
ssize_t size;
struct msghdr smsg;
struct cmsghdr *cmsg;
struct iovec iov;
struct ucred *cred;
char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
struct udev *udev = conn->uctrl->udev;
struct udev_ctrl_msg *uctrl_msg;
ssize_t size;
struct msghdr smsg;
struct cmsghdr *cmsg;
struct iovec iov;
struct ucred *cred;
char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
uctrl_msg = calloc(1, sizeof(struct udev_ctrl_msg));
if (uctrl_msg == NULL)
return NULL;
uctrl_msg->refcount = 1;
uctrl_msg->conn = conn;
udev_ctrl_connection_ref(conn);
uctrl_msg = calloc(1, sizeof(struct udev_ctrl_msg));
if (uctrl_msg == NULL)
return NULL;
uctrl_msg->refcount = 1;
uctrl_msg->conn = conn;
udev_ctrl_connection_ref(conn);
/* wait for the incoming message */
for(;;) {
struct pollfd pfd[1];
int r;
/* wait for the incoming message */
for(;;) {
struct pollfd pfd[1];
int r;
pfd[0].fd = conn->sock;
pfd[0].events = POLLIN;
pfd[0].fd = conn->sock;
pfd[0].events = POLLIN;
r = poll(pfd, 1, 10000);
if (r < 0) {
if (errno == EINTR)
continue;
goto err;
} else if (r == 0) {
err(udev, "timeout waiting for ctrl message\n");
goto err;
} else {
if (!(pfd[0].revents & POLLIN)) {
err(udev, "ctrl connection error: %m\n");
goto err;
}
}
r = poll(pfd, 1, 10000);
if (r < 0) {
if (errno == EINTR)
continue;
goto err;
} else if (r == 0) {
err(udev, "timeout waiting for ctrl message\n");
goto err;
} else {
if (!(pfd[0].revents & POLLIN)) {
err(udev, "ctrl connection error: %m\n");
goto err;
}
}
break;
}
break;
}
iov.iov_base = &uctrl_msg->ctrl_msg_wire;
iov.iov_len = sizeof(struct udev_ctrl_msg_wire);
memset(&smsg, 0x00, sizeof(struct msghdr));
smsg.msg_iov = &iov;
smsg.msg_iovlen = 1;
smsg.msg_control = cred_msg;
smsg.msg_controllen = sizeof(cred_msg);
size = recvmsg(conn->sock, &smsg, 0);
if (size < 0) {
err(udev, "unable to receive ctrl message: %m\n");
goto err;
}
cmsg = CMSG_FIRSTHDR(&smsg);
cred = (struct ucred *) CMSG_DATA(cmsg);
iov.iov_base = &uctrl_msg->ctrl_msg_wire;
iov.iov_len = sizeof(struct udev_ctrl_msg_wire);
memset(&smsg, 0x00, sizeof(struct msghdr));
smsg.msg_iov = &iov;
smsg.msg_iovlen = 1;
smsg.msg_control = cred_msg;
smsg.msg_controllen = sizeof(cred_msg);
size = recvmsg(conn->sock, &smsg, 0);
if (size < 0) {
err(udev, "unable to receive ctrl message: %m\n");
goto err;
}
cmsg = CMSG_FIRSTHDR(&smsg);
cred = (struct ucred *) CMSG_DATA(cmsg);
if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
err(udev, "no sender credentials received, message ignored\n");
goto err;
}
if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
err(udev, "no sender credentials received, message ignored\n");
goto err;
}
if (cred->uid != 0) {
err(udev, "sender uid=%i, message ignored\n", cred->uid);
goto err;
}
if (cred->uid != 0) {
err(udev, "sender uid=%i, message ignored\n", cred->uid);
goto err;
}
if (uctrl_msg->ctrl_msg_wire.magic != UDEV_CTRL_MAGIC) {
err(udev, "message magic 0x%08x doesn't match, ignore it\n", uctrl_msg->ctrl_msg_wire.magic);
goto err;
}
if (uctrl_msg->ctrl_msg_wire.magic != UDEV_CTRL_MAGIC) {
err(udev, "message magic 0x%08x doesn't match, ignore it\n", uctrl_msg->ctrl_msg_wire.magic);
goto err;
}
dbg(udev, "created ctrl_msg %p (%i)\n", uctrl_msg, uctrl_msg->ctrl_msg_wire.type);
return uctrl_msg;
dbg(udev, "created ctrl_msg %p (%i)\n", uctrl_msg, uctrl_msg->ctrl_msg_wire.type);
return uctrl_msg;
err:
udev_ctrl_msg_unref(uctrl_msg);
return NULL;
udev_ctrl_msg_unref(uctrl_msg);
return NULL;
}
struct udev_ctrl_msg *udev_ctrl_msg_ref(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg == NULL)
return NULL;
ctrl_msg->refcount++;
return ctrl_msg;
if (ctrl_msg == NULL)
return NULL;
ctrl_msg->refcount++;
return ctrl_msg;
}
struct udev_ctrl_msg *udev_ctrl_msg_unref(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg == NULL)
return NULL;
ctrl_msg->refcount--;
if (ctrl_msg->refcount > 0)
return ctrl_msg;
dbg(ctrl_msg->conn->uctrl->udev, "release ctrl_msg %p\n", ctrl_msg);
udev_ctrl_connection_unref(ctrl_msg->conn);
free(ctrl_msg);
return NULL;
if (ctrl_msg == NULL)
return NULL;
ctrl_msg->refcount--;
if (ctrl_msg->refcount > 0)
return ctrl_msg;
dbg(ctrl_msg->conn->uctrl->udev, "release ctrl_msg %p\n", ctrl_msg);
udev_ctrl_connection_unref(ctrl_msg->conn);
free(ctrl_msg);
return NULL;
}
int udev_ctrl_get_set_log_level(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_LOG_LEVEL)
return ctrl_msg->ctrl_msg_wire.intval;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_LOG_LEVEL)
return ctrl_msg->ctrl_msg_wire.intval;
return -1;
}
int udev_ctrl_get_stop_exec_queue(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_STOP_EXEC_QUEUE)
return 1;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_STOP_EXEC_QUEUE)
return 1;
return -1;
}
int udev_ctrl_get_start_exec_queue(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_START_EXEC_QUEUE)
return 1;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_START_EXEC_QUEUE)
return 1;
return -1;
}
int udev_ctrl_get_reload(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_RELOAD)
return 1;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_RELOAD)
return 1;
return -1;
}
const char *udev_ctrl_get_set_env(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_ENV)
return ctrl_msg->ctrl_msg_wire.buf;
return NULL;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_ENV)
return ctrl_msg->ctrl_msg_wire.buf;
return NULL;
}
int udev_ctrl_get_set_children_max(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_CHILDREN_MAX)
return ctrl_msg->ctrl_msg_wire.intval;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_SET_CHILDREN_MAX)
return ctrl_msg->ctrl_msg_wire.intval;
return -1;
}
int udev_ctrl_get_ping(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_PING)
return 1;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_PING)
return 1;
return -1;
}
int udev_ctrl_get_exit(struct udev_ctrl_msg *ctrl_msg)
{
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_EXIT)
return 1;
return -1;
if (ctrl_msg->ctrl_msg_wire.type == UDEV_CTRL_EXIT)
return 1;
return -1;
}
+807 -807
View File
File diff suppressed because it is too large Load Diff
+283 -283
View File
@@ -31,355 +31,355 @@
#include "udev.h"
#define TMP_FILE_EXT ".udev-tmp"
#define TMP_FILE_EXT ".udev-tmp"
static int node_symlink(struct udev *udev, const char *node, const char *slink)
{
struct stat stats;
char target[UTIL_PATH_SIZE];
char *s;
size_t l;
char slink_tmp[UTIL_PATH_SIZE + sizeof(TMP_FILE_EXT)];
int i = 0;
int tail = 0;
int err = 0;
struct stat stats;
char target[UTIL_PATH_SIZE];
char *s;
size_t l;
char slink_tmp[UTIL_PATH_SIZE + sizeof(TMP_FILE_EXT)];
int i = 0;
int tail = 0;
int err = 0;
/* use relative link */
target[0] = '\0';
while (node[i] && (node[i] == slink[i])) {
if (node[i] == '/')
tail = i+1;
i++;
}
s = target;
l = sizeof(target);
while (slink[i] != '\0') {
if (slink[i] == '/')
l = util_strpcpy(&s, l, "../");
i++;
}
l = util_strscpy(s, l, &node[tail]);
if (l == 0) {
err = -EINVAL;
goto exit;
}
/* use relative link */
target[0] = '\0';
while (node[i] && (node[i] == slink[i])) {
if (node[i] == '/')
tail = i+1;
i++;
}
s = target;
l = sizeof(target);
while (slink[i] != '\0') {
if (slink[i] == '/')
l = util_strpcpy(&s, l, "../");
i++;
}
l = util_strscpy(s, l, &node[tail]);
if (l == 0) {
err = -EINVAL;
goto exit;
}
/* preserve link with correct target, do not replace node of other device */
if (lstat(slink, &stats) == 0) {
if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
struct stat stats2;
/* preserve link with correct target, do not replace node of other device */
if (lstat(slink, &stats) == 0) {
if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
struct stat stats2;
info(udev, "found existing node instead of symlink '%s'\n", slink);
if (lstat(node, &stats2) == 0) {
if ((stats.st_mode & S_IFMT) == (stats2.st_mode & S_IFMT) &&
stats.st_rdev == stats2.st_rdev && stats.st_ino != stats2.st_ino) {
info(udev, "replace device node '%s' with symlink to our node '%s'\n",
slink, node);
} else {
err(udev, "device node '%s' already exists, "
"link to '%s' will not overwrite it\n",
slink, node);
goto exit;
}
}
} else if (S_ISLNK(stats.st_mode)) {
char buf[UTIL_PATH_SIZE];
int len;
info(udev, "found existing node instead of symlink '%s'\n", slink);
if (lstat(node, &stats2) == 0) {
if ((stats.st_mode & S_IFMT) == (stats2.st_mode & S_IFMT) &&
stats.st_rdev == stats2.st_rdev && stats.st_ino != stats2.st_ino) {
info(udev, "replace device node '%s' with symlink to our node '%s'\n",
slink, node);
} else {
err(udev, "device node '%s' already exists, "
"link to '%s' will not overwrite it\n",
slink, node);
goto exit;
}
}
} else if (S_ISLNK(stats.st_mode)) {
char buf[UTIL_PATH_SIZE];
int len;
dbg(udev, "found existing symlink '%s'\n", slink);
len = readlink(slink, buf, sizeof(buf));
if (len > 0 && len < (int)sizeof(buf)) {
buf[len] = '\0';
if (strcmp(target, buf) == 0) {
info(udev, "preserve already existing symlink '%s' to '%s'\n",
slink, target);
udev_selinux_lsetfilecon(udev, slink, S_IFLNK);
utimensat(AT_FDCWD, slink, NULL, AT_SYMLINK_NOFOLLOW);
goto exit;
}
}
}
} else {
info(udev, "creating symlink '%s' to '%s'\n", slink, target);
do {
err = util_create_path_selinux(udev, slink);
if (err != 0 && err != -ENOENT)
break;
udev_selinux_setfscreatecon(udev, slink, S_IFLNK);
err = symlink(target, slink);
if (err != 0)
err = -errno;
udev_selinux_resetfscreatecon(udev);
} while (err == -ENOENT);
if (err == 0)
goto exit;
}
dbg(udev, "found existing symlink '%s'\n", slink);
len = readlink(slink, buf, sizeof(buf));
if (len > 0 && len < (int)sizeof(buf)) {
buf[len] = '\0';
if (strcmp(target, buf) == 0) {
info(udev, "preserve already existing symlink '%s' to '%s'\n",
slink, target);
udev_selinux_lsetfilecon(udev, slink, S_IFLNK);
utimensat(AT_FDCWD, slink, NULL, AT_SYMLINK_NOFOLLOW);
goto exit;
}
}
}
} else {
info(udev, "creating symlink '%s' to '%s'\n", slink, target);
do {
err = util_create_path_selinux(udev, slink);
if (err != 0 && err != -ENOENT)
break;
udev_selinux_setfscreatecon(udev, slink, S_IFLNK);
err = symlink(target, slink);
if (err != 0)
err = -errno;
udev_selinux_resetfscreatecon(udev);
} while (err == -ENOENT);
if (err == 0)
goto exit;
}
info(udev, "atomically replace '%s'\n", slink);
util_strscpyl(slink_tmp, sizeof(slink_tmp), slink, TMP_FILE_EXT, NULL);
unlink(slink_tmp);
do {
err = util_create_path_selinux(udev, slink_tmp);
if (err != 0 && err != -ENOENT)
break;
udev_selinux_setfscreatecon(udev, slink_tmp, S_IFLNK);
err = symlink(target, slink_tmp);
if (err != 0)
err = -errno;
udev_selinux_resetfscreatecon(udev);
} while (err == -ENOENT);
if (err != 0) {
err(udev, "symlink '%s' '%s' failed: %m\n", target, slink_tmp);
goto exit;
}
err = rename(slink_tmp, slink);
if (err != 0) {
err(udev, "rename '%s' '%s' failed: %m\n", slink_tmp, slink);
unlink(slink_tmp);
}
info(udev, "atomically replace '%s'\n", slink);
util_strscpyl(slink_tmp, sizeof(slink_tmp), slink, TMP_FILE_EXT, NULL);
unlink(slink_tmp);
do {
err = util_create_path_selinux(udev, slink_tmp);
if (err != 0 && err != -ENOENT)
break;
udev_selinux_setfscreatecon(udev, slink_tmp, S_IFLNK);
err = symlink(target, slink_tmp);
if (err != 0)
err = -errno;
udev_selinux_resetfscreatecon(udev);
} while (err == -ENOENT);
if (err != 0) {
err(udev, "symlink '%s' '%s' failed: %m\n", target, slink_tmp);
goto exit;
}
err = rename(slink_tmp, slink);
if (err != 0) {
err(udev, "rename '%s' '%s' failed: %m\n", slink_tmp, slink);
unlink(slink_tmp);
}
exit:
return err;
return err;
}
/* find device node of device with highest priority */
static const char *link_find_prioritized(struct udev_device *dev, bool add, const char *stackdir, char *buf, size_t bufsize)
{
struct udev *udev = udev_device_get_udev(dev);
DIR *dir;
int priority = 0;
const char *target = NULL;
struct udev *udev = udev_device_get_udev(dev);
DIR *dir;
int priority = 0;
const char *target = NULL;
if (add) {
priority = udev_device_get_devlink_priority(dev);
util_strscpy(buf, bufsize, udev_device_get_devnode(dev));
target = buf;
}
if (add) {
priority = udev_device_get_devlink_priority(dev);
util_strscpy(buf, bufsize, udev_device_get_devnode(dev));
target = buf;
}
dir = opendir(stackdir);
if (dir == NULL)
return target;
for (;;) {
struct udev_device *dev_db;
struct dirent *dent;
dir = opendir(stackdir);
if (dir == NULL)
return target;
for (;;) {
struct udev_device *dev_db;
struct dirent *dent;
dent = readdir(dir);
if (dent == NULL || dent->d_name[0] == '\0')
break;
if (dent->d_name[0] == '.')
continue;
dent = readdir(dir);
if (dent == NULL || dent->d_name[0] == '\0')
break;
if (dent->d_name[0] == '.')
continue;
info(udev, "found '%s' claiming '%s'\n", dent->d_name, stackdir);
info(udev, "found '%s' claiming '%s'\n", dent->d_name, stackdir);
/* did we find ourself? */
if (strcmp(dent->d_name, udev_device_get_id_filename(dev)) == 0)
continue;
/* did we find ourself? */
if (strcmp(dent->d_name, udev_device_get_id_filename(dev)) == 0)
continue;
dev_db = udev_device_new_from_id_filename(udev, dent->d_name);
if (dev_db != NULL) {
const char *devnode;
dev_db = udev_device_new_from_id_filename(udev, dent->d_name);
if (dev_db != NULL) {
const char *devnode;
devnode = udev_device_get_devnode(dev_db);
if (devnode != NULL) {
dbg(udev, "compare priority of '%s'(%i) > '%s'(%i)\n", target, priority,
udev_device_get_devnode(dev_db), udev_device_get_devlink_priority(dev_db));
if (target == NULL || udev_device_get_devlink_priority(dev_db) > priority) {
info(udev, "'%s' claims priority %i for '%s'\n",
udev_device_get_syspath(dev_db), udev_device_get_devlink_priority(dev_db), stackdir);
priority = udev_device_get_devlink_priority(dev_db);
util_strscpy(buf, bufsize, devnode);
target = buf;
}
}
udev_device_unref(dev_db);
}
}
closedir(dir);
return target;
devnode = udev_device_get_devnode(dev_db);
if (devnode != NULL) {
dbg(udev, "compare priority of '%s'(%i) > '%s'(%i)\n", target, priority,
udev_device_get_devnode(dev_db), udev_device_get_devlink_priority(dev_db));
if (target == NULL || udev_device_get_devlink_priority(dev_db) > priority) {
info(udev, "'%s' claims priority %i for '%s'\n",
udev_device_get_syspath(dev_db), udev_device_get_devlink_priority(dev_db), stackdir);
priority = udev_device_get_devlink_priority(dev_db);
util_strscpy(buf, bufsize, devnode);
target = buf;
}
}
udev_device_unref(dev_db);
}
}
closedir(dir);
return target;
}
/* manage "stack of names" with possibly specified device priorities */
static void link_update(struct udev_device *dev, const char *slink, bool add)
{
struct udev *udev = udev_device_get_udev(dev);
char name_enc[UTIL_PATH_SIZE];
char filename[UTIL_PATH_SIZE * 2];
char dirname[UTIL_PATH_SIZE];
const char *target;
char buf[UTIL_PATH_SIZE];
struct udev *udev = udev_device_get_udev(dev);
char name_enc[UTIL_PATH_SIZE];
char filename[UTIL_PATH_SIZE * 2];
char dirname[UTIL_PATH_SIZE];
const char *target;
char buf[UTIL_PATH_SIZE];
dbg(udev, "update symlink '%s' of '%s'\n", slink, udev_device_get_syspath(dev));
dbg(udev, "update symlink '%s' of '%s'\n", slink, udev_device_get_syspath(dev));
util_path_encode(&slink[strlen(udev_get_dev_path(udev))+1], name_enc, sizeof(name_enc));
util_strscpyl(dirname, sizeof(dirname), udev_get_run_path(udev), "/links/", name_enc, NULL);
util_strscpyl(filename, sizeof(filename), dirname, "/", udev_device_get_id_filename(dev), NULL);
util_path_encode(&slink[strlen(udev_get_dev_path(udev))+1], name_enc, sizeof(name_enc));
util_strscpyl(dirname, sizeof(dirname), udev_get_run_path(udev), "/links/", name_enc, NULL);
util_strscpyl(filename, sizeof(filename), dirname, "/", udev_device_get_id_filename(dev), NULL);
if (!add) {
dbg(udev, "removing index: '%s'\n", filename);
if (unlink(filename) == 0)
rmdir(dirname);
}
if (!add) {
dbg(udev, "removing index: '%s'\n", filename);
if (unlink(filename) == 0)
rmdir(dirname);
}
target = link_find_prioritized(dev, add, dirname, buf, sizeof(buf));
if (target == NULL) {
info(udev, "no reference left, remove '%s'\n", slink);
if (unlink(slink) == 0)
util_delete_path(udev, slink);
} else {
info(udev, "creating link '%s' to '%s'\n", slink, target);
node_symlink(udev, target, slink);
}
target = link_find_prioritized(dev, add, dirname, buf, sizeof(buf));
if (target == NULL) {
info(udev, "no reference left, remove '%s'\n", slink);
if (unlink(slink) == 0)
util_delete_path(udev, slink);
} else {
info(udev, "creating link '%s' to '%s'\n", slink, target);
node_symlink(udev, target, slink);
}
if (add) {
int err;
if (add) {
int err;
dbg(udev, "creating index: '%s'\n", filename);
do {
int fd;
dbg(udev, "creating index: '%s'\n", filename);
do {
int fd;
err = util_create_path(udev, filename);
if (err != 0 && err != -ENOENT)
break;
fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
if (fd >= 0)
close(fd);
else
err = -errno;
} while (err == -ENOENT);
}
err = util_create_path(udev, filename);
if (err != 0 && err != -ENOENT)
break;
fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
if (fd >= 0)
close(fd);
else
err = -errno;
} while (err == -ENOENT);
}
}
void udev_node_update_old_links(struct udev_device *dev, struct udev_device *dev_old)
{
struct udev *udev = udev_device_get_udev(dev);
struct udev_list_entry *list_entry;
struct udev *udev = udev_device_get_udev(dev);
struct udev_list_entry *list_entry;
/* update possible left-over symlinks */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev_old)) {
const char *name = udev_list_entry_get_name(list_entry);
struct udev_list_entry *list_entry_current;
int found;
/* update possible left-over symlinks */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev_old)) {
const char *name = udev_list_entry_get_name(list_entry);
struct udev_list_entry *list_entry_current;
int found;
/* check if old link name still belongs to this device */
found = 0;
udev_list_entry_foreach(list_entry_current, udev_device_get_devlinks_list_entry(dev)) {
const char *name_current = udev_list_entry_get_name(list_entry_current);
/* check if old link name still belongs to this device */
found = 0;
udev_list_entry_foreach(list_entry_current, udev_device_get_devlinks_list_entry(dev)) {
const char *name_current = udev_list_entry_get_name(list_entry_current);
if (strcmp(name, name_current) == 0) {
found = 1;
break;
}
}
if (found)
continue;
if (strcmp(name, name_current) == 0) {
found = 1;
break;
}
}
if (found)
continue;
info(udev, "update old name, '%s' no longer belonging to '%s'\n",
name, udev_device_get_devpath(dev));
link_update(dev, name, 0);
}
info(udev, "update old name, '%s' no longer belonging to '%s'\n",
name, udev_device_get_devpath(dev));
link_update(dev, name, 0);
}
}
static int node_fixup(struct udev_device *dev, mode_t mode, uid_t uid, gid_t gid)
{
struct udev *udev = udev_device_get_udev(dev);
const char *devnode = udev_device_get_devnode(dev);
dev_t devnum = udev_device_get_devnum(dev);
struct stat stats;
int err = 0;
struct udev *udev = udev_device_get_udev(dev);
const char *devnode = udev_device_get_devnode(dev);
dev_t devnum = udev_device_get_devnum(dev);
struct stat stats;
int err = 0;
if (strcmp(udev_device_get_subsystem(dev), "block") == 0)
mode |= S_IFBLK;
else
mode |= S_IFCHR;
if (strcmp(udev_device_get_subsystem(dev), "block") == 0)
mode |= S_IFBLK;
else
mode |= S_IFCHR;
if (lstat(devnode, &stats) != 0) {
err = -errno;
info(udev, "can not stat() node '%s' (%m)\n", devnode);
goto out;
}
if (lstat(devnode, &stats) != 0) {
err = -errno;
info(udev, "can not stat() node '%s' (%m)\n", devnode);
goto out;
}
if (((stats.st_mode & S_IFMT) != (mode & S_IFMT)) || (stats.st_rdev != devnum)) {
err = -EEXIST;
info(udev, "found node '%s' with non-matching devnum %s, skip handling\n",
udev_device_get_devnode(dev), udev_device_get_id_filename(dev));
goto out;
}
if (((stats.st_mode & S_IFMT) != (mode & S_IFMT)) || (stats.st_rdev != devnum)) {
err = -EEXIST;
info(udev, "found node '%s' with non-matching devnum %s, skip handling\n",
udev_device_get_devnode(dev), udev_device_get_id_filename(dev));
goto out;
}
if ((stats.st_mode & 0777) != (mode & 0777) || stats.st_uid != uid || stats.st_gid != gid) {
info(udev, "set permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
chmod(devnode, mode);
chown(devnode, uid, gid);
} else {
info(udev, "preserve permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
}
if ((stats.st_mode & 0777) != (mode & 0777) || stats.st_uid != uid || stats.st_gid != gid) {
info(udev, "set permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
chmod(devnode, mode);
chown(devnode, uid, gid);
} else {
info(udev, "preserve permissions %s, %#o, uid=%u, gid=%u\n", devnode, mode, uid, gid);
}
/*
* Set initial selinux file context only on add events.
* We set the proper context on bootup (triger) or for newly
* added devices, but we don't change it later, in case
* something else has set a custom context in the meantime.
*/
if (strcmp(udev_device_get_action(dev), "add") == 0)
udev_selinux_lsetfilecon(udev, devnode, mode);
/*
* Set initial selinux file context only on add events.
* We set the proper context on bootup (triger) or for newly
* added devices, but we don't change it later, in case
* something else has set a custom context in the meantime.
*/
if (strcmp(udev_device_get_action(dev), "add") == 0)
udev_selinux_lsetfilecon(udev, devnode, mode);
/* always update timestamp when we re-use the node, like on media change events */
utimensat(AT_FDCWD, devnode, NULL, 0);
/* always update timestamp when we re-use the node, like on media change events */
utimensat(AT_FDCWD, devnode, NULL, 0);
out:
return err;
return err;
}
int udev_node_add(struct udev_device *dev, mode_t mode, uid_t uid, gid_t gid)
{
struct udev *udev = udev_device_get_udev(dev);
char filename[UTIL_PATH_SIZE];
struct udev_list_entry *list_entry;
int err = 0;
struct udev *udev = udev_device_get_udev(dev);
char filename[UTIL_PATH_SIZE];
struct udev_list_entry *list_entry;
int err = 0;
info(udev, "handling device node '%s', devnum=%s, mode=%#o, uid=%d, gid=%d\n",
udev_device_get_devnode(dev), udev_device_get_id_filename(dev), mode, uid, gid);
info(udev, "handling device node '%s', devnum=%s, mode=%#o, uid=%d, gid=%d\n",
udev_device_get_devnode(dev), udev_device_get_id_filename(dev), mode, uid, gid);
err = node_fixup(dev, mode, uid, gid);
if (err < 0)
goto exit;
err = node_fixup(dev, mode, uid, gid);
if (err < 0)
goto exit;
/* always add /dev/{block,char}/$major:$minor */
snprintf(filename, sizeof(filename), "%s/%s/%u:%u",
udev_get_dev_path(udev),
strcmp(udev_device_get_subsystem(dev), "block") == 0 ? "block" : "char",
major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
node_symlink(udev, udev_device_get_devnode(dev), filename);
/* always add /dev/{block,char}/$major:$minor */
snprintf(filename, sizeof(filename), "%s/%s/%u:%u",
udev_get_dev_path(udev),
strcmp(udev_device_get_subsystem(dev), "block") == 0 ? "block" : "char",
major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
node_symlink(udev, udev_device_get_devnode(dev), filename);
/* create/update symlinks, add symlinks to name index */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev)) {
if (udev_list_entry_get_num(list_entry))
/* simple unmanaged link name */
node_symlink(udev, udev_device_get_devnode(dev), udev_list_entry_get_name(list_entry));
else
link_update(dev, udev_list_entry_get_name(list_entry), 1);
}
/* create/update symlinks, add symlinks to name index */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev)) {
if (udev_list_entry_get_num(list_entry))
/* simple unmanaged link name */
node_symlink(udev, udev_device_get_devnode(dev), udev_list_entry_get_name(list_entry));
else
link_update(dev, udev_list_entry_get_name(list_entry), 1);
}
exit:
return err;
return err;
}
int udev_node_remove(struct udev_device *dev)
{
struct udev *udev = udev_device_get_udev(dev);
struct udev_list_entry *list_entry;
const char *devnode;
struct stat stats;
struct udev_device *dev_check;
char filename[UTIL_PATH_SIZE];
int err = 0;
struct udev *udev = udev_device_get_udev(dev);
struct udev_list_entry *list_entry;
const char *devnode;
struct stat stats;
struct udev_device *dev_check;
char filename[UTIL_PATH_SIZE];
int err = 0;
/* remove/update symlinks, remove symlinks from name index */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
link_update(dev, udev_list_entry_get_name(list_entry), 0);
/* remove/update symlinks, remove symlinks from name index */
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
link_update(dev, udev_list_entry_get_name(list_entry), 0);
/* remove /dev/{block,char}/$major:$minor */
snprintf(filename, sizeof(filename), "%s/%s/%u:%u",
udev_get_dev_path(udev),
strcmp(udev_device_get_subsystem(dev), "block") == 0 ? "block" : "char",
major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
unlink(filename);
/* remove /dev/{block,char}/$major:$minor */
snprintf(filename, sizeof(filename), "%s/%s/%u:%u",
udev_get_dev_path(udev),
strcmp(udev_device_get_subsystem(dev), "block") == 0 ? "block" : "char",
major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
unlink(filename);
out:
return err;
return err;
}
+2310 -2310
View File
File diff suppressed because it is too large Load Diff
+87 -87
View File
@@ -38,10 +38,10 @@ static int inotify_fd = -1;
*/
int udev_watch_init(struct udev *udev)
{
inotify_fd = inotify_init1(IN_CLOEXEC);
if (inotify_fd < 0)
err(udev, "inotify_init failed: %m\n");
return inotify_fd;
inotify_fd = inotify_init1(IN_CLOEXEC);
if (inotify_fd < 0)
err(udev, "inotify_init failed: %m\n");
return inotify_fd;
}
/* move any old watches directory out of the way, and then restore
@@ -49,122 +49,122 @@ int udev_watch_init(struct udev *udev)
*/
void udev_watch_restore(struct udev *udev)
{
char filename[UTIL_PATH_SIZE], oldname[UTIL_PATH_SIZE];
char filename[UTIL_PATH_SIZE], oldname[UTIL_PATH_SIZE];
if (inotify_fd < 0)
return;
if (inotify_fd < 0)
return;
util_strscpyl(oldname, sizeof(oldname), udev_get_run_path(udev), "/watch.old", NULL);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/watch", NULL);
if (rename(filename, oldname) == 0) {
DIR *dir;
struct dirent *ent;
util_strscpyl(oldname, sizeof(oldname), udev_get_run_path(udev), "/watch.old", NULL);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/watch", NULL);
if (rename(filename, oldname) == 0) {
DIR *dir;
struct dirent *ent;
dir = opendir(oldname);
if (dir == NULL) {
err(udev, "unable to open old watches dir '%s', old watches will not be restored: %m", oldname);
return;
}
dir = opendir(oldname);
if (dir == NULL) {
err(udev, "unable to open old watches dir '%s', old watches will not be restored: %m", oldname);
return;
}
for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
char device[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
struct udev_device *dev;
for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
char device[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
struct udev_device *dev;
if (ent->d_name[0] == '.')
continue;
if (ent->d_name[0] == '.')
continue;
s = device;
l = util_strpcpy(&s, sizeof(device), udev_get_sys_path(udev));
len = readlinkat(dirfd(dir), ent->d_name, s, l);
if (len <= 0 || len == (ssize_t)l)
goto unlink;
s[len] = '\0';
s = device;
l = util_strpcpy(&s, sizeof(device), udev_get_sys_path(udev));
len = readlinkat(dirfd(dir), ent->d_name, s, l);
if (len <= 0 || len == (ssize_t)l)
goto unlink;
s[len] = '\0';
dev = udev_device_new_from_id_filename(udev, s);
if (dev == NULL)
goto unlink;
dev = udev_device_new_from_id_filename(udev, s);
if (dev == NULL)
goto unlink;
info(udev, "restoring old watch on '%s'\n", udev_device_get_devnode(dev));
udev_watch_begin(udev, dev);
udev_device_unref(dev);
info(udev, "restoring old watch on '%s'\n", udev_device_get_devnode(dev));
udev_watch_begin(udev, dev);
udev_device_unref(dev);
unlink:
unlinkat(dirfd(dir), ent->d_name, 0);
}
unlinkat(dirfd(dir), ent->d_name, 0);
}
closedir(dir);
rmdir(oldname);
closedir(dir);
rmdir(oldname);
} else if (errno != ENOENT) {
err(udev, "unable to move watches dir '%s', old watches will not be restored: %m", filename);
}
} else if (errno != ENOENT) {
err(udev, "unable to move watches dir '%s', old watches will not be restored: %m", filename);
}
}
void udev_watch_begin(struct udev *udev, struct udev_device *dev)
{
char filename[UTIL_PATH_SIZE];
int wd;
char filename[UTIL_PATH_SIZE];
int wd;
if (inotify_fd < 0)
return;
if (inotify_fd < 0)
return;
info(udev, "adding watch on '%s'\n", udev_device_get_devnode(dev));
wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
if (wd < 0) {
err(udev, "inotify_add_watch(%d, %s, %o) failed: %m\n",
inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
return;
}
info(udev, "adding watch on '%s'\n", udev_device_get_devnode(dev));
wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
if (wd < 0) {
err(udev, "inotify_add_watch(%d, %s, %o) failed: %m\n",
inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE);
return;
}
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
util_create_path(udev, filename);
unlink(filename);
symlink(udev_device_get_id_filename(dev), filename);
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
util_create_path(udev, filename);
unlink(filename);
symlink(udev_device_get_id_filename(dev), filename);
udev_device_set_watch_handle(dev, wd);
udev_device_set_watch_handle(dev, wd);
}
void udev_watch_end(struct udev *udev, struct udev_device *dev)
{
int wd;
char filename[UTIL_PATH_SIZE];
int wd;
char filename[UTIL_PATH_SIZE];
if (inotify_fd < 0)
return;
if (inotify_fd < 0)
return;
wd = udev_device_get_watch_handle(dev);
if (wd < 0)
return;
wd = udev_device_get_watch_handle(dev);
if (wd < 0)
return;
info(udev, "removing watch on '%s'\n", udev_device_get_devnode(dev));
inotify_rm_watch(inotify_fd, wd);
info(udev, "removing watch on '%s'\n", udev_device_get_devnode(dev));
inotify_rm_watch(inotify_fd, wd);
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
unlink(filename);
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
unlink(filename);
udev_device_set_watch_handle(dev, -1);
udev_device_set_watch_handle(dev, -1);
}
struct udev_device *udev_watch_lookup(struct udev *udev, int wd)
{
char filename[UTIL_PATH_SIZE];
char majmin[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
char filename[UTIL_PATH_SIZE];
char majmin[UTIL_PATH_SIZE];
char *s;
size_t l;
ssize_t len;
if (inotify_fd < 0 || wd < 0)
return NULL;
if (inotify_fd < 0 || wd < 0)
return NULL;
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
s = majmin;
l = util_strpcpy(&s, sizeof(majmin), udev_get_sys_path(udev));
len = readlink(filename, s, l);
if (len <= 0 || (size_t)len == l)
return NULL;
s[len] = '\0';
snprintf(filename, sizeof(filename), "%s/watch/%d", udev_get_run_path(udev), wd);
s = majmin;
l = util_strpcpy(&s, sizeof(majmin), udev_get_sys_path(udev));
len = readlink(filename, s, l);
if (len <= 0 || (size_t)len == l)
return NULL;
s[len] = '\0';
return udev_device_new_from_id_filename(udev, s);
return udev_device_new_from_id_filename(udev, s);
}
+54 -54
View File
@@ -27,38 +27,38 @@
#include "libudev-private.h"
struct udev_event {
struct udev *udev;
struct udev_device *dev;
struct udev_device *dev_parent;
struct udev_device *dev_db;
char *name;
char *program_result;
mode_t mode;
uid_t uid;
gid_t gid;
struct udev_list run_list;
int exec_delay;
unsigned long long birth_usec;
unsigned long long timeout_usec;
int fd_signal;
unsigned int builtin_run;
unsigned int builtin_ret;
bool sigterm;
bool inotify_watch;
bool inotify_watch_final;
bool group_final;
bool owner_final;
bool mode_set;
bool mode_final;
bool name_final;
bool devlink_final;
bool run_final;
struct udev *udev;
struct udev_device *dev;
struct udev_device *dev_parent;
struct udev_device *dev_db;
char *name;
char *program_result;
mode_t mode;
uid_t uid;
gid_t gid;
struct udev_list run_list;
int exec_delay;
unsigned long long birth_usec;
unsigned long long timeout_usec;
int fd_signal;
unsigned int builtin_run;
unsigned int builtin_ret;
bool sigterm;
bool inotify_watch;
bool inotify_watch_final;
bool group_final;
bool owner_final;
bool mode_set;
bool mode_final;
bool name_final;
bool devlink_final;
bool run_final;
};
struct udev_watch {
struct udev_list_node node;
int handle;
char *name;
struct udev_list_node node;
int handle;
char *name;
};
/* udev-rules.c */
@@ -73,10 +73,10 @@ struct udev_event *udev_event_new(struct udev_device *dev);
void udev_event_unref(struct udev_event *event);
size_t udev_event_apply_format(struct udev_event *event, const char *src, char *dest, size_t size);
int udev_event_apply_subsys_kernel(struct udev_event *event, const char *string,
char *result, size_t maxsize, int read_value);
char *result, size_t maxsize, int read_value);
int udev_event_spawn(struct udev_event *event,
const char *cmd, char **envp, const sigset_t *sigmask,
char *result, size_t ressize);
const char *cmd, char **envp, const sigset_t *sigmask,
char *result, size_t ressize);
int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigset);
int udev_event_execute_run(struct udev_event *event, const sigset_t *sigset);
int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]);
@@ -130,24 +130,24 @@ int udev_ctrl_get_set_children_max(struct udev_ctrl_msg *ctrl_msg);
/* built-in commands */
enum udev_builtin_cmd {
UDEV_BUILTIN_BLKID,
UDEV_BUILTIN_FIRMWARE,
UDEV_BUILTIN_INPUT_ID,
UDEV_BUILTIN_KMOD,
UDEV_BUILTIN_PATH_ID,
UDEV_BUILTIN_PCI_DB,
UDEV_BUILTIN_USB_DB,
UDEV_BUILTIN_USB_ID,
UDEV_BUILTIN_MAX
UDEV_BUILTIN_BLKID,
UDEV_BUILTIN_FIRMWARE,
UDEV_BUILTIN_INPUT_ID,
UDEV_BUILTIN_KMOD,
UDEV_BUILTIN_PATH_ID,
UDEV_BUILTIN_PCI_DB,
UDEV_BUILTIN_USB_DB,
UDEV_BUILTIN_USB_ID,
UDEV_BUILTIN_MAX
};
struct udev_builtin {
const char *name;
int (*cmd)(struct udev_device *dev, int argc, char *argv[], bool test);
const char *help;
int (*init)(struct udev *udev);
void (*exit)(struct udev *udev);
bool (*validate)(struct udev *udev);
bool run_once;
const char *name;
int (*cmd)(struct udev_device *dev, int argc, char *argv[], bool test);
const char *help;
int (*init)(struct udev *udev);
void (*exit)(struct udev *udev);
bool (*validate)(struct udev *udev);
bool run_once;
};
extern const struct udev_builtin udev_builtin_blkid;
extern const struct udev_builtin udev_builtin_firmware;
@@ -168,15 +168,15 @@ int udev_builtin_add_property(struct udev_device *dev, bool test, const char *ke
/* udev logging */
void udev_main_log(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args);
const char *file, int line, const char *fn,
const char *format, va_list args);
/* udevadm commands */
struct udevadm_cmd {
const char *name;
int (*cmd)(struct udev *udev, int argc, char *argv[]);
const char *help;
int debug;
const char *name;
int (*cmd)(struct udev *udev, int argc, char *argv[]);
const char *help;
int debug;
};
extern const struct udevadm_cmd udevadm_info;
extern const struct udevadm_cmd udevadm_trigger;
+125 -125
View File
@@ -29,147 +29,147 @@
static void print_help(void)
{
printf("Usage: udevadm control COMMAND\n"
" --exit instruct the daemon to cleanup and exit\n"
" --log-priority=<level> set the udev log level for the daemon\n"
" --stop-exec-queue do not execute events, queue only\n"
" --start-exec-queue execute events, flush queue\n"
" --reload reload rules and databases\n"
" --property=<KEY>=<value> set a global property for all events\n"
" --children-max=<N> maximum number of children\n"
" --timeout=<seconds> maximum time to block for a reply\n"
" --help print this help text\n\n");
printf("Usage: udevadm control COMMAND\n"
" --exit instruct the daemon to cleanup and exit\n"
" --log-priority=<level> set the udev log level for the daemon\n"
" --stop-exec-queue do not execute events, queue only\n"
" --start-exec-queue execute events, flush queue\n"
" --reload reload rules and databases\n"
" --property=<KEY>=<value> set a global property for all events\n"
" --children-max=<N> maximum number of children\n"
" --timeout=<seconds> maximum time to block for a reply\n"
" --help print this help text\n\n");
}
static int adm_control(struct udev *udev, int argc, char *argv[])
{
struct udev_ctrl *uctrl = NULL;
int timeout = 60;
int rc = 1;
struct udev_ctrl *uctrl = NULL;
int timeout = 60;
int rc = 1;
static const struct option options[] = {
{ "exit", no_argument, NULL, 'e' },
{ "log-priority", required_argument, NULL, 'l' },
{ "stop-exec-queue", no_argument, NULL, 's' },
{ "start-exec-queue", no_argument, NULL, 'S' },
{ "reload", no_argument, NULL, 'R' },
{ "reload-rules", no_argument, NULL, 'R' },
{ "property", required_argument, NULL, 'p' },
{ "env", required_argument, NULL, 'p' },
{ "children-max", required_argument, NULL, 'm' },
{ "timeout", required_argument, NULL, 't' },
{ "help", no_argument, NULL, 'h' },
{}
};
static const struct option options[] = {
{ "exit", no_argument, NULL, 'e' },
{ "log-priority", required_argument, NULL, 'l' },
{ "stop-exec-queue", no_argument, NULL, 's' },
{ "start-exec-queue", no_argument, NULL, 'S' },
{ "reload", no_argument, NULL, 'R' },
{ "reload-rules", no_argument, NULL, 'R' },
{ "property", required_argument, NULL, 'p' },
{ "env", required_argument, NULL, 'p' },
{ "children-max", required_argument, NULL, 'm' },
{ "timeout", required_argument, NULL, 't' },
{ "help", no_argument, NULL, 'h' },
{}
};
if (getuid() != 0) {
fprintf(stderr, "root privileges required\n");
return 1;
}
if (getuid() != 0) {
fprintf(stderr, "root privileges required\n");
return 1;
}
uctrl = udev_ctrl_new(udev);
if (uctrl == NULL)
return 2;
uctrl = udev_ctrl_new(udev);
if (uctrl == NULL)
return 2;
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "el:sSRp:m:h", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "el:sSRp:m:h", options, NULL);
if (option == -1)
break;
switch (option) {
case 'e':
if (udev_ctrl_send_exit(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'l': {
int i;
switch (option) {
case 'e':
if (udev_ctrl_send_exit(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'l': {
int i;
i = util_log_priority(optarg);
if (i < 0) {
fprintf(stderr, "invalid number '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_log_level(uctrl, util_log_priority(optarg), timeout) < 0)
rc = 2;
else
rc = 0;
break;
}
case 's':
if (udev_ctrl_send_stop_exec_queue(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'S':
if (udev_ctrl_send_start_exec_queue(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'R':
if (udev_ctrl_send_reload(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'p':
if (strchr(optarg, '=') == NULL) {
fprintf(stderr, "expect <KEY>=<value> instead of '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_env(uctrl, optarg, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'm': {
char *endp;
int i;
i = util_log_priority(optarg);
if (i < 0) {
fprintf(stderr, "invalid number '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_log_level(uctrl, util_log_priority(optarg), timeout) < 0)
rc = 2;
else
rc = 0;
break;
}
case 's':
if (udev_ctrl_send_stop_exec_queue(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'S':
if (udev_ctrl_send_start_exec_queue(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'R':
if (udev_ctrl_send_reload(uctrl, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'p':
if (strchr(optarg, '=') == NULL) {
fprintf(stderr, "expect <KEY>=<value> instead of '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_env(uctrl, optarg, timeout) < 0)
rc = 2;
else
rc = 0;
break;
case 'm': {
char *endp;
int i;
i = strtoul(optarg, &endp, 0);
if (endp[0] != '\0' || i < 1) {
fprintf(stderr, "invalid number '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_children_max(uctrl, i, timeout) < 0)
rc = 2;
else
rc = 0;
break;
}
case 't': {
int seconds;
i = strtoul(optarg, &endp, 0);
if (endp[0] != '\0' || i < 1) {
fprintf(stderr, "invalid number '%s'\n", optarg);
goto out;
}
if (udev_ctrl_send_set_children_max(uctrl, i, timeout) < 0)
rc = 2;
else
rc = 0;
break;
}
case 't': {
int seconds;
seconds = atoi(optarg);
if (seconds >= 0)
timeout = seconds;
else
fprintf(stderr, "invalid timeout value\n");
break;
}
case 'h':
print_help();
rc = 0;
break;
}
}
seconds = atoi(optarg);
if (seconds >= 0)
timeout = seconds;
else
fprintf(stderr, "invalid timeout value\n");
break;
}
case 'h':
print_help();
rc = 0;
break;
}
}
if (argv[optind] != NULL)
fprintf(stderr, "unknown option\n");
else if (optind == 1)
fprintf(stderr, "missing option\n");
if (argv[optind] != NULL)
fprintf(stderr, "unknown option\n");
else if (optind == 1)
fprintf(stderr, "missing option\n");
out:
udev_ctrl_unref(uctrl);
return rc;
udev_ctrl_unref(uctrl);
return rc;
}
const struct udevadm_cmd udevadm_control = {
.name = "control",
.cmd = adm_control,
.help = "control the udev daemon",
.name = "control",
.cmd = adm_control,
.help = "control the udev daemon",
};
+451 -451
View File
@@ -33,536 +33,536 @@
static bool skip_attribute(const char *name)
{
static const char const *skip[] = {
"uevent",
"dev",
"modalias",
"resource",
"driver",
"subsystem",
"module",
};
unsigned int i;
static const char const *skip[] = {
"uevent",
"dev",
"modalias",
"resource",
"driver",
"subsystem",
"module",
};
unsigned int i;
for (i = 0; i < ARRAY_SIZE(skip); i++)
if (strcmp(name, skip[i]) == 0)
return true;
return false;
for (i = 0; i < ARRAY_SIZE(skip); i++)
if (strcmp(name, skip[i]) == 0)
return true;
return false;
}
static void print_all_attributes(struct udev_device *device, const char *key)
{
struct udev *udev = udev_device_get_udev(device);
struct udev_list_entry *sysattr;
struct udev *udev = udev_device_get_udev(device);
struct udev_list_entry *sysattr;
udev_list_entry_foreach(sysattr, udev_device_get_sysattr_list_entry(device)) {
const char *name;
const char *value;
size_t len;
udev_list_entry_foreach(sysattr, udev_device_get_sysattr_list_entry(device)) {
const char *name;
const char *value;
size_t len;
name = udev_list_entry_get_name(sysattr);
if (skip_attribute(name))
continue;
name = udev_list_entry_get_name(sysattr);
if (skip_attribute(name))
continue;
value = udev_device_get_sysattr_value(device, name);
if (value == NULL)
continue;
dbg(udev, "attr '%s'='%s'\n", name, value);
value = udev_device_get_sysattr_value(device, name);
if (value == NULL)
continue;
dbg(udev, "attr '%s'='%s'\n", name, value);
/* skip any values that look like a path */
if (value[0] == '/')
continue;
/* skip any values that look like a path */
if (value[0] == '/')
continue;
/* skip nonprintable attributes */
len = strlen(value);
while (len > 0 && isprint(value[len-1]))
len--;
if (len > 0) {
dbg(udev, "attribute value of '%s' non-printable, skip\n", name);
continue;
}
/* skip nonprintable attributes */
len = strlen(value);
while (len > 0 && isprint(value[len-1]))
len--;
if (len > 0) {
dbg(udev, "attribute value of '%s' non-printable, skip\n", name);
continue;
}
printf(" %s{%s}==\"%s\"\n", key, name, value);
}
printf("\n");
printf(" %s{%s}==\"%s\"\n", key, name, value);
}
printf("\n");
}
static int print_device_chain(struct udev_device *device)
{
struct udev_device *device_parent;
const char *str;
struct udev_device *device_parent;
const char *str;
printf("\n"
"Udevadm info starts with the device specified by the devpath and then\n"
"walks up the chain of parent devices. It prints for every device\n"
"found, all possible attributes in the udev rules key format.\n"
"A rule to match, can be composed by the attributes of the device\n"
"and the attributes from one single parent device.\n"
"\n");
printf("\n"
"Udevadm info starts with the device specified by the devpath and then\n"
"walks up the chain of parent devices. It prints for every device\n"
"found, all possible attributes in the udev rules key format.\n"
"A rule to match, can be composed by the attributes of the device\n"
"and the attributes from one single parent device.\n"
"\n");
printf(" looking at device '%s':\n", udev_device_get_devpath(device));
printf(" KERNEL==\"%s\"\n", udev_device_get_sysname(device));
str = udev_device_get_subsystem(device);
if (str == NULL)
str = "";
printf(" SUBSYSTEM==\"%s\"\n", str);
str = udev_device_get_driver(device);
if (str == NULL)
str = "";
printf(" DRIVER==\"%s\"\n", str);
print_all_attributes(device, "ATTR");
printf(" looking at device '%s':\n", udev_device_get_devpath(device));
printf(" KERNEL==\"%s\"\n", udev_device_get_sysname(device));
str = udev_device_get_subsystem(device);
if (str == NULL)
str = "";
printf(" SUBSYSTEM==\"%s\"\n", str);
str = udev_device_get_driver(device);
if (str == NULL)
str = "";
printf(" DRIVER==\"%s\"\n", str);
print_all_attributes(device, "ATTR");
device_parent = device;
do {
device_parent = udev_device_get_parent(device_parent);
if (device_parent == NULL)
break;
printf(" looking at parent device '%s':\n", udev_device_get_devpath(device_parent));
printf(" KERNELS==\"%s\"\n", udev_device_get_sysname(device_parent));
str = udev_device_get_subsystem(device_parent);
if (str == NULL)
str = "";
printf(" SUBSYSTEMS==\"%s\"\n", str);
str = udev_device_get_driver(device_parent);
if (str == NULL)
str = "";
printf(" DRIVERS==\"%s\"\n", str);
print_all_attributes(device_parent, "ATTRS");
} while (device_parent != NULL);
device_parent = device;
do {
device_parent = udev_device_get_parent(device_parent);
if (device_parent == NULL)
break;
printf(" looking at parent device '%s':\n", udev_device_get_devpath(device_parent));
printf(" KERNELS==\"%s\"\n", udev_device_get_sysname(device_parent));
str = udev_device_get_subsystem(device_parent);
if (str == NULL)
str = "";
printf(" SUBSYSTEMS==\"%s\"\n", str);
str = udev_device_get_driver(device_parent);
if (str == NULL)
str = "";
printf(" DRIVERS==\"%s\"\n", str);
print_all_attributes(device_parent, "ATTRS");
} while (device_parent != NULL);
return 0;
return 0;
}
static void print_record(struct udev_device *device)
{
size_t len;
const char *str;
int i;
struct udev_list_entry *list_entry;
size_t len;
const char *str;
int i;
struct udev_list_entry *list_entry;
printf("P: %s\n", udev_device_get_devpath(device));
printf("P: %s\n", udev_device_get_devpath(device));
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
str = udev_device_get_devnode(device);
if (str != NULL)
printf("N: %s\n", &str[len+1]);
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
str = udev_device_get_devnode(device);
if (str != NULL)
printf("N: %s\n", &str[len+1]);
i = udev_device_get_devlink_priority(device);
if (i != 0)
printf("L: %i\n", i);
i = udev_device_get_devlink_priority(device);
if (i != 0)
printf("L: %i\n", i);
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
printf("S: %s\n", &udev_list_entry_get_name(list_entry)[len+1]);
}
udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(device)) {
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
printf("S: %s\n", &udev_list_entry_get_name(list_entry)[len+1]);
}
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
printf("E: %s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
printf("\n");
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
printf("E: %s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
printf("\n");
}
static int stat_device(const char *name, bool export, const char *prefix)
{
struct stat statbuf;
struct stat statbuf;
if (stat(name, &statbuf) != 0)
return -1;
if (stat(name, &statbuf) != 0)
return -1;
if (export) {
if (prefix == NULL)
prefix = "INFO_";
printf("%sMAJOR=%d\n"
"%sMINOR=%d\n",
prefix, major(statbuf.st_dev),
prefix, minor(statbuf.st_dev));
} else
printf("%d:%d\n", major(statbuf.st_dev), minor(statbuf.st_dev));
return 0;
if (export) {
if (prefix == NULL)
prefix = "INFO_";
printf("%sMAJOR=%d\n"
"%sMINOR=%d\n",
prefix, major(statbuf.st_dev),
prefix, minor(statbuf.st_dev));
} else
printf("%d:%d\n", major(statbuf.st_dev), minor(statbuf.st_dev));
return 0;
}
static int export_devices(struct udev *udev)
{
struct udev_enumerate *udev_enumerate;
struct udev_list_entry *list_entry;
struct udev_enumerate *udev_enumerate;
struct udev_list_entry *list_entry;
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_scan_devices(udev_enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
struct udev_device *device;
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL)
return -1;
udev_enumerate_scan_devices(udev_enumerate);
udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(udev_enumerate)) {
struct udev_device *device;
device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
if (device != NULL) {
print_record(device);
udev_device_unref(device);
}
}
udev_enumerate_unref(udev_enumerate);
return 0;
device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(list_entry));
if (device != NULL) {
print_record(device);
udev_device_unref(device);
}
}
udev_enumerate_unref(udev_enumerate);
return 0;
}
static void cleanup_dir(DIR *dir, mode_t mask, int depth)
{
struct dirent *dent;
struct dirent *dent;
if (depth <= 0)
return;
if (depth <= 0)
return;
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
struct stat stats;
for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
struct stat stats;
if (dent->d_name[0] == '.')
continue;
if (fstatat(dirfd(dir), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
continue;
if ((stats.st_mode & mask) != 0)
continue;
if (S_ISDIR(stats.st_mode)) {
DIR *dir2;
if (dent->d_name[0] == '.')
continue;
if (fstatat(dirfd(dir), dent->d_name, &stats, AT_SYMLINK_NOFOLLOW) != 0)
continue;
if ((stats.st_mode & mask) != 0)
continue;
if (S_ISDIR(stats.st_mode)) {
DIR *dir2;
dir2 = fdopendir(openat(dirfd(dir), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
if (dir2 != NULL) {
cleanup_dir(dir2, mask, depth-1);
closedir(dir2);
}
unlinkat(dirfd(dir), dent->d_name, AT_REMOVEDIR);
} else {
unlinkat(dirfd(dir), dent->d_name, 0);
}
}
dir2 = fdopendir(openat(dirfd(dir), dent->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
if (dir2 != NULL) {
cleanup_dir(dir2, mask, depth-1);
closedir(dir2);
}
unlinkat(dirfd(dir), dent->d_name, AT_REMOVEDIR);
} else {
unlinkat(dirfd(dir), dent->d_name, 0);
}
}
}
static void cleanup_db(struct udev *udev)
{
char filename[UTIL_PATH_SIZE];
DIR *dir;
char filename[UTIL_PATH_SIZE];
DIR *dir;
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/queue.bin", NULL);
unlink(filename);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/queue.bin", NULL);
unlink(filename);
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, S_ISVTX, 1);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/data", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, S_ISVTX, 1);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/links", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 2);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/links", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 2);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/tags", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 2);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/tags", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 2);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/watch", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 1);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/watch", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 1);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/firmware-missing", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 1);
closedir(dir);
}
util_strscpyl(filename, sizeof(filename), udev_get_run_path(udev), "/firmware-missing", NULL);
dir = opendir(filename);
if (dir != NULL) {
cleanup_dir(dir, 0, 1);
closedir(dir);
}
}
static int uinfo(struct udev *udev, int argc, char *argv[])
{
struct udev_device *device = NULL;
bool root = 0;
bool export = 0;
const char *export_prefix = NULL;
char path[UTIL_PATH_SIZE];
char name[UTIL_PATH_SIZE];
struct udev_list_entry *list_entry;
int rc = 0;
struct udev_device *device = NULL;
bool root = 0;
bool export = 0;
const char *export_prefix = NULL;
char path[UTIL_PATH_SIZE];
char name[UTIL_PATH_SIZE];
struct udev_list_entry *list_entry;
int rc = 0;
static const struct option options[] = {
{ "name", required_argument, NULL, 'n' },
{ "path", required_argument, NULL, 'p' },
{ "query", required_argument, NULL, 'q' },
{ "attribute-walk", no_argument, NULL, 'a' },
{ "cleanup-db", no_argument, NULL, 'c' },
{ "export-db", no_argument, NULL, 'e' },
{ "root", no_argument, NULL, 'r' },
{ "run", no_argument, NULL, 'R' },
{ "device-id-of-file", required_argument, NULL, 'd' },
{ "export", no_argument, NULL, 'x' },
{ "export-prefix", required_argument, NULL, 'P' },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{}
};
static const struct option options[] = {
{ "name", required_argument, NULL, 'n' },
{ "path", required_argument, NULL, 'p' },
{ "query", required_argument, NULL, 'q' },
{ "attribute-walk", no_argument, NULL, 'a' },
{ "cleanup-db", no_argument, NULL, 'c' },
{ "export-db", no_argument, NULL, 'e' },
{ "root", no_argument, NULL, 'r' },
{ "run", no_argument, NULL, 'R' },
{ "device-id-of-file", required_argument, NULL, 'd' },
{ "export", no_argument, NULL, 'x' },
{ "export-prefix", required_argument, NULL, 'P' },
{ "version", no_argument, NULL, 'V' },
{ "help", no_argument, NULL, 'h' },
{}
};
enum action_type {
ACTION_NONE,
ACTION_QUERY,
ACTION_ATTRIBUTE_WALK,
ACTION_ROOT,
ACTION_DEVICE_ID_FILE,
} action = ACTION_NONE;
enum action_type {
ACTION_NONE,
ACTION_QUERY,
ACTION_ATTRIBUTE_WALK,
ACTION_ROOT,
ACTION_DEVICE_ID_FILE,
} action = ACTION_NONE;
enum query_type {
QUERY_NONE,
QUERY_NAME,
QUERY_PATH,
QUERY_SYMLINK,
QUERY_PROPERTY,
QUERY_ALL,
} query = QUERY_NONE;
enum query_type {
QUERY_NONE,
QUERY_NAME,
QUERY_PATH,
QUERY_SYMLINK,
QUERY_PROPERTY,
QUERY_ALL,
} query = QUERY_NONE;
for (;;) {
int option;
struct stat statbuf;
for (;;) {
int option;
struct stat statbuf;
option = getopt_long(argc, argv, "aced:n:p:q:rxP:RVh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "aced:n:p:q:rxP:RVh", options, NULL);
if (option == -1)
break;
dbg(udev, "option '%c'\n", option);
switch (option) {
case 'n':
if (device != NULL) {
fprintf(stderr, "device already specified\n");
rc = 2;
goto exit;
}
/* remove /dev if given */
if (strncmp(optarg, udev_get_dev_path(udev), strlen(udev_get_dev_path(udev))) != 0)
util_strscpyl(name, sizeof(name), udev_get_dev_path(udev), "/", optarg, NULL);
else
util_strscpy(name, sizeof(name), optarg);
util_remove_trailing_chars(name, '/');
if (stat(name, &statbuf) < 0) {
fprintf(stderr, "device node not found\n");
rc = 2;
goto exit;
} else {
char type;
dbg(udev, "option '%c'\n", option);
switch (option) {
case 'n':
if (device != NULL) {
fprintf(stderr, "device already specified\n");
rc = 2;
goto exit;
}
/* remove /dev if given */
if (strncmp(optarg, udev_get_dev_path(udev), strlen(udev_get_dev_path(udev))) != 0)
util_strscpyl(name, sizeof(name), udev_get_dev_path(udev), "/", optarg, NULL);
else
util_strscpy(name, sizeof(name), optarg);
util_remove_trailing_chars(name, '/');
if (stat(name, &statbuf) < 0) {
fprintf(stderr, "device node not found\n");
rc = 2;
goto exit;
} else {
char type;
if (S_ISBLK(statbuf.st_mode)) {
type = 'b';
} else if (S_ISCHR(statbuf.st_mode)) {
type = 'c';
} else {
fprintf(stderr, "device node has wrong file type\n");
rc = 2;
goto exit;
}
device = udev_device_new_from_devnum(udev, type, statbuf.st_rdev);
if (device == NULL) {
fprintf(stderr, "device node not found\n");
rc = 2;
goto exit;
}
}
break;
case 'p':
if (device != NULL) {
fprintf(stderr, "device already specified\n");
rc = 2;
goto exit;
}
/* add sys dir if needed */
if (strncmp(optarg, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), optarg, NULL);
else
util_strscpy(path, sizeof(path), optarg);
util_remove_trailing_chars(path, '/');
device = udev_device_new_from_syspath(udev, path);
if (device == NULL) {
fprintf(stderr, "device path not found\n");
rc = 2;
goto exit;
}
break;
case 'q':
action = ACTION_QUERY;
if (strcmp(optarg, "property") == 0 || strcmp(optarg, "env") == 0) {
query = QUERY_PROPERTY;
} else if (strcmp(optarg, "name") == 0) {
query = QUERY_NAME;
} else if (strcmp(optarg, "symlink") == 0) {
query = QUERY_SYMLINK;
} else if (strcmp(optarg, "path") == 0) {
query = QUERY_PATH;
} else if (strcmp(optarg, "all") == 0) {
query = QUERY_ALL;
} else {
fprintf(stderr, "unknown query type\n");
rc = 3;
goto exit;
}
break;
case 'r':
if (action == ACTION_NONE)
action = ACTION_ROOT;
root = true;
break;
case 'R':
printf("%s\n", udev_get_run_path(udev));
goto exit;
case 'd':
action = ACTION_DEVICE_ID_FILE;
util_strscpy(name, sizeof(name), optarg);
break;
case 'a':
action = ACTION_ATTRIBUTE_WALK;
break;
case 'e':
export_devices(udev);
goto exit;
case 'c':
cleanup_db(udev);
goto exit;
case 'x':
export = true;
break;
case 'P':
export_prefix = optarg;
break;
case 'V':
printf("%s\n", VERSION);
goto exit;
case 'h':
printf("Usage: udevadm info OPTIONS\n"
" --query=<type> query device information:\n"
" name name of device node\n"
" symlink pointing to node\n"
" path sys device path\n"
" property the device properties\n"
" all all values\n"
" --path=<syspath> sys device path used for query or attribute walk\n"
" --name=<name> node or symlink name used for query or attribute walk\n"
" --root prepend dev directory to path names\n"
" --attribute-walk print all key matches while walking along the chain\n"
" of parent devices\n"
" --device-id-of-file=<file> print major:minor of device containing this file\n"
" --export export key/value pairs\n"
" --export-prefix export the key name with a prefix\n"
" --export-db export the content of the udev database\n"
" --cleanup-db cleanup the udev database\n"
" --help\n\n");
goto exit;
default:
rc = 1;
goto exit;
}
}
if (S_ISBLK(statbuf.st_mode)) {
type = 'b';
} else if (S_ISCHR(statbuf.st_mode)) {
type = 'c';
} else {
fprintf(stderr, "device node has wrong file type\n");
rc = 2;
goto exit;
}
device = udev_device_new_from_devnum(udev, type, statbuf.st_rdev);
if (device == NULL) {
fprintf(stderr, "device node not found\n");
rc = 2;
goto exit;
}
}
break;
case 'p':
if (device != NULL) {
fprintf(stderr, "device already specified\n");
rc = 2;
goto exit;
}
/* add sys dir if needed */
if (strncmp(optarg, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), optarg, NULL);
else
util_strscpy(path, sizeof(path), optarg);
util_remove_trailing_chars(path, '/');
device = udev_device_new_from_syspath(udev, path);
if (device == NULL) {
fprintf(stderr, "device path not found\n");
rc = 2;
goto exit;
}
break;
case 'q':
action = ACTION_QUERY;
if (strcmp(optarg, "property") == 0 || strcmp(optarg, "env") == 0) {
query = QUERY_PROPERTY;
} else if (strcmp(optarg, "name") == 0) {
query = QUERY_NAME;
} else if (strcmp(optarg, "symlink") == 0) {
query = QUERY_SYMLINK;
} else if (strcmp(optarg, "path") == 0) {
query = QUERY_PATH;
} else if (strcmp(optarg, "all") == 0) {
query = QUERY_ALL;
} else {
fprintf(stderr, "unknown query type\n");
rc = 3;
goto exit;
}
break;
case 'r':
if (action == ACTION_NONE)
action = ACTION_ROOT;
root = true;
break;
case 'R':
printf("%s\n", udev_get_run_path(udev));
goto exit;
case 'd':
action = ACTION_DEVICE_ID_FILE;
util_strscpy(name, sizeof(name), optarg);
break;
case 'a':
action = ACTION_ATTRIBUTE_WALK;
break;
case 'e':
export_devices(udev);
goto exit;
case 'c':
cleanup_db(udev);
goto exit;
case 'x':
export = true;
break;
case 'P':
export_prefix = optarg;
break;
case 'V':
printf("%s\n", VERSION);
goto exit;
case 'h':
printf("Usage: udevadm info OPTIONS\n"
" --query=<type> query device information:\n"
" name name of device node\n"
" symlink pointing to node\n"
" path sys device path\n"
" property the device properties\n"
" all all values\n"
" --path=<syspath> sys device path used for query or attribute walk\n"
" --name=<name> node or symlink name used for query or attribute walk\n"
" --root prepend dev directory to path names\n"
" --attribute-walk print all key matches while walking along the chain\n"
" of parent devices\n"
" --device-id-of-file=<file> print major:minor of device containing this file\n"
" --export export key/value pairs\n"
" --export-prefix export the key name with a prefix\n"
" --export-db export the content of the udev database\n"
" --cleanup-db cleanup the udev database\n"
" --help\n\n");
goto exit;
default:
rc = 1;
goto exit;
}
}
switch (action) {
case ACTION_QUERY:
if (device == NULL) {
fprintf(stderr, "query needs a valid device specified by --path= or --name=\n");
rc = 4;
goto exit;
}
switch (action) {
case ACTION_QUERY:
if (device == NULL) {
fprintf(stderr, "query needs a valid device specified by --path= or --name=\n");
rc = 4;
goto exit;
}
switch(query) {
case QUERY_NAME: {
const char *node = udev_device_get_devnode(device);
switch(query) {
case QUERY_NAME: {
const char *node = udev_device_get_devnode(device);
if (node == NULL) {
fprintf(stderr, "no device node found\n");
rc = 5;
goto exit;
}
if (node == NULL) {
fprintf(stderr, "no device node found\n");
rc = 5;
goto exit;
}
if (root) {
printf("%s\n", udev_device_get_devnode(device));
} else {
size_t len = strlen(udev_get_dev_path(udev));
if (root) {
printf("%s\n", udev_device_get_devnode(device));
} else {
size_t len = strlen(udev_get_dev_path(udev));
printf("%s\n", &udev_device_get_devnode(device)[len+1]);
}
break;
}
case QUERY_SYMLINK:
list_entry = udev_device_get_devlinks_list_entry(device);
while (list_entry != NULL) {
if (root) {
printf("%s", udev_list_entry_get_name(list_entry));
} else {
size_t len;
printf("%s\n", &udev_device_get_devnode(device)[len+1]);
}
break;
}
case QUERY_SYMLINK:
list_entry = udev_device_get_devlinks_list_entry(device);
while (list_entry != NULL) {
if (root) {
printf("%s", udev_list_entry_get_name(list_entry));
} else {
size_t len;
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
printf("%s", &udev_list_entry_get_name(list_entry)[len+1]);
}
list_entry = udev_list_entry_get_next(list_entry);
if (list_entry != NULL)
printf(" ");
}
printf("\n");
break;
case QUERY_PATH:
printf("%s\n", udev_device_get_devpath(device));
goto exit;
case QUERY_PROPERTY:
list_entry = udev_device_get_properties_list_entry(device);
while (list_entry != NULL) {
if (export) {
const char *prefix = export_prefix;
len = strlen(udev_get_dev_path(udev_device_get_udev(device)));
printf("%s", &udev_list_entry_get_name(list_entry)[len+1]);
}
list_entry = udev_list_entry_get_next(list_entry);
if (list_entry != NULL)
printf(" ");
}
printf("\n");
break;
case QUERY_PATH:
printf("%s\n", udev_device_get_devpath(device));
goto exit;
case QUERY_PROPERTY:
list_entry = udev_device_get_properties_list_entry(device);
while (list_entry != NULL) {
if (export) {
const char *prefix = export_prefix;
if (prefix == NULL)
prefix = "";
printf("%s%s='%s'\n", prefix,
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
} else {
printf("%s=%s\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
}
list_entry = udev_list_entry_get_next(list_entry);
}
break;
case QUERY_ALL:
print_record(device);
break;
default:
fprintf(stderr, "unknown query type\n");
break;
}
break;
case ACTION_ATTRIBUTE_WALK:
if (device == NULL) {
fprintf(stderr, "query needs a valid device specified by --path= or --name=\n");
rc = 4;
goto exit;
}
print_device_chain(device);
break;
case ACTION_DEVICE_ID_FILE:
if (stat_device(name, export, export_prefix) != 0)
rc = 1;
break;
case ACTION_ROOT:
printf("%s\n", udev_get_dev_path(udev));
break;
default:
fprintf(stderr, "missing option\n");
rc = 1;
break;
}
if (prefix == NULL)
prefix = "";
printf("%s%s='%s'\n", prefix,
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
} else {
printf("%s=%s\n", udev_list_entry_get_name(list_entry), udev_list_entry_get_value(list_entry));
}
list_entry = udev_list_entry_get_next(list_entry);
}
break;
case QUERY_ALL:
print_record(device);
break;
default:
fprintf(stderr, "unknown query type\n");
break;
}
break;
case ACTION_ATTRIBUTE_WALK:
if (device == NULL) {
fprintf(stderr, "query needs a valid device specified by --path= or --name=\n");
rc = 4;
goto exit;
}
print_device_chain(device);
break;
case ACTION_DEVICE_ID_FILE:
if (stat_device(name, export, export_prefix) != 0)
rc = 1;
break;
case ACTION_ROOT:
printf("%s\n", udev_get_dev_path(udev));
break;
default:
fprintf(stderr, "missing option\n");
rc = 1;
break;
}
exit:
udev_device_unref(device);
return rc;
udev_device_unref(device);
return rc;
}
const struct udevadm_cmd udevadm_info = {
.name = "info",
.cmd = uinfo,
.help = "query sysfs or the udev database",
.name = "info",
.cmd = uinfo,
.help = "query sysfs or the udev database",
};
+213 -213
View File
@@ -38,260 +38,260 @@ static bool udev_exit;
static void sig_handler(int signum)
{
if (signum == SIGINT || signum == SIGTERM)
udev_exit = true;
if (signum == SIGINT || signum == SIGTERM)
udev_exit = true;
}
static void print_device(struct udev_device *device, const char *source, int prop)
{
struct timespec ts;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
printf("%-6s[%llu.%06u] %-8s %s (%s)\n",
source,
(unsigned long long) ts.tv_sec, (unsigned int) ts.tv_nsec/1000,
udev_device_get_action(device),
udev_device_get_devpath(device),
udev_device_get_subsystem(device));
if (prop) {
struct udev_list_entry *list_entry;
clock_gettime(CLOCK_MONOTONIC, &ts);
printf("%-6s[%llu.%06u] %-8s %s (%s)\n",
source,
(unsigned long long) ts.tv_sec, (unsigned int) ts.tv_nsec/1000,
udev_device_get_action(device),
udev_device_get_devpath(device),
udev_device_get_subsystem(device));
if (prop) {
struct udev_list_entry *list_entry;
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
printf("%s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
printf("\n");
}
udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(device))
printf("%s=%s\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
printf("\n");
}
}
static int adm_monitor(struct udev *udev, int argc, char *argv[])
{
struct sigaction act;
sigset_t mask;
int option;
bool prop = false;
bool print_kernel = false;
bool print_udev = false;
struct udev_list subsystem_match_list;
struct udev_list tag_match_list;
struct udev_monitor *udev_monitor = NULL;
struct udev_monitor *kernel_monitor = NULL;
int fd_ep = -1;
int fd_kernel = -1, fd_udev = -1;
struct epoll_event ep_kernel, ep_udev;
int rc = 0;
struct sigaction act;
sigset_t mask;
int option;
bool prop = false;
bool print_kernel = false;
bool print_udev = false;
struct udev_list subsystem_match_list;
struct udev_list tag_match_list;
struct udev_monitor *udev_monitor = NULL;
struct udev_monitor *kernel_monitor = NULL;
int fd_ep = -1;
int fd_kernel = -1, fd_udev = -1;
struct epoll_event ep_kernel, ep_udev;
int rc = 0;
static const struct option options[] = {
{ "property", no_argument, NULL, 'p' },
{ "environment", no_argument, NULL, 'e' },
{ "kernel", no_argument, NULL, 'k' },
{ "udev", no_argument, NULL, 'u' },
{ "subsystem-match", required_argument, NULL, 's' },
{ "tag-match", required_argument, NULL, 't' },
{ "help", no_argument, NULL, 'h' },
{}
};
static const struct option options[] = {
{ "property", no_argument, NULL, 'p' },
{ "environment", no_argument, NULL, 'e' },
{ "kernel", no_argument, NULL, 'k' },
{ "udev", no_argument, NULL, 'u' },
{ "subsystem-match", required_argument, NULL, 's' },
{ "tag-match", required_argument, NULL, 't' },
{ "help", no_argument, NULL, 'h' },
{}
};
udev_list_init(udev, &subsystem_match_list, true);
udev_list_init(udev, &tag_match_list, true);
udev_list_init(udev, &subsystem_match_list, true);
udev_list_init(udev, &tag_match_list, true);
for (;;) {
option = getopt_long(argc, argv, "pekus:t:h", options, NULL);
if (option == -1)
break;
for (;;) {
option = getopt_long(argc, argv, "pekus:t:h", options, NULL);
if (option == -1)
break;
switch (option) {
case 'p':
case 'e':
prop = true;
break;
case 'k':
print_kernel = true;
break;
case 'u':
print_udev = true;
break;
case 's':
{
char subsys[UTIL_NAME_SIZE];
char *devtype;
switch (option) {
case 'p':
case 'e':
prop = true;
break;
case 'k':
print_kernel = true;
break;
case 'u':
print_udev = true;
break;
case 's':
{
char subsys[UTIL_NAME_SIZE];
char *devtype;
util_strscpy(subsys, sizeof(subsys), optarg);
devtype = strchr(subsys, '/');
if (devtype != NULL) {
devtype[0] = '\0';
devtype++;
}
udev_list_entry_add(&subsystem_match_list, subsys, devtype);
break;
}
case 't':
udev_list_entry_add(&tag_match_list, optarg, NULL);
break;
case 'h':
printf("Usage: udevadm monitor [--property] [--kernel] [--udev] [--help]\n"
" --property print the event properties\n"
" --kernel print kernel uevents\n"
" --udev print udev events\n"
" --subsystem-match=<subsystem[/devtype]> filter events by subsystem\n"
" --tag-match=<tag> filter events by tag\n"
" --help\n\n");
goto out;
default:
rc = 1;
goto out;
}
}
util_strscpy(subsys, sizeof(subsys), optarg);
devtype = strchr(subsys, '/');
if (devtype != NULL) {
devtype[0] = '\0';
devtype++;
}
udev_list_entry_add(&subsystem_match_list, subsys, devtype);
break;
}
case 't':
udev_list_entry_add(&tag_match_list, optarg, NULL);
break;
case 'h':
printf("Usage: udevadm monitor [--property] [--kernel] [--udev] [--help]\n"
" --property print the event properties\n"
" --kernel print kernel uevents\n"
" --udev print udev events\n"
" --subsystem-match=<subsystem[/devtype]> filter events by subsystem\n"
" --tag-match=<tag> filter events by tag\n"
" --help\n\n");
goto out;
default:
rc = 1;
goto out;
}
}
if (!print_kernel && !print_udev) {
print_kernel = true;
print_udev = true;
}
if (!print_kernel && !print_udev) {
print_kernel = true;
print_udev = true;
}
/* set signal handlers */
memset(&act, 0x00, sizeof(struct sigaction));
act.sa_handler = sig_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART;
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
/* set signal handlers */
memset(&act, 0x00, sizeof(struct sigaction));
act.sa_handler = sig_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART;
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
fd_ep = epoll_create1(EPOLL_CLOEXEC);
if (fd_ep < 0) {
err(udev, "error creating epoll fd: %m\n");
goto out;
}
fd_ep = epoll_create1(EPOLL_CLOEXEC);
if (fd_ep < 0) {
err(udev, "error creating epoll fd: %m\n");
goto out;
}
printf("monitor will print the received events for:\n");
if (print_udev) {
struct udev_list_entry *entry;
printf("monitor will print the received events for:\n");
if (print_udev) {
struct udev_list_entry *entry;
udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
if (udev_monitor == NULL) {
fprintf(stderr, "error: unable to create netlink socket\n");
rc = 1;
goto out;
}
udev_monitor_set_receive_buffer_size(udev_monitor, 128*1024*1024);
fd_udev = udev_monitor_get_fd(udev_monitor);
udev_monitor = udev_monitor_new_from_netlink(udev, "udev");
if (udev_monitor == NULL) {
fprintf(stderr, "error: unable to create netlink socket\n");
rc = 1;
goto out;
}
udev_monitor_set_receive_buffer_size(udev_monitor, 128*1024*1024);
fd_udev = udev_monitor_get_fd(udev_monitor);
udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
const char *subsys = udev_list_entry_get_name(entry);
const char *devtype = udev_list_entry_get_value(entry);
udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
const char *subsys = udev_list_entry_get_name(entry);
const char *devtype = udev_list_entry_get_value(entry);
if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, subsys, devtype) < 0)
fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
}
if (udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, subsys, devtype) < 0)
fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
}
udev_list_entry_foreach(entry, udev_list_get_entry(&tag_match_list)) {
const char *tag = udev_list_entry_get_name(entry);
udev_list_entry_foreach(entry, udev_list_get_entry(&tag_match_list)) {
const char *tag = udev_list_entry_get_name(entry);
if (udev_monitor_filter_add_match_tag(udev_monitor, tag) < 0)
fprintf(stderr, "error: unable to apply tag filter '%s'\n", tag);
}
if (udev_monitor_filter_add_match_tag(udev_monitor, tag) < 0)
fprintf(stderr, "error: unable to apply tag filter '%s'\n", tag);
}
if (udev_monitor_enable_receiving(udev_monitor) < 0) {
fprintf(stderr, "error: unable to subscribe to udev events\n");
rc = 2;
goto out;
}
if (udev_monitor_enable_receiving(udev_monitor) < 0) {
fprintf(stderr, "error: unable to subscribe to udev events\n");
rc = 2;
goto out;
}
memset(&ep_udev, 0, sizeof(struct epoll_event));
ep_udev.events = EPOLLIN;
ep_udev.data.fd = fd_udev;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
err(udev, "fail to add fd to epoll: %m\n");
goto out;
}
memset(&ep_udev, 0, sizeof(struct epoll_event));
ep_udev.events = EPOLLIN;
ep_udev.data.fd = fd_udev;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_udev, &ep_udev) < 0) {
err(udev, "fail to add fd to epoll: %m\n");
goto out;
}
printf("UDEV - the event which udev sends out after rule processing\n");
}
printf("UDEV - the event which udev sends out after rule processing\n");
}
if (print_kernel) {
struct udev_list_entry *entry;
if (print_kernel) {
struct udev_list_entry *entry;
kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
if (kernel_monitor == NULL) {
fprintf(stderr, "error: unable to create netlink socket\n");
rc = 3;
goto out;
}
udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
fd_kernel = udev_monitor_get_fd(kernel_monitor);
kernel_monitor = udev_monitor_new_from_netlink(udev, "kernel");
if (kernel_monitor == NULL) {
fprintf(stderr, "error: unable to create netlink socket\n");
rc = 3;
goto out;
}
udev_monitor_set_receive_buffer_size(kernel_monitor, 128*1024*1024);
fd_kernel = udev_monitor_get_fd(kernel_monitor);
udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
const char *subsys = udev_list_entry_get_name(entry);
udev_list_entry_foreach(entry, udev_list_get_entry(&subsystem_match_list)) {
const char *subsys = udev_list_entry_get_name(entry);
if (udev_monitor_filter_add_match_subsystem_devtype(kernel_monitor, subsys, NULL) < 0)
fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
}
if (udev_monitor_filter_add_match_subsystem_devtype(kernel_monitor, subsys, NULL) < 0)
fprintf(stderr, "error: unable to apply subsystem filter '%s'\n", subsys);
}
if (udev_monitor_enable_receiving(kernel_monitor) < 0) {
fprintf(stderr, "error: unable to subscribe to kernel events\n");
rc = 4;
goto out;
}
if (udev_monitor_enable_receiving(kernel_monitor) < 0) {
fprintf(stderr, "error: unable to subscribe to kernel events\n");
rc = 4;
goto out;
}
memset(&ep_kernel, 0, sizeof(struct epoll_event));
ep_kernel.events = EPOLLIN;
ep_kernel.data.fd = fd_kernel;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_kernel, &ep_kernel) < 0) {
err(udev, "fail to add fd to epoll: %m\n");
goto out;
}
memset(&ep_kernel, 0, sizeof(struct epoll_event));
ep_kernel.events = EPOLLIN;
ep_kernel.data.fd = fd_kernel;
if (epoll_ctl(fd_ep, EPOLL_CTL_ADD, fd_kernel, &ep_kernel) < 0) {
err(udev, "fail to add fd to epoll: %m\n");
goto out;
}
printf("KERNEL - the kernel uevent\n");
}
printf("\n");
printf("KERNEL - the kernel uevent\n");
}
printf("\n");
while (!udev_exit) {
int fdcount;
struct epoll_event ev[4];
int i;
while (!udev_exit) {
int fdcount;
struct epoll_event ev[4];
int i;
fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
if (fdcount < 0) {
if (errno != EINTR)
fprintf(stderr, "error receiving uevent message: %m\n");
continue;
}
fdcount = epoll_wait(fd_ep, ev, ARRAY_SIZE(ev), -1);
if (fdcount < 0) {
if (errno != EINTR)
fprintf(stderr, "error receiving uevent message: %m\n");
continue;
}
for (i = 0; i < fdcount; i++) {
if (ev[i].data.fd == fd_kernel && ev[i].events & EPOLLIN) {
struct udev_device *device;
for (i = 0; i < fdcount; i++) {
if (ev[i].data.fd == fd_kernel && ev[i].events & EPOLLIN) {
struct udev_device *device;
device = udev_monitor_receive_device(kernel_monitor);
if (device == NULL)
continue;
print_device(device, "KERNEL", prop);
udev_device_unref(device);
} else if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
struct udev_device *device;
device = udev_monitor_receive_device(kernel_monitor);
if (device == NULL)
continue;
print_device(device, "KERNEL", prop);
udev_device_unref(device);
} else if (ev[i].data.fd == fd_udev && ev[i].events & EPOLLIN) {
struct udev_device *device;
device = udev_monitor_receive_device(udev_monitor);
if (device == NULL)
continue;
print_device(device, "UDEV", prop);
udev_device_unref(device);
}
}
}
device = udev_monitor_receive_device(udev_monitor);
if (device == NULL)
continue;
print_device(device, "UDEV", prop);
udev_device_unref(device);
}
}
}
out:
if (fd_ep >= 0)
close(fd_ep);
udev_monitor_unref(udev_monitor);
udev_monitor_unref(kernel_monitor);
udev_list_cleanup(&subsystem_match_list);
udev_list_cleanup(&tag_match_list);
return rc;
if (fd_ep >= 0)
close(fd_ep);
udev_monitor_unref(udev_monitor);
udev_monitor_unref(kernel_monitor);
udev_list_cleanup(&subsystem_match_list);
udev_list_cleanup(&tag_match_list);
return rc;
}
const struct udevadm_cmd udevadm_monitor = {
.name = "monitor",
.cmd = adm_monitor,
.help = "listen to kernel and udev events",
.name = "monitor",
.cmd = adm_monitor,
.help = "listen to kernel and udev events",
};
+167 -167
View File
@@ -38,198 +38,198 @@
static int adm_settle(struct udev *udev, int argc, char *argv[])
{
static const struct option options[] = {
{ "seq-start", required_argument, NULL, 's' },
{ "seq-end", required_argument, NULL, 'e' },
{ "timeout", required_argument, NULL, 't' },
{ "exit-if-exists", required_argument, NULL, 'E' },
{ "quiet", no_argument, NULL, 'q' },
{ "help", no_argument, NULL, 'h' },
{}
};
unsigned long long start_usec = now_usec();
unsigned long long start = 0;
unsigned long long end = 0;
int quiet = 0;
const char *exists = NULL;
unsigned int timeout = 120;
struct pollfd pfd[1];
struct udev_queue *udev_queue = NULL;
int rc = EXIT_FAILURE;
static const struct option options[] = {
{ "seq-start", required_argument, NULL, 's' },
{ "seq-end", required_argument, NULL, 'e' },
{ "timeout", required_argument, NULL, 't' },
{ "exit-if-exists", required_argument, NULL, 'E' },
{ "quiet", no_argument, NULL, 'q' },
{ "help", no_argument, NULL, 'h' },
{}
};
unsigned long long start_usec = now_usec();
unsigned long long start = 0;
unsigned long long end = 0;
int quiet = 0;
const char *exists = NULL;
unsigned int timeout = 120;
struct pollfd pfd[1];
struct udev_queue *udev_queue = NULL;
int rc = EXIT_FAILURE;
dbg(udev, "version %s\n", VERSION);
dbg(udev, "version %s\n", VERSION);
for (;;) {
int option;
int seconds;
for (;;) {
int option;
int seconds;
option = getopt_long(argc, argv, "s:e:t:E:qh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "s:e:t:E:qh", options, NULL);
if (option == -1)
break;
switch (option) {
case 's':
start = strtoull(optarg, NULL, 0);
break;
case 'e':
end = strtoull(optarg, NULL, 0);
break;
case 't':
seconds = atoi(optarg);
if (seconds >= 0)
timeout = seconds;
else
fprintf(stderr, "invalid timeout value\n");
dbg(udev, "timeout=%i\n", timeout);
break;
case 'q':
quiet = 1;
break;
case 'E':
exists = optarg;
break;
case 'h':
printf("Usage: udevadm settle OPTIONS\n"
" --timeout=<seconds> maximum time to wait for events\n"
" --seq-start=<seqnum> first seqnum to wait for\n"
" --seq-end=<seqnum> last seqnum to wait for\n"
" --exit-if-exists=<file> stop waiting if file exists\n"
" --quiet do not print list after timeout\n"
" --help\n\n");
exit(EXIT_SUCCESS);
default:
exit(EXIT_FAILURE);
}
}
switch (option) {
case 's':
start = strtoull(optarg, NULL, 0);
break;
case 'e':
end = strtoull(optarg, NULL, 0);
break;
case 't':
seconds = atoi(optarg);
if (seconds >= 0)
timeout = seconds;
else
fprintf(stderr, "invalid timeout value\n");
dbg(udev, "timeout=%i\n", timeout);
break;
case 'q':
quiet = 1;
break;
case 'E':
exists = optarg;
break;
case 'h':
printf("Usage: udevadm settle OPTIONS\n"
" --timeout=<seconds> maximum time to wait for events\n"
" --seq-start=<seqnum> first seqnum to wait for\n"
" --seq-end=<seqnum> last seqnum to wait for\n"
" --exit-if-exists=<file> stop waiting if file exists\n"
" --quiet do not print list after timeout\n"
" --help\n\n");
exit(EXIT_SUCCESS);
default:
exit(EXIT_FAILURE);
}
}
udev_queue = udev_queue_new(udev);
if (udev_queue == NULL)
exit(2);
udev_queue = udev_queue_new(udev);
if (udev_queue == NULL)
exit(2);
if (start > 0) {
unsigned long long kernel_seq;
if (start > 0) {
unsigned long long kernel_seq;
kernel_seq = udev_queue_get_kernel_seqnum(udev_queue);
kernel_seq = udev_queue_get_kernel_seqnum(udev_queue);
/* unless specified, the last event is the current kernel seqnum */
if (end == 0)
end = udev_queue_get_kernel_seqnum(udev_queue);
/* unless specified, the last event is the current kernel seqnum */
if (end == 0)
end = udev_queue_get_kernel_seqnum(udev_queue);
if (start > end) {
err(udev, "seq-start larger than seq-end, ignoring\n");
start = 0;
end = 0;
}
if (start > end) {
err(udev, "seq-start larger than seq-end, ignoring\n");
start = 0;
end = 0;
}
if (start > kernel_seq || end > kernel_seq) {
err(udev, "seq-start or seq-end larger than current kernel value, ignoring\n");
start = 0;
end = 0;
}
info(udev, "start=%llu end=%llu current=%llu\n", start, end, kernel_seq);
} else {
if (end > 0) {
err(udev, "seq-end needs seq-start parameter, ignoring\n");
end = 0;
}
}
if (start > kernel_seq || end > kernel_seq) {
err(udev, "seq-start or seq-end larger than current kernel value, ignoring\n");
start = 0;
end = 0;
}
info(udev, "start=%llu end=%llu current=%llu\n", start, end, kernel_seq);
} else {
if (end > 0) {
err(udev, "seq-end needs seq-start parameter, ignoring\n");
end = 0;
}
}
/* guarantee that the udev daemon isn't pre-processing */
if (getuid() == 0) {
struct udev_ctrl *uctrl;
/* guarantee that the udev daemon isn't pre-processing */
if (getuid() == 0) {
struct udev_ctrl *uctrl;
uctrl = udev_ctrl_new(udev);
if (uctrl != NULL) {
if (udev_ctrl_send_ping(uctrl, timeout) < 0) {
info(udev, "no connection to daemon\n");
udev_ctrl_unref(uctrl);
rc = EXIT_SUCCESS;
goto out;
}
udev_ctrl_unref(uctrl);
}
}
uctrl = udev_ctrl_new(udev);
if (uctrl != NULL) {
if (udev_ctrl_send_ping(uctrl, timeout) < 0) {
info(udev, "no connection to daemon\n");
udev_ctrl_unref(uctrl);
rc = EXIT_SUCCESS;
goto out;
}
udev_ctrl_unref(uctrl);
}
}
pfd[0].events = POLLIN;
pfd[0].fd = inotify_init1(IN_CLOEXEC);
if (pfd[0].fd < 0) {
err(udev, "inotify_init failed: %m\n");
} else {
if (inotify_add_watch(pfd[0].fd, udev_get_run_path(udev), IN_MOVED_TO) < 0) {
err(udev, "watching '%s' failed\n", udev_get_run_path(udev));
close(pfd[0].fd);
pfd[0].fd = -1;
}
}
pfd[0].events = POLLIN;
pfd[0].fd = inotify_init1(IN_CLOEXEC);
if (pfd[0].fd < 0) {
err(udev, "inotify_init failed: %m\n");
} else {
if (inotify_add_watch(pfd[0].fd, udev_get_run_path(udev), IN_MOVED_TO) < 0) {
err(udev, "watching '%s' failed\n", udev_get_run_path(udev));
close(pfd[0].fd);
pfd[0].fd = -1;
}
}
for (;;) {
struct stat statbuf;
for (;;) {
struct stat statbuf;
if (exists != NULL && stat(exists, &statbuf) == 0) {
rc = EXIT_SUCCESS;
break;
}
if (exists != NULL && stat(exists, &statbuf) == 0) {
rc = EXIT_SUCCESS;
break;
}
if (start > 0) {
/* if asked for, wait for a specific sequence of events */
if (udev_queue_get_seqnum_sequence_is_finished(udev_queue, start, end) == 1) {
rc = EXIT_SUCCESS;
break;
}
} else {
/* exit if queue is empty */
if (udev_queue_get_queue_is_empty(udev_queue)) {
rc = EXIT_SUCCESS;
break;
}
}
if (start > 0) {
/* if asked for, wait for a specific sequence of events */
if (udev_queue_get_seqnum_sequence_is_finished(udev_queue, start, end) == 1) {
rc = EXIT_SUCCESS;
break;
}
} else {
/* exit if queue is empty */
if (udev_queue_get_queue_is_empty(udev_queue)) {
rc = EXIT_SUCCESS;
break;
}
}
if (pfd[0].fd >= 0) {
int delay;
if (pfd[0].fd >= 0) {
int delay;
if (exists != NULL || start > 0)
delay = 100;
else
delay = 1000;
/* wake up after delay, or immediately after the queue is rebuilt */
if (poll(pfd, 1, delay) > 0 && pfd[0].revents & POLLIN) {
char buf[sizeof(struct inotify_event) + PATH_MAX];
if (exists != NULL || start > 0)
delay = 100;
else
delay = 1000;
/* wake up after delay, or immediately after the queue is rebuilt */
if (poll(pfd, 1, delay) > 0 && pfd[0].revents & POLLIN) {
char buf[sizeof(struct inotify_event) + PATH_MAX];
read(pfd[0].fd, buf, sizeof(buf));
}
} else {
sleep(1);
}
read(pfd[0].fd, buf, sizeof(buf));
}
} else {
sleep(1);
}
if (timeout > 0) {
unsigned long long age_usec;
if (timeout > 0) {
unsigned long long age_usec;
age_usec = now_usec() - start_usec;
if (age_usec / (1000 * 1000) >= timeout) {
struct udev_list_entry *list_entry;
age_usec = now_usec() - start_usec;
if (age_usec / (1000 * 1000) >= timeout) {
struct udev_list_entry *list_entry;
if (!quiet && udev_queue_get_queued_list_entry(udev_queue) != NULL) {
info(udev, "timeout waiting for udev queue\n");
printf("\nudevadm settle - timeout of %i seconds reached, the event queue contains:\n", timeout);
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf(" %s (%s)\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
}
if (!quiet && udev_queue_get_queued_list_entry(udev_queue) != NULL) {
info(udev, "timeout waiting for udev queue\n");
printf("\nudevadm settle - timeout of %i seconds reached, the event queue contains:\n", timeout);
udev_list_entry_foreach(list_entry, udev_queue_get_queued_list_entry(udev_queue))
printf(" %s (%s)\n",
udev_list_entry_get_name(list_entry),
udev_list_entry_get_value(list_entry));
}
break;
}
}
}
break;
}
}
}
out:
if (pfd[0].fd >= 0)
close(pfd[0].fd);
udev_queue_unref(udev_queue);
return rc;
if (pfd[0].fd >= 0)
close(pfd[0].fd);
udev_queue_unref(udev_queue);
return rc;
}
const struct udevadm_cmd udevadm_settle = {
.name = "settle",
.cmd = adm_settle,
.help = "wait for the event queue to finish",
.name = "settle",
.cmd = adm_settle,
.help = "wait for the event queue to finish",
};
+70 -70
View File
@@ -36,93 +36,93 @@
static void help(struct udev *udev)
{
fprintf(stderr, "\n");
fprintf(stderr, "Usage: udevadm builtin [--help] <command> <syspath>\n");
udev_builtin_list(udev);
fprintf(stderr, "\n");
fprintf(stderr, "\n");
fprintf(stderr, "Usage: udevadm builtin [--help] <command> <syspath>\n");
udev_builtin_list(udev);
fprintf(stderr, "\n");
}
static int adm_builtin(struct udev *udev, int argc, char *argv[])
{
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{}
};
char *command = NULL;
char *syspath = NULL;
char filename[UTIL_PATH_SIZE];
struct udev_device *dev = NULL;
enum udev_builtin_cmd cmd;
int rc = EXIT_SUCCESS;
static const struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{}
};
char *command = NULL;
char *syspath = NULL;
char filename[UTIL_PATH_SIZE];
struct udev_device *dev = NULL;
enum udev_builtin_cmd cmd;
int rc = EXIT_SUCCESS;
dbg(udev, "version %s\n", VERSION);
dbg(udev, "version %s\n", VERSION);
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "h", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "h", options, NULL);
if (option == -1)
break;
switch (option) {
case 'h':
help(udev);
goto out;
}
}
switch (option) {
case 'h':
help(udev);
goto out;
}
}
command = argv[optind++];
if (command == NULL) {
fprintf(stderr, "command missing\n");
help(udev);
rc = 2;
goto out;
}
command = argv[optind++];
if (command == NULL) {
fprintf(stderr, "command missing\n");
help(udev);
rc = 2;
goto out;
}
syspath = argv[optind++];
if (syspath == NULL) {
fprintf(stderr, "syspath missing\n\n");
rc = 3;
goto out;
}
syspath = argv[optind++];
if (syspath == NULL) {
fprintf(stderr, "syspath missing\n\n");
rc = 3;
goto out;
}
udev_builtin_init(udev);
udev_builtin_init(udev);
cmd = udev_builtin_lookup(command);
if (cmd >= UDEV_BUILTIN_MAX) {
fprintf(stderr, "unknown command '%s'\n", command);
help(udev);
rc = 5;
goto out;
}
cmd = udev_builtin_lookup(command);
if (cmd >= UDEV_BUILTIN_MAX) {
fprintf(stderr, "unknown command '%s'\n", command);
help(udev);
rc = 5;
goto out;
}
/* add /sys if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), syspath, NULL);
else
util_strscpy(filename, sizeof(filename), syspath);
util_remove_trailing_chars(filename, '/');
/* add /sys if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), syspath, NULL);
else
util_strscpy(filename, sizeof(filename), syspath);
util_remove_trailing_chars(filename, '/');
dev = udev_device_new_from_syspath(udev, filename);
if (dev == NULL) {
fprintf(stderr, "unable to open device '%s'\n\n", filename);
rc = 4;
goto out;
}
dev = udev_device_new_from_syspath(udev, filename);
if (dev == NULL) {
fprintf(stderr, "unable to open device '%s'\n\n", filename);
rc = 4;
goto out;
}
if (udev_builtin_run(dev, cmd, command, true) < 0) {
fprintf(stderr, "error executing '%s'\n\n", command);
rc = 6;
}
if (udev_builtin_run(dev, cmd, command, true) < 0) {
fprintf(stderr, "error executing '%s'\n\n", command);
rc = 6;
}
out:
udev_device_unref(dev);
udev_builtin_exit(udev);
return rc;
udev_device_unref(dev);
udev_builtin_exit(udev);
return rc;
}
const struct udevadm_cmd udevadm_test_builtin = {
.name = "test-builtin",
.cmd = adm_builtin,
.help = "test a built-in command",
.debug = true,
.name = "test-builtin",
.cmd = adm_builtin,
.help = "test a built-in command",
.debug = true,
};
+114 -114
View File
@@ -33,141 +33,141 @@
static int adm_test(struct udev *udev, int argc, char *argv[])
{
int resolve_names = 1;
char filename[UTIL_PATH_SIZE];
const char *action = "add";
const char *syspath = NULL;
struct udev_event *event = NULL;
struct udev_device *dev = NULL;
struct udev_rules *rules = NULL;
struct udev_list_entry *entry;
sigset_t mask, sigmask_orig;
int err;
int rc = 0;
int resolve_names = 1;
char filename[UTIL_PATH_SIZE];
const char *action = "add";
const char *syspath = NULL;
struct udev_event *event = NULL;
struct udev_device *dev = NULL;
struct udev_rules *rules = NULL;
struct udev_list_entry *entry;
sigset_t mask, sigmask_orig;
int err;
int rc = 0;
static const struct option options[] = {
{ "action", required_argument, NULL, 'a' },
{ "resolve-names", required_argument, NULL, 'N' },
{ "help", no_argument, NULL, 'h' },
{}
};
static const struct option options[] = {
{ "action", required_argument, NULL, 'a' },
{ "resolve-names", required_argument, NULL, 'N' },
{ "help", no_argument, NULL, 'h' },
{}
};
info(udev, "version %s\n", VERSION);
info(udev, "version %s\n", VERSION);
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "a:s:N:fh", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "a:s:N:fh", options, NULL);
if (option == -1)
break;
dbg(udev, "option '%c'\n", option);
switch (option) {
case 'a':
action = optarg;
break;
case 'N':
if (strcmp (optarg, "early") == 0) {
resolve_names = 1;
} else if (strcmp (optarg, "late") == 0) {
resolve_names = 0;
} else if (strcmp (optarg, "never") == 0) {
resolve_names = -1;
} else {
fprintf(stderr, "resolve-names must be early, late or never\n");
err(udev, "resolve-names must be early, late or never\n");
exit(EXIT_FAILURE);
}
break;
case 'h':
printf("Usage: udevadm test OPTIONS <syspath>\n"
" --action=<string> set action string\n"
" --help\n\n");
exit(EXIT_SUCCESS);
default:
exit(EXIT_FAILURE);
}
}
syspath = argv[optind];
dbg(udev, "option '%c'\n", option);
switch (option) {
case 'a':
action = optarg;
break;
case 'N':
if (strcmp (optarg, "early") == 0) {
resolve_names = 1;
} else if (strcmp (optarg, "late") == 0) {
resolve_names = 0;
} else if (strcmp (optarg, "never") == 0) {
resolve_names = -1;
} else {
fprintf(stderr, "resolve-names must be early, late or never\n");
err(udev, "resolve-names must be early, late or never\n");
exit(EXIT_FAILURE);
}
break;
case 'h':
printf("Usage: udevadm test OPTIONS <syspath>\n"
" --action=<string> set action string\n"
" --help\n\n");
exit(EXIT_SUCCESS);
default:
exit(EXIT_FAILURE);
}
}
syspath = argv[optind];
if (syspath == NULL) {
fprintf(stderr, "syspath parameter missing\n");
rc = 2;
goto out;
}
if (syspath == NULL) {
fprintf(stderr, "syspath parameter missing\n");
rc = 2;
goto out;
}
printf("This program is for debugging only, it does not run any program,\n"
"specified by a RUN key. It may show incorrect results, because\n"
"some values may be different, or not available at a simulation run.\n"
"\n");
printf("This program is for debugging only, it does not run any program,\n"
"specified by a RUN key. It may show incorrect results, because\n"
"some values may be different, or not available at a simulation run.\n"
"\n");
sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
sigprocmask(SIG_SETMASK, NULL, &sigmask_orig);
udev_builtin_init(udev);
udev_builtin_init(udev);
rules = udev_rules_new(udev, resolve_names);
if (rules == NULL) {
fprintf(stderr, "error reading rules\n");
rc = 3;
goto out;
}
rules = udev_rules_new(udev, resolve_names);
if (rules == NULL) {
fprintf(stderr, "error reading rules\n");
rc = 3;
goto out;
}
/* add /sys if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), syspath, NULL);
else
util_strscpy(filename, sizeof(filename), syspath);
util_remove_trailing_chars(filename, '/');
/* add /sys if needed */
if (strncmp(syspath, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(filename, sizeof(filename), udev_get_sys_path(udev), syspath, NULL);
else
util_strscpy(filename, sizeof(filename), syspath);
util_remove_trailing_chars(filename, '/');
dev = udev_device_new_from_syspath(udev, filename);
if (dev == NULL) {
fprintf(stderr, "unable to open device '%s'\n", filename);
rc = 4;
goto out;
}
dev = udev_device_new_from_syspath(udev, filename);
if (dev == NULL) {
fprintf(stderr, "unable to open device '%s'\n", filename);
rc = 4;
goto out;
}
/* skip reading of db, but read kernel parameters */
udev_device_set_info_loaded(dev);
udev_device_read_uevent_file(dev);
/* skip reading of db, but read kernel parameters */
udev_device_set_info_loaded(dev);
udev_device_read_uevent_file(dev);
udev_device_set_action(dev, action);
event = udev_event_new(dev);
udev_device_set_action(dev, action);
event = udev_event_new(dev);
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (event->fd_signal < 0) {
fprintf(stderr, "error creating signalfd\n");
rc = 5;
goto out;
}
sigfillset(&mask);
sigprocmask(SIG_SETMASK, &mask, &sigmask_orig);
event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
if (event->fd_signal < 0) {
fprintf(stderr, "error creating signalfd\n");
rc = 5;
goto out;
}
err = udev_event_execute_rules(event, rules, &sigmask_orig);
err = udev_event_execute_rules(event, rules, &sigmask_orig);
udev_list_entry_foreach(entry, udev_device_get_properties_list_entry(dev))
printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
udev_list_entry_foreach(entry, udev_device_get_properties_list_entry(dev))
printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
if (err == 0) {
udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) {
char program[UTIL_PATH_SIZE];
if (err == 0) {
udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) {
char program[UTIL_PATH_SIZE];
udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program));
printf("run: '%s'\n", program);
}
}
udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program));
printf("run: '%s'\n", program);
}
}
out:
if (event != NULL && event->fd_signal >= 0)
close(event->fd_signal);
udev_event_unref(event);
udev_device_unref(dev);
udev_rules_unref(rules);
udev_builtin_exit(udev);
return rc;
if (event != NULL && event->fd_signal >= 0)
close(event->fd_signal);
udev_event_unref(event);
udev_device_unref(dev);
udev_rules_unref(rules);
udev_builtin_exit(udev);
return rc;
}
const struct udevadm_cmd udevadm_test = {
.name = "test",
.cmd = adm_test,
.help = "test an event run",
.debug = true,
.name = "test",
.cmd = adm_test,
.help = "test an event run",
.debug = true,
};
+170 -170
View File
@@ -38,195 +38,195 @@ static int dry_run;
static void exec_list(struct udev_enumerate *udev_enumerate, const char *action)
{
struct udev *udev = udev_enumerate_get_udev(udev_enumerate);
struct udev_list_entry *entry;
struct udev *udev = udev_enumerate_get_udev(udev_enumerate);
struct udev_list_entry *entry;
udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(udev_enumerate)) {
char filename[UTIL_PATH_SIZE];
int fd;
udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(udev_enumerate)) {
char filename[UTIL_PATH_SIZE];
int fd;
if (verbose)
printf("%s\n", udev_list_entry_get_name(entry));
if (dry_run)
continue;
util_strscpyl(filename, sizeof(filename), udev_list_entry_get_name(entry), "/uevent", NULL);
fd = open(filename, O_WRONLY);
if (fd < 0) {
dbg(udev, "error on opening %s: %m\n", filename);
continue;
}
if (write(fd, action, strlen(action)) < 0)
info(udev, "error writing '%s' to '%s': %m\n", action, filename);
close(fd);
}
if (verbose)
printf("%s\n", udev_list_entry_get_name(entry));
if (dry_run)
continue;
util_strscpyl(filename, sizeof(filename), udev_list_entry_get_name(entry), "/uevent", NULL);
fd = open(filename, O_WRONLY);
if (fd < 0) {
dbg(udev, "error on opening %s: %m\n", filename);
continue;
}
if (write(fd, action, strlen(action)) < 0)
info(udev, "error writing '%s' to '%s': %m\n", action, filename);
close(fd);
}
}
static const char *keyval(const char *str, const char **val, char *buf, size_t size)
{
char *pos;
char *pos;
util_strscpy(buf, size,str);
pos = strchr(buf, '=');
if (pos != NULL) {
pos[0] = 0;
pos++;
}
*val = pos;
return buf;
util_strscpy(buf, size,str);
pos = strchr(buf, '=');
if (pos != NULL) {
pos[0] = 0;
pos++;
}
*val = pos;
return buf;
}
static int adm_trigger(struct udev *udev, int argc, char *argv[])
{
static const struct option options[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "dry-run", no_argument, NULL, 'n' },
{ "type", required_argument, NULL, 't' },
{ "action", required_argument, NULL, 'c' },
{ "subsystem-match", required_argument, NULL, 's' },
{ "subsystem-nomatch", required_argument, NULL, 'S' },
{ "attr-match", required_argument, NULL, 'a' },
{ "attr-nomatch", required_argument, NULL, 'A' },
{ "property-match", required_argument, NULL, 'p' },
{ "tag-match", required_argument, NULL, 'g' },
{ "sysname-match", required_argument, NULL, 'y' },
{ "parent-match", required_argument, NULL, 'b' },
{ "help", no_argument, NULL, 'h' },
{}
};
enum {
TYPE_DEVICES,
TYPE_SUBSYSTEMS,
} device_type = TYPE_DEVICES;
const char *action = "change";
struct udev_enumerate *udev_enumerate;
int rc = 0;
static const struct option options[] = {
{ "verbose", no_argument, NULL, 'v' },
{ "dry-run", no_argument, NULL, 'n' },
{ "type", required_argument, NULL, 't' },
{ "action", required_argument, NULL, 'c' },
{ "subsystem-match", required_argument, NULL, 's' },
{ "subsystem-nomatch", required_argument, NULL, 'S' },
{ "attr-match", required_argument, NULL, 'a' },
{ "attr-nomatch", required_argument, NULL, 'A' },
{ "property-match", required_argument, NULL, 'p' },
{ "tag-match", required_argument, NULL, 'g' },
{ "sysname-match", required_argument, NULL, 'y' },
{ "parent-match", required_argument, NULL, 'b' },
{ "help", no_argument, NULL, 'h' },
{}
};
enum {
TYPE_DEVICES,
TYPE_SUBSYSTEMS,
} device_type = TYPE_DEVICES;
const char *action = "change";
struct udev_enumerate *udev_enumerate;
int rc = 0;
dbg(udev, "version %s\n", VERSION);
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL) {
rc = 1;
goto exit;
}
dbg(udev, "version %s\n", VERSION);
udev_enumerate = udev_enumerate_new(udev);
if (udev_enumerate == NULL) {
rc = 1;
goto exit;
}
for (;;) {
int option;
const char *key;
const char *val;
char buf[UTIL_PATH_SIZE];
for (;;) {
int option;
const char *key;
const char *val;
char buf[UTIL_PATH_SIZE];
option = getopt_long(argc, argv, "vng:o:t:hc:p:s:S:a:A:y:b:", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "vng:o:t:hc:p:s:S:a:A:y:b:", options, NULL);
if (option == -1)
break;
switch (option) {
case 'v':
verbose = 1;
break;
case 'n':
dry_run = 1;
break;
case 't':
if (strcmp(optarg, "devices") == 0) {
device_type = TYPE_DEVICES;
} else if (strcmp(optarg, "subsystems") == 0) {
device_type = TYPE_SUBSYSTEMS;
} else {
err(udev, "unknown type --type=%s\n", optarg);
rc = 2;
goto exit;
}
break;
case 'c':
action = optarg;
break;
case 's':
udev_enumerate_add_match_subsystem(udev_enumerate, optarg);
break;
case 'S':
udev_enumerate_add_nomatch_subsystem(udev_enumerate, optarg);
break;
case 'a':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_match_sysattr(udev_enumerate, key, val);
break;
case 'A':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_nomatch_sysattr(udev_enumerate, key, val);
break;
case 'p':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_match_property(udev_enumerate, key, val);
break;
case 'g':
udev_enumerate_add_match_tag(udev_enumerate, optarg);
break;
case 'y':
udev_enumerate_add_match_sysname(udev_enumerate, optarg);
break;
case 'b': {
char path[UTIL_PATH_SIZE];
struct udev_device *dev;
switch (option) {
case 'v':
verbose = 1;
break;
case 'n':
dry_run = 1;
break;
case 't':
if (strcmp(optarg, "devices") == 0) {
device_type = TYPE_DEVICES;
} else if (strcmp(optarg, "subsystems") == 0) {
device_type = TYPE_SUBSYSTEMS;
} else {
err(udev, "unknown type --type=%s\n", optarg);
rc = 2;
goto exit;
}
break;
case 'c':
action = optarg;
break;
case 's':
udev_enumerate_add_match_subsystem(udev_enumerate, optarg);
break;
case 'S':
udev_enumerate_add_nomatch_subsystem(udev_enumerate, optarg);
break;
case 'a':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_match_sysattr(udev_enumerate, key, val);
break;
case 'A':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_nomatch_sysattr(udev_enumerate, key, val);
break;
case 'p':
key = keyval(optarg, &val, buf, sizeof(buf));
udev_enumerate_add_match_property(udev_enumerate, key, val);
break;
case 'g':
udev_enumerate_add_match_tag(udev_enumerate, optarg);
break;
case 'y':
udev_enumerate_add_match_sysname(udev_enumerate, optarg);
break;
case 'b': {
char path[UTIL_PATH_SIZE];
struct udev_device *dev;
/* add sys dir if needed */
if (strncmp(optarg, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), optarg, NULL);
else
util_strscpy(path, sizeof(path), optarg);
util_remove_trailing_chars(path, '/');
dev = udev_device_new_from_syspath(udev, path);
if (dev == NULL) {
err(udev, "unable to open the device '%s'\n", optarg);
rc = 2;
goto exit;
}
udev_enumerate_add_match_parent(udev_enumerate, dev);
/* drop reference immediately, enumerate pins the device as long as needed */
udev_device_unref(dev);
break;
}
case 'h':
printf("Usage: udevadm trigger OPTIONS\n"
" --verbose print the list of devices while running\n"
" --dry-run do not actually trigger the events\n"
" --type= type of events to trigger\n"
" devices sys devices (default)\n"
" subsystems sys subsystems and drivers\n"
" --action=<action> event action value, default is \"change\"\n"
" --subsystem-match=<subsystem> trigger devices from a matching subsystem\n"
" --subsystem-nomatch=<subsystem> exclude devices from a matching subsystem\n"
" --attr-match=<file[=<value>]> trigger devices with a matching attribute\n"
" --attr-nomatch=<file[=<value>]> exclude devices with a matching attribute\n"
" --property-match=<key>=<value> trigger devices with a matching property\n"
" --tag-match=<key>=<value> trigger devices with a matching property\n"
" --sysname-match=<name> trigger devices with a matching name\n"
" --parent-match=<name> trigger devices with that parent device\n"
" --help\n\n");
goto exit;
default:
rc = 1;
goto exit;
}
}
/* add sys dir if needed */
if (strncmp(optarg, udev_get_sys_path(udev), strlen(udev_get_sys_path(udev))) != 0)
util_strscpyl(path, sizeof(path), udev_get_sys_path(udev), optarg, NULL);
else
util_strscpy(path, sizeof(path), optarg);
util_remove_trailing_chars(path, '/');
dev = udev_device_new_from_syspath(udev, path);
if (dev == NULL) {
err(udev, "unable to open the device '%s'\n", optarg);
rc = 2;
goto exit;
}
udev_enumerate_add_match_parent(udev_enumerate, dev);
/* drop reference immediately, enumerate pins the device as long as needed */
udev_device_unref(dev);
break;
}
case 'h':
printf("Usage: udevadm trigger OPTIONS\n"
" --verbose print the list of devices while running\n"
" --dry-run do not actually trigger the events\n"
" --type= type of events to trigger\n"
" devices sys devices (default)\n"
" subsystems sys subsystems and drivers\n"
" --action=<action> event action value, default is \"change\"\n"
" --subsystem-match=<subsystem> trigger devices from a matching subsystem\n"
" --subsystem-nomatch=<subsystem> exclude devices from a matching subsystem\n"
" --attr-match=<file[=<value>]> trigger devices with a matching attribute\n"
" --attr-nomatch=<file[=<value>]> exclude devices with a matching attribute\n"
" --property-match=<key>=<value> trigger devices with a matching property\n"
" --tag-match=<key>=<value> trigger devices with a matching property\n"
" --sysname-match=<name> trigger devices with a matching name\n"
" --parent-match=<name> trigger devices with that parent device\n"
" --help\n\n");
goto exit;
default:
rc = 1;
goto exit;
}
}
switch (device_type) {
case TYPE_SUBSYSTEMS:
udev_enumerate_scan_subsystems(udev_enumerate);
exec_list(udev_enumerate, action);
goto exit;
case TYPE_DEVICES:
udev_enumerate_scan_devices(udev_enumerate);
exec_list(udev_enumerate, action);
goto exit;
default:
goto exit;
}
switch (device_type) {
case TYPE_SUBSYSTEMS:
udev_enumerate_scan_subsystems(udev_enumerate);
exec_list(udev_enumerate, action);
goto exit;
case TYPE_DEVICES:
udev_enumerate_scan_devices(udev_enumerate);
exec_list(udev_enumerate, action);
goto exit;
default:
goto exit;
}
exit:
udev_enumerate_unref(udev_enumerate);
return rc;
udev_enumerate_unref(udev_enumerate);
return rc;
}
const struct udevadm_cmd udevadm_trigger = {
.name = "trigger",
.cmd = adm_trigger,
.help = "request events from the kernel",
.name = "trigger",
.cmd = adm_trigger,
.help = "request events from the kernel",
};
+97 -97
View File
@@ -28,138 +28,138 @@
static bool debug;
void udev_main_log(struct udev *udev, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)
const char *file, int line, const char *fn,
const char *format, va_list args)
{
if (debug) {
fprintf(stderr, "%s: ", fn);
vfprintf(stderr, format, args);
} else {
va_list args2;
if (debug) {
fprintf(stderr, "%s: ", fn);
vfprintf(stderr, format, args);
} else {
va_list args2;
va_copy(args2, args);
vfprintf(stderr, format, args2);
va_end(args2);
vsyslog(priority, format, args);
}
va_copy(args2, args);
vfprintf(stderr, format, args2);
va_end(args2);
vsyslog(priority, format, args);
}
}
static int adm_version(struct udev *udev, int argc, char *argv[])
{
printf("%s\n", VERSION);
return 0;
printf("%s\n", VERSION);
return 0;
}
static const struct udevadm_cmd udevadm_version = {
.name = "version",
.cmd = adm_version,
.name = "version",
.cmd = adm_version,
};
static int adm_help(struct udev *udev, int argc, char *argv[]);
static const struct udevadm_cmd udevadm_help = {
.name = "help",
.cmd = adm_help,
.name = "help",
.cmd = adm_help,
};
static const struct udevadm_cmd *udevadm_cmds[] = {
&udevadm_info,
&udevadm_trigger,
&udevadm_settle,
&udevadm_control,
&udevadm_monitor,
&udevadm_test,
&udevadm_test_builtin,
&udevadm_version,
&udevadm_help,
&udevadm_info,
&udevadm_trigger,
&udevadm_settle,
&udevadm_control,
&udevadm_monitor,
&udevadm_test,
&udevadm_test_builtin,
&udevadm_version,
&udevadm_help,
};
static int adm_help(struct udev *udev, int argc, char *argv[])
{
unsigned int i;
unsigned int i;
fprintf(stderr, "Usage: udevadm [--help] [--version] [--debug] COMMAND [COMMAND OPTIONS]\n");
for (i = 0; i < ARRAY_SIZE(udevadm_cmds); i++)
if (udevadm_cmds[i]->help != NULL)
printf(" %-12s %s\n", udevadm_cmds[i]->name, udevadm_cmds[i]->help);
fprintf(stderr, "\n");
return 0;
fprintf(stderr, "Usage: udevadm [--help] [--version] [--debug] COMMAND [COMMAND OPTIONS]\n");
for (i = 0; i < ARRAY_SIZE(udevadm_cmds); i++)
if (udevadm_cmds[i]->help != NULL)
printf(" %-12s %s\n", udevadm_cmds[i]->name, udevadm_cmds[i]->help);
fprintf(stderr, "\n");
return 0;
}
static int run_command(struct udev *udev, const struct udevadm_cmd *cmd, int argc, char *argv[])
{
if (cmd->debug) {
debug = true;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
}
info(udev, "calling: %s\n", cmd->name);
return cmd->cmd(udev, argc, argv);
if (cmd->debug) {
debug = true;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
}
info(udev, "calling: %s\n", cmd->name);
return cmd->cmd(udev, argc, argv);
}
int main(int argc, char *argv[])
{
struct udev *udev;
static const struct option options[] = {
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
{}
};
const char *command;
unsigned int i;
int rc = 1;
struct udev *udev;
static const struct option options[] = {
{ "debug", no_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
{}
};
const char *command;
unsigned int i;
int rc = 1;
udev = udev_new();
if (udev == NULL)
goto out;
udev = udev_new();
if (udev == NULL)
goto out;
udev_log_init("udevadm");
udev_set_log_fn(udev, udev_main_log);
udev_selinux_init(udev);
udev_log_init("udevadm");
udev_set_log_fn(udev, udev_main_log);
udev_selinux_init(udev);
for (;;) {
int option;
for (;;) {
int option;
option = getopt_long(argc, argv, "+dhV", options, NULL);
if (option == -1)
break;
option = getopt_long(argc, argv, "+dhV", options, NULL);
if (option == -1)
break;
switch (option) {
case 'd':
debug = true;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
rc = adm_help(udev, argc, argv);
goto out;
case 'V':
rc = adm_version(udev, argc, argv);
goto out;
default:
goto out;
}
}
command = argv[optind];
switch (option) {
case 'd':
debug = true;
if (udev_get_log_priority(udev) < LOG_INFO)
udev_set_log_priority(udev, LOG_INFO);
break;
case 'h':
rc = adm_help(udev, argc, argv);
goto out;
case 'V':
rc = adm_version(udev, argc, argv);
goto out;
default:
goto out;
}
}
command = argv[optind];
info(udev, "runtime dir '%s'\n", udev_get_run_path(udev));
info(udev, "runtime dir '%s'\n", udev_get_run_path(udev));
if (command != NULL)
for (i = 0; i < ARRAY_SIZE(udevadm_cmds); i++) {
if (strcmp(udevadm_cmds[i]->name, command) == 0) {
argc -= optind;
argv += optind;
optind = 0;
rc = run_command(udev, udevadm_cmds[i], argc, argv);
goto out;
}
}
if (command != NULL)
for (i = 0; i < ARRAY_SIZE(udevadm_cmds); i++) {
if (strcmp(udevadm_cmds[i]->name, command) == 0) {
argc -= optind;
argv += optind;
optind = 0;
rc = run_command(udev, udevadm_cmds[i], argc, argv);
goto out;
}
}
fprintf(stderr, "missing or unknown command\n\n");
adm_help(udev, argc, argv);
rc = 2;
fprintf(stderr, "missing or unknown command\n\n");
adm_help(udev, argc, argv);
rc = 2;
out:
udev_selinux_exit(udev);
udev_unref(udev);
udev_log_close();
return rc;
udev_selinux_exit(udev);
udev_unref(udev);
udev_log_close();
return rc;
}
+1345 -1345
View File
File diff suppressed because it is too large Load Diff
+3 -5
View File
@@ -1,17 +1,15 @@
#!/usr/bin/env sh
#!/bin/sh
# Call the udev rule syntax checker on all rules that we ship
#
# (C) 2010 Canonical Ltd.
# Author: Martin Pitt <martin.pitt@ubuntu.com>
set -e
[ -n "$srcdir" ] || srcdir=`dirname $0`/..
# skip if we don't have python
type python >/dev/null 2>&1 || {
echo "$0: No python installed, skipping udev rule syntax check"
exit 0
echo "$0: No python installed, skipping udev rule syntax check"
exit 0
}
$srcdir/test/rule-syntax-check.py `find $srcdir/rules -name '*.rules'`
+1034 -1034
View File
File diff suppressed because it is too large Load Diff