chiark / gitweb /
udev: support ENV{}=="" global property matches
[elogind.git] / src / libsystemd-terminal / idev-evdev.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright (C) 2014 David Herrmann <dh.herrmann@gmail.com>
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <libevdev/libevdev.h>
25 #include <libudev.h>
26 #include <stdbool.h>
27 #include <stdlib.h>
28 #include <systemd/sd-bus.h>
29 #include <systemd/sd-event.h>
30 #include <unistd.h>
31 #include "bus-util.h"
32 #include "hashmap.h"
33 #include "idev.h"
34 #include "idev-internal.h"
35 #include "macro.h"
36 #include "udev-util.h"
37 #include "util.h"
38
39 typedef struct idev_evdev idev_evdev;
40 typedef struct unmanaged_evdev unmanaged_evdev;
41 typedef struct managed_evdev managed_evdev;
42
43 struct idev_evdev {
44         idev_element element;
45         struct libevdev *evdev;
46         int fd;
47         sd_event_source *fd_src;
48         sd_event_source *idle_src;
49
50         bool unsync : 1;                /* not in-sync with kernel */
51         bool resync : 1;                /* re-syncing with kernel */
52         bool running : 1;
53 };
54
55 struct unmanaged_evdev {
56         idev_evdev evdev;
57         char *devnode;
58 };
59
60 struct managed_evdev {
61         idev_evdev evdev;
62         dev_t devnum;
63         sd_bus_slot *slot_take_device;
64
65         bool requested : 1;             /* TakeDevice() was sent */
66         bool acquired : 1;              /* TakeDevice() was successful */
67 };
68
69 #define idev_evdev_from_element(_e) container_of((_e), idev_evdev, element)
70 #define unmanaged_evdev_from_element(_e) \
71         container_of(idev_evdev_from_element(_e), unmanaged_evdev, evdev)
72 #define managed_evdev_from_element(_e) \
73         container_of(idev_evdev_from_element(_e), managed_evdev, evdev)
74
75 #define IDEV_EVDEV_INIT(_vtable, _session) ((idev_evdev){ \
76                 .element = IDEV_ELEMENT_INIT((_vtable), (_session)), \
77                 .fd = -1, \
78         })
79
80 #define IDEV_EVDEV_NAME_MAX (8 + DECIMAL_STR_MAX(unsigned) * 2)
81
82 static const idev_element_vtable unmanaged_evdev_vtable;
83 static const idev_element_vtable managed_evdev_vtable;
84
85 static int idev_evdev_resume(idev_evdev *evdev, int dev_fd);
86 static void idev_evdev_pause(idev_evdev *evdev, bool release);
87
88 /*
89  * Virtual Evdev Element
90  * The virtual evdev element is the base class of all other evdev elements. It
91  * uses libevdev to access the kernel evdev API. It supports asynchronous
92  * access revocation, re-syncing if events got dropped and more.
93  * This element cannot be used by itself. There must be a wrapper around it
94  * which opens a file-descriptor and passes it to the virtual evdev element.
95  */
96
97 static void idev_evdev_name(char *out, dev_t devnum) {
98         /* @out must be at least of size IDEV_EVDEV_NAME_MAX */
99         sprintf(out, "evdev/%u:%u", major(devnum), minor(devnum));
100 }
101
102 static int idev_evdev_feed_resync(idev_evdev *evdev) {
103         idev_data data = {
104                 .type = IDEV_DATA_RESYNC,
105                 .resync = evdev->resync,
106         };
107
108         return idev_element_feed(&evdev->element, &data);
109 }
110
111 static int idev_evdev_feed_evdev(idev_evdev *evdev, struct input_event *event) {
112         idev_data data = {
113                 .type = IDEV_DATA_EVDEV,
114                 .resync = evdev->resync,
115                 .evdev = {
116                         .event = *event,
117                 },
118         };
119
120         return idev_element_feed(&evdev->element, &data);
121 }
122
123 static void idev_evdev_hup(idev_evdev *evdev) {
124         /*
125          * On HUP, we close the current fd via idev_evdev_pause(). This drops
126          * the event-sources from the main-loop and effectively puts the
127          * element asleep. If the HUP is part of a hotplug-event, a following
128          * udev-notification will destroy the element. Otherwise, the HUP is
129          * either result of access-revokation or a serious error.
130          * For unmanaged devices, we should never receive HUP (except for
131          * unplug-events). But if we do, something went seriously wrong and we
132          * shouldn't try to be clever.
133          * Instead, we simply stay asleep and wait for the device to be
134          * disabled and then re-enabled (or closed and re-opened). This will
135          * re-open the device node and restart the device.
136          * For managed devices, a HUP usually means our device-access was
137          * revoked. In that case, we simply put the device asleep and wait for
138          * logind to notify us once the device is alive again. logind also
139          * passes us a new fd. Hence, we don't have to re-enable the device.
140          *
141          * Long story short: The only thing we have to do here, is close() the
142          * file-descriptor and remove it from the main-loop. Everything else is
143          * handled via additional events we receive.
144          */
145
146         idev_evdev_pause(evdev, true);
147 }
148
149 static int idev_evdev_io(idev_evdev *evdev) {
150         idev_element *e = &evdev->element;
151         struct input_event ev;
152         unsigned int flags;
153         int r, error = 0;
154
155         /*
156          * Read input-events via libevdev until the input-queue is drained. In
157          * case we're disabled, don't do anything. The input-queue might
158          * overflow, but we don't care as we have to resync after wake-up,
159          * anyway.
160          * TODO: libevdev should give us a hint how many events to read. We
161          * really want to avoid starvation, so we shouldn't read forever in
162          * case we cannot keep up with the kernel.
163          * TODO: Make sure libevdev always reports SYN_DROPPED to us, regardless
164          * whether any event was synced afterwards.
165          */
166
167         flags = LIBEVDEV_READ_FLAG_NORMAL;
168         while (e->enabled) {
169                 if (evdev->unsync) {
170                         /* immediately resync, even if in sync right now */
171                         evdev->unsync = false;
172                         evdev->resync = false;
173                         flags = LIBEVDEV_READ_FLAG_NORMAL;
174                         r = libevdev_next_event(evdev->evdev, flags | LIBEVDEV_READ_FLAG_FORCE_SYNC, &ev);
175                         if (r < 0 && r != -EAGAIN) {
176                                 r = 0;
177                                 goto error;
178                         } else if (r != LIBEVDEV_READ_STATUS_SYNC) {
179                                 log_debug("idev-evdev: %s/%s: cannot force resync: %d",
180                                           e->session->name, e->name, r);
181                         }
182                 } else {
183                         r = libevdev_next_event(evdev->evdev, flags, &ev);
184                 }
185
186                 if (evdev->resync && r == -EAGAIN) {
187                         /* end of re-sync */
188                         evdev->resync = false;
189                         flags = LIBEVDEV_READ_FLAG_NORMAL;
190                 } else if (r == -EAGAIN) {
191                         /* no data available */
192                         break;
193                 } else if (r < 0) {
194                         /* read error */
195                         goto error;
196                 } else if (r == LIBEVDEV_READ_STATUS_SYNC) {
197                         if (evdev->resync) {
198                                 /* sync-event */
199                                 r = idev_evdev_feed_evdev(evdev, &ev);
200                                 if (r != 0) {
201                                         error = r;
202                                         break;
203                                 }
204                         } else {
205                                 /* start of sync */
206                                 evdev->resync = true;
207                                 flags = LIBEVDEV_READ_FLAG_SYNC;
208                                 r = idev_evdev_feed_resync(evdev);
209                                 if (r != 0) {
210                                         error = r;
211                                         break;
212                                 }
213                         }
214                 } else {
215                         /* normal event */
216                         r = idev_evdev_feed_evdev(evdev, &ev);
217                         if (r != 0) {
218                                 error = r;
219                                 break;
220                         }
221                 }
222         }
223
224         if (error < 0)
225                 log_debug("idev-evdev: %s/%s: error on data event: %s",
226                           e->session->name, e->name, strerror(-error));
227         return error;
228
229 error:
230         idev_evdev_hup(evdev);
231         return 0; /* idev_evdev_hup() handles the error so discard it */
232 }
233
234 static int idev_evdev_event_fn(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
235         idev_evdev *evdev = userdata;
236
237         /* fetch data as long as EPOLLIN is signalled */
238         if (revents & EPOLLIN)
239                 return idev_evdev_io(evdev);
240
241         if (revents & (EPOLLHUP | EPOLLERR))
242                 idev_evdev_hup(evdev);
243
244         return 0;
245 }
246
247 static int idev_evdev_idle_fn(sd_event_source *s, void *userdata) {
248         idev_evdev *evdev = userdata;
249
250         /*
251          * The idle-event is raised whenever we have to re-sync the libevdev
252          * state from the kernel. We simply call into idev_evdev_io() which
253          * flushes the state and re-syncs it if @unsync is set.
254          * State has to be synced whenever our view of the kernel device is
255          * out of date. This is the case when we open the device, if the
256          * kernel's receive buffer overflows, or on other exceptional
257          * situations. Events during re-syncs must be forwarded to the upper
258          * layers so they can update their view of the device. However, such
259          * events must only be handled passively, as they might be out-of-order
260          * and/or re-ordered. Therefore, we mark them as 'sync' events.
261          */
262
263         if (!evdev->unsync)
264                 return 0;
265
266         return idev_evdev_io(evdev);
267 }
268
269 static void idev_evdev_destroy(idev_evdev *evdev) {
270         assert(evdev);
271         assert(evdev->fd < 0);
272
273         libevdev_free(evdev->evdev);
274         evdev->evdev = NULL;
275 }
276
277 static void idev_evdev_enable(idev_evdev *evdev) {
278         assert(evdev);
279         assert(evdev->fd_src);
280         assert(evdev->idle_src);
281
282         if (evdev->running)
283                 return;
284         if (evdev->fd < 0 || evdev->element.n_open < 1 || !evdev->element.enabled)
285                 return;
286
287         evdev->running = true;
288         sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_ON);
289         sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_ONESHOT);
290 }
291
292 static void idev_evdev_disable(idev_evdev *evdev) {
293         assert(evdev);
294         assert(evdev->fd_src);
295         assert(evdev->idle_src);
296
297         if (!evdev->running)
298                 return;
299
300         evdev->running = false;
301         idev_evdev_feed_resync(evdev);
302         sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
303         sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
304 }
305
306 static int idev_evdev_resume(idev_evdev *evdev, int dev_fd) {
307         idev_element *e = &evdev->element;
308         _cleanup_close_ int fd = dev_fd;
309         int r, flags;
310
311         if (fd < 0 || evdev->fd == fd) {
312                 fd = -1;
313                 idev_evdev_enable(evdev);
314                 return 0;
315         }
316
317         idev_evdev_pause(evdev, true);
318         log_debug("idev-evdev: %s/%s: resume", e->session->name, e->name);
319
320         r = fd_nonblock(fd, true);
321         if (r < 0)
322                 return r;
323
324         r = fd_cloexec(fd, true);
325         if (r < 0)
326                 return r;
327
328         flags = fcntl(fd, F_GETFL, 0);
329         if (flags < 0)
330                 return -errno;
331
332         flags &= O_ACCMODE;
333         if (flags == O_WRONLY)
334                 return -EACCES;
335
336         evdev->element.readable = true;
337         evdev->element.writable = !(flags & O_RDONLY);
338
339         /*
340          * TODO: We *MUST* re-sync the device so we get a delta of the changed
341          * state while we didn't read events from the device. This works just
342          * fine with libevdev_change_fd(), however, libevdev_new_from_fd() (or
343          * libevdev_set_fd()) don't pass us events for the initial device
344          * state. So even if we force a re-sync, we will not get the delta for
345          * the initial device state.
346          * We really need to fix libevdev to support that!
347          */
348         if (evdev->evdev)
349                 r = libevdev_change_fd(evdev->evdev, fd);
350         else
351                 r = libevdev_new_from_fd(fd, &evdev->evdev);
352
353         if (r < 0)
354                 return r;
355
356         r = sd_event_add_io(e->session->context->event,
357                             &evdev->fd_src,
358                             fd,
359                             EPOLLHUP | EPOLLERR | EPOLLIN,
360                             idev_evdev_event_fn,
361                             evdev);
362         if (r < 0)
363                 return r;
364
365         r = sd_event_add_defer(e->session->context->event,
366                                &evdev->idle_src,
367                                idev_evdev_idle_fn,
368                                evdev);
369         if (r < 0) {
370                 evdev->fd_src = sd_event_source_unref(evdev->fd_src);
371                 return r;
372         }
373
374         sd_event_source_set_enabled(evdev->fd_src, SD_EVENT_OFF);
375         sd_event_source_set_enabled(evdev->idle_src, SD_EVENT_OFF);
376
377         evdev->unsync = true;
378         evdev->fd = fd;
379         fd = -1;
380
381         idev_evdev_enable(evdev);
382         return 0;
383 }
384
385 static void idev_evdev_pause(idev_evdev *evdev, bool release) {
386         idev_element *e = &evdev->element;
387
388         if (evdev->fd < 0)
389                 return;
390
391         log_debug("idev-evdev: %s/%s: pause", e->session->name, e->name);
392
393         idev_evdev_disable(evdev);
394         if (release) {
395                 evdev->idle_src = sd_event_source_unref(evdev->idle_src);
396                 evdev->fd_src = sd_event_source_unref(evdev->fd_src);
397                 evdev->fd = safe_close(evdev->fd);
398         }
399 }
400
401 /*
402  * Unmanaged Evdev Element
403  * The unmanaged evdev element opens the evdev node for a given input device
404  * directly (/dev/input/eventX) and thus needs sufficient privileges. It opens
405  * the device only if we really require it and releases it as soon as we're
406  * disabled or closed.
407  * The unmanaged element can be used in all situations where you have direct
408  * access to input device nodes. Unlike managed evdev elements, it can be used
409  * outside of user sessions and in emergency situations where logind is not
410  * available.
411  */
412
413 static void unmanaged_evdev_resume(idev_element *e) {
414         unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
415         int r, fd;
416
417         /*
418          * Unmanaged devices can be acquired on-demand. Therefore, don't
419          * acquire it unless someone opened the device *and* we're enabled.
420          */
421         if (e->n_open < 1 || !e->enabled)
422                 return;
423
424         fd = eu->evdev.fd;
425         if (fd < 0) {
426                 fd = open(eu->devnode, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
427                 if (fd < 0) {
428                         if (errno != EACCES && errno != EPERM) {
429                                 log_debug("idev-evdev: %s/%s: cannot open node %s: %m",
430                                           e->session->name, e->name, eu->devnode);
431                                 return;
432                         }
433
434                         fd = open(eu->devnode, O_RDONLY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
435                         if (fd < 0) {
436                                 log_debug("idev-evdev: %s/%s: cannot open node %s: %m",
437                                           e->session->name, e->name, eu->devnode);
438                                 return;
439                         }
440
441                         e->readable = true;
442                         e->writable = false;
443                 } else {
444                         e->readable = true;
445                         e->writable = true;
446                 }
447         }
448
449         r = idev_evdev_resume(&eu->evdev, fd);
450         if (r < 0)
451                 log_debug("idev-evdev: %s/%s: cannot resume: %s",
452                           e->session->name, e->name, strerror(-r));
453 }
454
455 static void unmanaged_evdev_pause(idev_element *e) {
456         unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
457
458         /*
459          * Release the device if the device is disabled or there is no-one who
460          * opened it. This guarantees we stay only available if we're opened
461          * *and* enabled.
462          */
463
464         idev_evdev_pause(&eu->evdev, true);
465 }
466
467 static int unmanaged_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
468         _cleanup_(idev_element_freep) idev_element *e = NULL;
469         char name[IDEV_EVDEV_NAME_MAX];
470         unmanaged_evdev *eu;
471         const char *devnode;
472         dev_t devnum;
473         int r;
474
475         assert_return(s, -EINVAL);
476         assert_return(ud, -EINVAL);
477
478         devnode = udev_device_get_devnode(ud);
479         devnum = udev_device_get_devnum(ud);
480         if (!devnode || devnum == 0)
481                 return -ENODEV;
482
483         idev_evdev_name(name, devnum);
484
485         eu = new0(unmanaged_evdev, 1);
486         if (!eu)
487                 return -ENOMEM;
488
489         e = &eu->evdev.element;
490         eu->evdev = IDEV_EVDEV_INIT(&unmanaged_evdev_vtable, s);
491
492         eu->devnode = strdup(devnode);
493         if (!eu->devnode)
494                 return -ENOMEM;
495
496         r = idev_element_add(e, name);
497         if (r < 0)
498                 return r;
499
500         if (out)
501                 *out = e;
502         e = NULL;
503         return 0;
504 }
505
506 static void unmanaged_evdev_free(idev_element *e) {
507         unmanaged_evdev *eu = unmanaged_evdev_from_element(e);
508
509         idev_evdev_destroy(&eu->evdev);
510         free(eu->devnode);
511         free(eu);
512 }
513
514 static const idev_element_vtable unmanaged_evdev_vtable = {
515         .free                   = unmanaged_evdev_free,
516         .enable                 = unmanaged_evdev_resume,
517         .disable                = unmanaged_evdev_pause,
518         .open                   = unmanaged_evdev_resume,
519         .close                  = unmanaged_evdev_pause,
520 };
521
522 /*
523  * Managed Evdev Element
524  * The managed evdev element uses systemd-logind to acquire evdev devices. This
525  * means, we do not open the device node /dev/input/eventX directly. Instead,
526  * logind passes us a file-descriptor whenever our session is activated. Thus,
527  * we don't need access to the device node directly.
528  * Furthermore, whenever the session is put asleep, logind revokes the
529  * file-descriptor so we loose access to the device.
530  * Managed evdev elements should be preferred over unmanaged elements whenever
531  * you run inside a user session with exclusive device access.
532  */
533
534 static int managed_evdev_take_device_fn(sd_bus *bus,
535                                         sd_bus_message *reply,
536                                         void *userdata,
537                                         sd_bus_error *ret_error) {
538         managed_evdev *em = userdata;
539         idev_element *e = &em->evdev.element;
540         idev_session *s = e->session;
541         int r, paused, fd;
542
543         em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
544
545         if (sd_bus_message_is_method_error(reply, NULL)) {
546                 const sd_bus_error *error = sd_bus_message_get_error(reply);
547
548                 log_debug("idev-evdev: %s/%s: TakeDevice failed: %s: %s",
549                           s->name, e->name, error->name, error->message);
550                 return 0;
551         }
552
553         em->acquired = true;
554
555         r = sd_bus_message_read(reply, "hb", &fd, &paused);
556         if (r < 0) {
557                 log_debug("idev-evdev: %s/%s: erroneous TakeDevice reply", s->name, e->name);
558                 return 0;
559         }
560
561         /* If the device is paused, ignore it; we will get the next fd via
562          * ResumeDevice signals. */
563         if (paused)
564                 return 0;
565
566         fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
567         if (fd < 0) {
568                 log_debug("idev-evdev: %s/%s: cannot duplicate evdev fd: %m", s->name, e->name);
569                 return 0;
570         }
571
572         r = idev_evdev_resume(&em->evdev, fd);
573         if (r < 0)
574                 log_debug("idev-evdev: %s/%s: cannot resume: %s",
575                           s->name, e->name, strerror(-r));
576
577         return 0;
578 }
579
580 static void managed_evdev_enable(idev_element *e) {
581         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
582         managed_evdev *em = managed_evdev_from_element(e);
583         idev_session *s = e->session;
584         idev_context *c = s->context;
585         int r;
586
587         /*
588          * Acquiring managed devices is heavy, so do it only once we're
589          * enabled *and* opened by someone.
590          */
591         if (e->n_open < 1 || !e->enabled)
592                 return;
593
594         /* bail out if already pending */
595         if (em->requested)
596                 return;
597
598         r = sd_bus_message_new_method_call(c->sysbus,
599                                            &m,
600                                            "org.freedesktop.login1",
601                                            s->path,
602                                            "org.freedesktop.login1.Session",
603                                            "TakeDevice");
604         if (r < 0)
605                 goto error;
606
607         r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
608         if (r < 0)
609                 goto error;
610
611         r = sd_bus_call_async(c->sysbus,
612                               &em->slot_take_device,
613                               m,
614                               managed_evdev_take_device_fn,
615                               em,
616                               0);
617         if (r < 0)
618                 goto error;
619
620         em->requested = true;
621         return;
622
623 error:
624         log_debug("idev-evdev: %s/%s: cannot send TakeDevice request: %s",
625                   s->name, e->name, strerror(-r));
626 }
627
628 static void managed_evdev_disable(idev_element *e) {
629         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
630         managed_evdev *em = managed_evdev_from_element(e);
631         idev_session *s = e->session;
632         idev_context *c = s->context;
633         int r;
634
635         /*
636          * Releasing managed devices is heavy. Once acquired, we get
637          * notifications for sleep/wake-up events, so there's no reason to
638          * release it if disabled but opened. However, if a device is closed,
639          * we release it immediately as we don't care for sleep/wake-up events
640          * then (even if we're actually enabled).
641          */
642
643         idev_evdev_pause(&em->evdev, false);
644
645         if (e->n_open > 0 || !em->requested)
646                 return;
647
648         /*
649          * If TakeDevice() is pending or was successful, make sure to
650          * release the device again. We don't care for return-values,
651          * so send it without waiting or callbacks.
652          * If a failed TakeDevice() is pending, but someone else took
653          * the device on the same bus-connection, we might incorrectly
654          * release their device. This is an unlikely race, though.
655          * Furthermore, you really shouldn't have two users of the
656          * controller-API on the same session, on the same devices, *AND* on
657          * the same bus-connection. So we don't care for that race..
658          */
659
660         idev_evdev_pause(&em->evdev, true);
661         em->requested = false;
662
663         if (!em->acquired && !em->slot_take_device)
664                 return;
665
666         em->slot_take_device = sd_bus_slot_unref(em->slot_take_device);
667         em->acquired = false;
668
669         r = sd_bus_message_new_method_call(c->sysbus,
670                                            &m,
671                                            "org.freedesktop.login1",
672                                            s->path,
673                                            "org.freedesktop.login1.Session",
674                                            "ReleaseDevice");
675         if (r >= 0) {
676                 r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
677                 if (r >= 0)
678                         r = sd_bus_send(c->sysbus, m, NULL);
679         }
680
681         if (r < 0 && r != -ENOTCONN)
682                 log_debug("idev-evdev: %s/%s: cannot send ReleaseDevice: %s",
683                           s->name, e->name, strerror(-r));
684 }
685
686 static void managed_evdev_resume(idev_element *e, int fd) {
687         managed_evdev *em = managed_evdev_from_element(e);
688         idev_session *s = e->session;
689         int r;
690
691         /*
692          * We get ResumeDevice signals whenever logind resumed a previously
693          * paused device. The arguments contain the major/minor number of the
694          * related device and a new file-descriptor for the freshly opened
695          * device-node. We take the file-descriptor and immediately resume the
696          * device.
697          */
698
699         fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
700         if (fd < 0) {
701                 log_debug("idev-evdev: %s/%s: cannot duplicate evdev fd: %m",
702                           s->name, e->name);
703                 return;
704         }
705
706         r = idev_evdev_resume(&em->evdev, fd);
707         if (r < 0)
708                 log_debug("idev-evdev: %s/%s: cannot resume: %s",
709                           s->name, e->name, strerror(-r));
710
711         return;
712 }
713
714 static void managed_evdev_pause(idev_element *e, const char *mode) {
715         managed_evdev *em = managed_evdev_from_element(e);
716         idev_session *s = e->session;
717         idev_context *c = s->context;
718         int r;
719
720         /*
721          * We get PauseDevice() signals from logind whenever a device we
722          * requested was, or is about to be, paused. Arguments are major/minor
723          * number of the device and the mode of the operation.
724          * We treat it as asynchronous access-revocation (as if we got HUP on
725          * the device fd). Note that we might have already treated the HUP
726          * event via EPOLLHUP, whichever comes first.
727          *
728          * @mode can be one of the following:
729          *   "pause": The device is about to be paused. We must react
730          *            immediately and respond with PauseDeviceComplete(). Once
731          *            we replied, logind will pause the device. Note that
732          *            logind might apply any kind of timeout and force pause
733          *            the device if we don't respond in a timely manner. In
734          *            this case, we will receive a second PauseDevice event
735          *            with @mode set to "force" (or similar).
736          *   "force": The device was disabled forecfully by logind. Access is
737          *            already revoked. This is just an asynchronous
738          *            notification so we can put the device asleep (in case
739          *            we didn't already notice the access revocation).
740          *    "gone": This is like "force" but is sent if the device was
741          *            paused due to a device-removal event.
742          *
743          * We always handle PauseDevice signals as "force" as we properly
744          * support asynchronous access revocation, anyway. But in case logind
745          * sent mode "pause", we also call PauseDeviceComplete() to immediately
746          * acknowledge the request.
747          */
748
749         idev_evdev_pause(&em->evdev, true);
750
751         if (streq(mode, "pause")) {
752                 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
753
754                 /*
755                  * Sending PauseDeviceComplete() is racy if logind triggers the
756                  * timeout. That is, if we take too long and logind pauses the
757                  * device by sending a forced PauseDevice, our
758                  * PauseDeviceComplete call will be stray. That's fine, though.
759                  * logind ignores such stray calls. Only if logind also sent a
760                  * further PauseDevice() signal, it might match our call
761                  * incorrectly to the newer PauseDevice(). That's fine, too, as
762                  * we handle that event asynchronously, anyway. Therefore,
763                  * whatever happens, we're fine. Yay!
764                  */
765
766                 r = sd_bus_message_new_method_call(c->sysbus,
767                                                    &m,
768                                                    "org.freedesktop.login1",
769                                                    s->path,
770                                                    "org.freedesktop.login1.Session",
771                                                    "PauseDeviceComplete");
772                 if (r >= 0) {
773                         r = sd_bus_message_append(m, "uu", major(em->devnum), minor(em->devnum));
774                         if (r >= 0)
775                                 r = sd_bus_send(c->sysbus, m, NULL);
776                 }
777
778                 if (r < 0)
779                         log_debug("idev-evdev: %s/%s: cannot send PauseDeviceComplete: %s",
780                                   s->name, e->name, strerror(-r));
781         }
782 }
783
784 static int managed_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
785         _cleanup_(idev_element_freep) idev_element *e = NULL;
786         char name[IDEV_EVDEV_NAME_MAX];
787         managed_evdev *em;
788         dev_t devnum;
789         int r;
790
791         assert_return(s, -EINVAL);
792         assert_return(s->managed, -EINVAL);
793         assert_return(s->context->sysbus, -EINVAL);
794         assert_return(ud, -EINVAL);
795
796         devnum = udev_device_get_devnum(ud);
797         if (devnum == 0)
798                 return -ENODEV;
799
800         idev_evdev_name(name, devnum);
801
802         em = new0(managed_evdev, 1);
803         if (!em)
804                 return -ENOMEM;
805
806         e = &em->evdev.element;
807         em->evdev = IDEV_EVDEV_INIT(&managed_evdev_vtable, s);
808         em->devnum = devnum;
809
810         r = idev_element_add(e, name);
811         if (r < 0)
812                 return r;
813
814         if (out)
815                 *out = e;
816         e = NULL;
817         return 0;
818 }
819
820 static void managed_evdev_free(idev_element *e) {
821         managed_evdev *em = managed_evdev_from_element(e);
822
823         idev_evdev_destroy(&em->evdev);
824         free(em);
825 }
826
827 static const idev_element_vtable managed_evdev_vtable = {
828         .free                   = managed_evdev_free,
829         .enable                 = managed_evdev_enable,
830         .disable                = managed_evdev_disable,
831         .open                   = managed_evdev_enable,
832         .close                  = managed_evdev_disable,
833         .resume                 = managed_evdev_resume,
834         .pause                  = managed_evdev_pause,
835 };
836
837 /*
838  * Generic Constructor
839  * Instead of relying on the caller to choose between managed and unmanaged
840  * evdev devices, the idev_evdev_new() constructor does that for you (by
841  * looking at s->managed).
842  */
843
844 bool idev_is_evdev(idev_element *e) {
845         return e && (e->vtable == &unmanaged_evdev_vtable ||
846                      e->vtable == &managed_evdev_vtable);
847 }
848
849 idev_element *idev_find_evdev(idev_session *s, dev_t devnum) {
850         char name[IDEV_EVDEV_NAME_MAX];
851
852         assert_return(s, NULL);
853         assert_return(devnum != 0, NULL);
854
855         idev_evdev_name(name, devnum);
856         return idev_find_element(s, name);
857 }
858
859 int idev_evdev_new(idev_element **out, idev_session *s, struct udev_device *ud) {
860         assert_return(s, -EINVAL);
861         assert_return(ud, -EINVAL);
862
863         return s->managed ? managed_evdev_new(out, s, ud) : unmanaged_evdev_new(out, s, ud);
864 }