chiark / gitweb /
libudev: udev_device_add_property - implicitly mark properties for saving to db
[elogind.git] / src / libudev / libudev-device.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2008-2012 Kay Sievers <kay@vrfy.org>
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <unistd.h>
24 #include <stdbool.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <dirent.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 #include <net/if.h>
31 #include <sys/stat.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <linux/sockios.h>
35
36 #include "libudev.h"
37 #include "libudev-private.h"
38
39 static int udev_device_set_devnode(struct udev_device *udev_device, const char *devnode);
40 static struct udev_list_entry *udev_device_add_property_internal(struct udev_device *udev_device, const char *key, const char *value);
41
42 /**
43  * SECTION:libudev-device
44  * @short_description: kernel sys devices
45  *
46  * Representation of kernel sys devices. Devices are uniquely identified
47  * by their syspath, every device has exactly one path in the kernel sys
48  * filesystem. Devices usually belong to a kernel subsystem, and have
49  * a unique name inside that subsystem.
50  */
51
52 /**
53  * udev_device:
54  *
55  * Opaque object representing one kernel sys device.
56  */
57 struct udev_device {
58         struct udev *udev;
59         struct udev_device *parent_device;
60         char *syspath;
61         const char *devpath;
62         char *sysname;
63         const char *sysnum;
64         char *devnode;
65         mode_t devnode_mode;
66         uid_t devnode_uid;
67         gid_t devnode_gid;
68         char *subsystem;
69         char *devtype;
70         char *driver;
71         char *action;
72         char *devpath_old;
73         char *id_filename;
74         char **envp;
75         char *monitor_buf;
76         size_t monitor_buf_len;
77         struct udev_list devlinks_list;
78         struct udev_list properties_list;
79         struct udev_list sysattr_value_list;
80         struct udev_list sysattr_list;
81         struct udev_list tags_list;
82         unsigned long long int seqnum;
83         usec_t usec_initialized;
84         int devlink_priority;
85         int refcount;
86         dev_t devnum;
87         int ifindex;
88         int watch_handle;
89         int maj, min;
90         bool parent_set;
91         bool subsystem_set;
92         bool devtype_set;
93         bool devlinks_uptodate;
94         bool envp_uptodate;
95         bool tags_uptodate;
96         bool driver_set;
97         bool info_loaded;
98         bool db_loaded;
99         bool uevent_loaded;
100         bool is_initialized;
101         bool sysattr_list_read;
102         bool db_persist;
103 };
104
105 /**
106  * udev_device_get_seqnum:
107  * @udev_device: udev device
108  *
109  * This is only valid if the device was received through a monitor. Devices read from
110  * sys do not have a sequence number.
111  *
112  * Returns: the kernel event sequence number, or 0 if there is no sequence number available.
113  **/
114 _public_ unsigned long long int udev_device_get_seqnum(struct udev_device *udev_device)
115 {
116         if (udev_device == NULL)
117                 return 0;
118         return udev_device->seqnum;
119 }
120
121 static int udev_device_set_seqnum(struct udev_device *udev_device, unsigned long long int seqnum)
122 {
123         char num[32];
124
125         udev_device->seqnum = seqnum;
126         snprintf(num, sizeof(num), "%llu", seqnum);
127         udev_device_add_property_internal(udev_device, "SEQNUM", num);
128         return 0;
129 }
130
131 int udev_device_get_ifindex(struct udev_device *udev_device)
132 {
133         if (!udev_device->info_loaded)
134                 udev_device_read_uevent_file(udev_device);
135         return udev_device->ifindex;
136 }
137
138 static int udev_device_set_ifindex(struct udev_device *udev_device, int ifindex)
139 {
140         char num[32];
141
142         udev_device->ifindex = ifindex;
143         snprintf(num, sizeof(num), "%d", ifindex);
144         udev_device_add_property_internal(udev_device, "IFINDEX", num);
145         return 0;
146 }
147
148 /**
149  * udev_device_get_devnum:
150  * @udev_device: udev device
151  *
152  * Get the device major/minor number.
153  *
154  * Returns: the dev_t number.
155  **/
156 _public_ dev_t udev_device_get_devnum(struct udev_device *udev_device)
157 {
158         if (udev_device == NULL)
159                 return makedev(0, 0);
160         if (!udev_device->info_loaded)
161                 udev_device_read_uevent_file(udev_device);
162         return udev_device->devnum;
163 }
164
165 static int udev_device_set_devnum(struct udev_device *udev_device, dev_t devnum)
166 {
167         char num[32];
168
169         udev_device->devnum = devnum;
170
171         snprintf(num, sizeof(num), "%u", major(devnum));
172         udev_device_add_property_internal(udev_device, "MAJOR", num);
173         snprintf(num, sizeof(num), "%u", minor(devnum));
174         udev_device_add_property_internal(udev_device, "MINOR", num);
175         return 0;
176 }
177
178 const char *udev_device_get_devpath_old(struct udev_device *udev_device)
179 {
180         return udev_device->devpath_old;
181 }
182
183 static int udev_device_set_devpath_old(struct udev_device *udev_device, const char *devpath_old)
184 {
185         const char *pos;
186
187         free(udev_device->devpath_old);
188         udev_device->devpath_old = strdup(devpath_old);
189         if (udev_device->devpath_old == NULL)
190                 return -ENOMEM;
191         udev_device_add_property_internal(udev_device, "DEVPATH_OLD", udev_device->devpath_old);
192
193         pos = strrchr(udev_device->devpath_old, '/');
194         if (pos == NULL)
195                 return -EINVAL;
196         return 0;
197 }
198
199 /**
200  * udev_device_get_driver:
201  * @udev_device: udev device
202  *
203  * Get the kernel driver name.
204  *
205  * Returns: the driver name string, or #NULL if there is no driver attached.
206  **/
207 _public_ const char *udev_device_get_driver(struct udev_device *udev_device)
208 {
209         char driver[UTIL_NAME_SIZE];
210
211         if (udev_device == NULL)
212                 return NULL;
213         if (!udev_device->driver_set) {
214                 udev_device->driver_set = true;
215                 if (util_get_sys_core_link_value(udev_device->udev, "driver", udev_device->syspath, driver, sizeof(driver)) > 0)
216                         udev_device->driver = strdup(driver);
217         }
218         return udev_device->driver;
219 }
220
221 static int udev_device_set_driver(struct udev_device *udev_device, const char *driver)
222 {
223         free(udev_device->driver);
224         udev_device->driver = strdup(driver);
225         if (udev_device->driver == NULL)
226                 return -ENOMEM;
227         udev_device->driver_set = true;
228         udev_device_add_property_internal(udev_device, "DRIVER", udev_device->driver);
229         return 0;
230 }
231
232 /**
233  * udev_device_get_devtype:
234  * @udev_device: udev device
235  *
236  * Retrieve the devtype string of the udev device.
237  *
238  * Returns: the devtype name of the udev device, or #NULL if it can not be determined
239  **/
240 _public_ const char *udev_device_get_devtype(struct udev_device *udev_device)
241 {
242         if (udev_device == NULL)
243                 return NULL;
244         if (!udev_device->devtype_set) {
245                 udev_device->devtype_set = true;
246                 udev_device_read_uevent_file(udev_device);
247         }
248         return udev_device->devtype;
249 }
250
251 static int udev_device_set_devtype(struct udev_device *udev_device, const char *devtype)
252 {
253         free(udev_device->devtype);
254         udev_device->devtype = strdup(devtype);
255         if (udev_device->devtype == NULL)
256                 return -ENOMEM;
257         udev_device->devtype_set = true;
258         udev_device_add_property_internal(udev_device, "DEVTYPE", udev_device->devtype);
259         return 0;
260 }
261
262 static int udev_device_set_subsystem(struct udev_device *udev_device, const char *subsystem)
263 {
264         free(udev_device->subsystem);
265         udev_device->subsystem = strdup(subsystem);
266         if (udev_device->subsystem == NULL)
267                 return -ENOMEM;
268         udev_device->subsystem_set = true;
269         udev_device_add_property_internal(udev_device, "SUBSYSTEM", udev_device->subsystem);
270         return 0;
271 }
272
273 /**
274  * udev_device_get_subsystem:
275  * @udev_device: udev device
276  *
277  * Retrieve the subsystem string of the udev device. The string does not
278  * contain any "/".
279  *
280  * Returns: the subsystem name of the udev device, or #NULL if it can not be determined
281  **/
282 _public_ const char *udev_device_get_subsystem(struct udev_device *udev_device)
283 {
284         char subsystem[UTIL_NAME_SIZE];
285
286         if (udev_device == NULL)
287                 return NULL;
288         if (!udev_device->subsystem_set) {
289                 udev_device->subsystem_set = true;
290                 /* read "subsystem" link */
291                 if (util_get_sys_core_link_value(udev_device->udev, "subsystem", udev_device->syspath, subsystem, sizeof(subsystem)) > 0) {
292                         udev_device_set_subsystem(udev_device, subsystem);
293                         return udev_device->subsystem;
294                 }
295                 /* implicit names */
296                 if (startswith(udev_device->devpath, "/module/")) {
297                         udev_device_set_subsystem(udev_device, "module");
298                         return udev_device->subsystem;
299                 }
300                 if (strstr(udev_device->devpath, "/drivers/") != NULL) {
301                         udev_device_set_subsystem(udev_device, "drivers");
302                         return udev_device->subsystem;
303                 }
304                 if (startswith(udev_device->devpath, "/subsystem/") ||
305                     startswith(udev_device->devpath, "/class/") ||
306                     startswith(udev_device->devpath, "/bus/")) {
307                         udev_device_set_subsystem(udev_device, "subsystem");
308                         return udev_device->subsystem;
309                 }
310         }
311         return udev_device->subsystem;
312 }
313
314 mode_t udev_device_get_devnode_mode(struct udev_device *udev_device)
315 {
316         if (!udev_device->info_loaded)
317                 udev_device_read_uevent_file(udev_device);
318         return udev_device->devnode_mode;
319 }
320
321 static int udev_device_set_devnode_mode(struct udev_device *udev_device, mode_t mode)
322 {
323         char num[32];
324
325         udev_device->devnode_mode = mode;
326         snprintf(num, sizeof(num), "%#o", mode);
327         udev_device_add_property_internal(udev_device, "DEVMODE", num);
328         return 0;
329 }
330
331 uid_t udev_device_get_devnode_uid(struct udev_device *udev_device)
332 {
333         if (!udev_device->info_loaded)
334                 udev_device_read_uevent_file(udev_device);
335         return udev_device->devnode_uid;
336 }
337
338 static int udev_device_set_devnode_uid(struct udev_device *udev_device, uid_t uid)
339 {
340         char num[32];
341
342         udev_device->devnode_uid = uid;
343         snprintf(num, sizeof(num), "%u", uid);
344         udev_device_add_property_internal(udev_device, "DEVUID", num);
345         return 0;
346 }
347
348 gid_t udev_device_get_devnode_gid(struct udev_device *udev_device)
349 {
350         if (!udev_device->info_loaded)
351                 udev_device_read_uevent_file(udev_device);
352         return udev_device->devnode_gid;
353 }
354
355 static int udev_device_set_devnode_gid(struct udev_device *udev_device, gid_t gid)
356 {
357         char num[32];
358
359         udev_device->devnode_gid = gid;
360         snprintf(num, sizeof(num), "%u", gid);
361         udev_device_add_property_internal(udev_device, "DEVGID", num);
362         return 0;
363 }
364
365 static struct udev_list_entry *udev_device_add_property_internal(struct udev_device *udev_device, const char *key, const char *value)
366 {
367         udev_device->envp_uptodate = false;
368         if (value == NULL) {
369                 struct udev_list_entry *list_entry;
370
371                 list_entry = udev_device_get_properties_list_entry(udev_device);
372                 list_entry = udev_list_entry_get_by_name(list_entry, key);
373                 if (list_entry != NULL)
374                         udev_list_entry_delete(list_entry);
375                 return NULL;
376         }
377         return udev_list_entry_add(&udev_device->properties_list, key, value);
378 }
379
380
381 int udev_device_add_property(struct udev_device *udev_device, const char *key, const char *value)
382 {
383         struct udev_list_entry *property;
384
385         property = udev_device_add_property_internal(udev_device, key, value);
386
387         /* store in db, skip private keys */
388         if (key[0] != '.')
389                 udev_list_entry_set_num(property, true);
390
391         return 0;
392 }
393
394 static struct udev_list_entry *udev_device_add_property_from_string(struct udev_device *udev_device, const char *property)
395 {
396         char name[UTIL_LINE_SIZE];
397         char *val;
398
399         strscpy(name, sizeof(name), property);
400         val = strchr(name, '=');
401         if (val == NULL)
402                 return NULL;
403         val[0] = '\0';
404         val = &val[1];
405         if (val[0] == '\0')
406                 val = NULL;
407         return udev_device_add_property_internal(udev_device, name, val);
408 }
409
410 static int udev_device_set_syspath(struct udev_device *udev_device, const char *syspath)
411 {
412         const char *pos;
413         size_t len;
414
415         free(udev_device->syspath);
416         udev_device->syspath = strdup(syspath);
417         if (udev_device->syspath ==  NULL)
418                 return -ENOMEM;
419         udev_device->devpath = udev_device->syspath + strlen("/sys");
420         udev_device_add_property_internal(udev_device, "DEVPATH", udev_device->devpath);
421
422         pos = strrchr(udev_device->syspath, '/');
423         if (pos == NULL)
424                 return -EINVAL;
425         udev_device->sysname = strdup(&pos[1]);
426         if (udev_device->sysname == NULL)
427                 return -ENOMEM;
428
429         /* some devices have '!' in their name, change that to '/' */
430         len = 0;
431         while (udev_device->sysname[len] != '\0') {
432                 if (udev_device->sysname[len] == '!')
433                         udev_device->sysname[len] = '/';
434                 len++;
435         }
436
437         /* trailing number */
438         while (len > 0 && isdigit(udev_device->sysname[--len]))
439                 udev_device->sysnum = &udev_device->sysname[len];
440
441         /* sysname is completely numeric */
442         if (len == 0)
443                 udev_device->sysnum = NULL;
444
445         return 0;
446 }
447
448 /*
449  * parse property string, and if needed, update internal values accordingly
450  *
451  * udev_device_add_property_from_string_parse_finish() needs to be
452  * called after adding properties, and its return value checked
453  *
454  * udev_device_set_info_loaded() needs to be set, to avoid trying
455  * to use a device without a DEVPATH set
456  */
457 static void udev_device_add_property_from_string_parse(struct udev_device *udev_device, const char *property)
458 {
459         if (startswith(property, "DEVPATH=")) {
460                 char path[UTIL_PATH_SIZE];
461
462                 strscpyl(path, sizeof(path), "/sys", &property[8], NULL);
463                 udev_device_set_syspath(udev_device, path);
464         } else if (startswith(property, "SUBSYSTEM=")) {
465                 udev_device_set_subsystem(udev_device, &property[10]);
466         } else if (startswith(property, "DEVTYPE=")) {
467                 udev_device_set_devtype(udev_device, &property[8]);
468         } else if (startswith(property, "DEVNAME=")) {
469                 udev_device_set_devnode(udev_device, &property[8]);
470         } else if (startswith(property, "DEVLINKS=")) {
471                 char devlinks[UTIL_PATH_SIZE];
472                 char *slink;
473                 char *next;
474
475                 strscpy(devlinks, sizeof(devlinks), &property[9]);
476                 slink = devlinks;
477                 next = strchr(slink, ' ');
478                 while (next != NULL) {
479                         next[0] = '\0';
480                         udev_device_add_devlink(udev_device, slink);
481                         slink = &next[1];
482                         next = strchr(slink, ' ');
483                 }
484                 if (slink[0] != '\0')
485                         udev_device_add_devlink(udev_device, slink);
486         } else if (startswith(property, "TAGS=")) {
487                 char tags[UTIL_PATH_SIZE];
488                 char *next;
489
490                 strscpy(tags, sizeof(tags), &property[5]);
491                 next = strchr(tags, ':');
492                 if (next != NULL) {
493                         next++;
494                         while (next[0] != '\0') {
495                                 char *tag;
496
497                                 tag = next;
498                                 next = strchr(tag, ':');
499                                 if (next == NULL)
500                                         break;
501                                 next[0] = '\0';
502                                 next++;
503                                 udev_device_add_tag(udev_device, tag);
504                         }
505                 }
506         } else if (startswith(property, "USEC_INITIALIZED=")) {
507                 udev_device_set_usec_initialized(udev_device, strtoull(&property[19], NULL, 10));
508         } else if (startswith(property, "DRIVER=")) {
509                 udev_device_set_driver(udev_device, &property[7]);
510         } else if (startswith(property, "ACTION=")) {
511                 udev_device_set_action(udev_device, &property[7]);
512         } else if (startswith(property, "MAJOR=")) {
513                 udev_device->maj = strtoull(&property[6], NULL, 10);
514         } else if (startswith(property, "MINOR=")) {
515                 udev_device->min = strtoull(&property[6], NULL, 10);
516         } else if (startswith(property, "DEVPATH_OLD=")) {
517                 udev_device_set_devpath_old(udev_device, &property[12]);
518         } else if (startswith(property, "SEQNUM=")) {
519                 udev_device_set_seqnum(udev_device, strtoull(&property[7], NULL, 10));
520         } else if (startswith(property, "IFINDEX=")) {
521                 udev_device_set_ifindex(udev_device, strtoull(&property[8], NULL, 10));
522         } else if (startswith(property, "DEVMODE=")) {
523                 udev_device_set_devnode_mode(udev_device, strtoul(&property[8], NULL, 8));
524         } else if (startswith(property, "DEVUID=")) {
525                 udev_device_set_devnode_uid(udev_device, strtoul(&property[7], NULL, 10));
526         } else if (startswith(property, "DEVGID=")) {
527                 udev_device_set_devnode_gid(udev_device, strtoul(&property[7], NULL, 10));
528         } else {
529                 udev_device_add_property_from_string(udev_device, property);
530         }
531 }
532
533 static int udev_device_add_property_from_string_parse_finish(struct udev_device *udev_device)
534 {
535         if (udev_device->maj > 0)
536                 udev_device_set_devnum(udev_device, makedev(udev_device->maj, udev_device->min));
537         udev_device->maj = 0;
538         udev_device->min = 0;
539
540         if (udev_device->devpath == NULL || udev_device->subsystem == NULL)
541                 return -EINVAL;
542         return 0;
543 }
544
545 /**
546  * udev_device_get_property_value:
547  * @udev_device: udev device
548  * @key: property name
549  *
550  * Get the value of a given property.
551  *
552  * Returns: the property string, or #NULL if there is no such property.
553  **/
554 _public_ const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key)
555 {
556         struct udev_list_entry *list_entry;
557
558         if (udev_device == NULL)
559                 return NULL;
560         if (key == NULL)
561                 return NULL;
562
563         list_entry = udev_device_get_properties_list_entry(udev_device);
564         list_entry = udev_list_entry_get_by_name(list_entry, key);
565         return udev_list_entry_get_value(list_entry);
566 }
567
568 int udev_device_read_db(struct udev_device *udev_device, const char *dbfile)
569 {
570         char filename[UTIL_PATH_SIZE];
571         char line[UTIL_LINE_SIZE];
572         FILE *f;
573
574         /* providing a database file will always force-load it */
575         if (dbfile == NULL) {
576                 const char *id;
577
578                 if (udev_device->db_loaded)
579                         return 0;
580                 udev_device->db_loaded = true;
581
582                 id = udev_device_get_id_filename(udev_device);
583                 if (id == NULL)
584                         return -1;
585                 strscpyl(filename, sizeof(filename), "/run/udev/data/", id, NULL);
586                 dbfile = filename;
587         }
588
589         f = fopen(dbfile, "re");
590         if (f == NULL)
591                 return log_debug_errno(errno, "no db file to read %s: %m", dbfile);
592
593         /* devices with a database entry are initialized */
594         udev_device->is_initialized = true;
595
596         while (fgets(line, sizeof(line), f)) {
597                 ssize_t len;
598                 const char *val;
599                 struct udev_list_entry *entry;
600
601                 len = strlen(line);
602                 if (len < 4)
603                         break;
604                 line[len-1] = '\0';
605                 val = &line[2];
606                 switch(line[0]) {
607                 case 'S':
608                         strscpyl(filename, sizeof(filename), "/dev/", val, NULL);
609                         udev_device_add_devlink(udev_device, filename);
610                         break;
611                 case 'L':
612                         udev_device_set_devlink_priority(udev_device, atoi(val));
613                         break;
614                 case 'E':
615                         entry = udev_device_add_property_from_string(udev_device, val);
616                         udev_list_entry_set_num(entry, true);
617                         break;
618                 case 'G':
619                         udev_device_add_tag(udev_device, val);
620                         break;
621                 case 'W':
622                         udev_device_set_watch_handle(udev_device, atoi(val));
623                         break;
624                 case 'I':
625                         udev_device_set_usec_initialized(udev_device, strtoull(val, NULL, 10));
626                         break;
627                 }
628         }
629         fclose(f);
630
631         log_debug("device %p filled with db file data", udev_device);
632         return 0;
633 }
634
635 int udev_device_read_uevent_file(struct udev_device *udev_device)
636 {
637         char filename[UTIL_PATH_SIZE];
638         FILE *f;
639         char line[UTIL_LINE_SIZE];
640         int maj = 0;
641         int min = 0;
642
643         if (udev_device->uevent_loaded)
644                 return 0;
645
646         strscpyl(filename, sizeof(filename), udev_device->syspath, "/uevent", NULL);
647         f = fopen(filename, "re");
648         if (f == NULL)
649                 return -errno;
650         udev_device->uevent_loaded = true;
651
652         while (fgets(line, sizeof(line), f)) {
653                 char *pos;
654
655                 pos = strchr(line, '\n');
656                 if (pos == NULL)
657                         continue;
658                 pos[0] = '\0';
659
660                 if (startswith(line, "DEVTYPE=")) {
661                         udev_device_set_devtype(udev_device, &line[8]);
662                         continue;
663                 }
664                 if (startswith(line, "IFINDEX=")) {
665                         udev_device_set_ifindex(udev_device, strtoull(&line[8], NULL, 10));
666                         continue;
667                 }
668                 if (startswith(line, "DEVNAME=")) {
669                         udev_device_set_devnode(udev_device, &line[8]);
670                         continue;
671                 }
672
673                 if (startswith(line, "MAJOR="))
674                         maj = strtoull(&line[6], NULL, 10);
675                 else if (startswith(line, "MINOR="))
676                         min = strtoull(&line[6], NULL, 10);
677                 else if (startswith(line, "DEVMODE="))
678                         udev_device->devnode_mode = strtoul(&line[8], NULL, 8);
679
680                 udev_device_add_property_from_string(udev_device, line);
681         }
682
683         udev_device->devnum = makedev(maj, min);
684         fclose(f);
685         return 0;
686 }
687
688 void udev_device_set_info_loaded(struct udev_device *device)
689 {
690         device->info_loaded = true;
691 }
692
693 static struct udev_device *udev_device_new(struct udev *udev)
694 {
695         struct udev_device *udev_device;
696
697         if (udev == NULL) {
698                 errno = EINVAL;
699                 return NULL;
700         }
701
702         udev_device = new0(struct udev_device, 1);
703         if (udev_device == NULL) {
704                 errno = ENOMEM;
705                 return NULL;
706         }
707         udev_device->refcount = 1;
708         udev_device->udev = udev;
709         udev_list_init(udev, &udev_device->devlinks_list, true);
710         udev_list_init(udev, &udev_device->properties_list, true);
711         udev_list_init(udev, &udev_device->sysattr_value_list, true);
712         udev_list_init(udev, &udev_device->sysattr_list, false);
713         udev_list_init(udev, &udev_device->tags_list, true);
714         udev_device->watch_handle = -1;
715
716         return udev_device;
717 }
718
719 /**
720  * udev_device_new_from_syspath:
721  * @udev: udev library context
722  * @syspath: sys device path including sys directory
723  *
724  * Create new udev device, and fill in information from the sys
725  * device and the udev database entry. The syspath is the absolute
726  * path to the device, including the sys mount point.
727  *
728  * The initial refcount is 1, and needs to be decremented to
729  * release the resources of the udev device.
730  *
731  * Returns: a new udev device, or #NULL, if it does not exist
732  **/
733 _public_ struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath)
734 {
735         const char *subdir;
736         char path[UTIL_PATH_SIZE];
737         char *pos;
738         struct stat statbuf;
739         struct udev_device *udev_device;
740
741         if (udev == NULL) {
742                 errno = EINVAL;
743                 return NULL;
744         }
745
746         if (syspath == NULL) {
747                 errno = EINVAL;
748                 return NULL;
749         }
750
751         /* path starts in sys */
752         if (!startswith(syspath, "/sys")) {
753                 log_debug("not in sys :%s", syspath);
754                 errno = EINVAL;
755                 return NULL;
756         }
757
758         /* path is not a root directory */
759         subdir = syspath + strlen("/sys");
760         pos = strrchr(subdir, '/');
761         if (pos == NULL || pos[1] == '\0' || pos < &subdir[2]) {
762                 errno = EINVAL;
763                 return NULL;
764         }
765
766         /* resolve possible symlink to real path */
767         strscpy(path, sizeof(path), syspath);
768         util_resolve_sys_link(udev, path, sizeof(path));
769
770         if (startswith(path + strlen("/sys"), "/devices/")) {
771                 char file[UTIL_PATH_SIZE];
772
773                 /* all "devices" require a "uevent" file */
774                 strscpyl(file, sizeof(file), path, "/uevent", NULL);
775                 if (stat(file, &statbuf) != 0)
776                         return NULL;
777         } else {
778                 /* everything else just needs to be a directory */
779                 if (stat(path, &statbuf) != 0)
780                         return NULL;
781
782                 if (!S_ISDIR(statbuf.st_mode)) {
783                         errno = EISDIR;
784                         return NULL;
785                 }
786         }
787
788         udev_device = udev_device_new(udev);
789         if (udev_device == NULL)
790                 return NULL;
791
792         udev_device_set_syspath(udev_device, path);
793         log_debug("device %p has devpath '%s'", udev_device, udev_device_get_devpath(udev_device));
794
795         return udev_device;
796 }
797
798 /**
799  * udev_device_new_from_devnum:
800  * @udev: udev library context
801  * @type: char or block device
802  * @devnum: device major/minor number
803  *
804  * Create new udev device, and fill in information from the sys
805  * device and the udev database entry. The device is looked-up
806  * by its major/minor number and type. Character and block device
807  * numbers are not unique across the two types.
808  *
809  * The initial refcount is 1, and needs to be decremented to
810  * release the resources of the udev device.
811  *
812  * Returns: a new udev device, or #NULL, if it does not exist
813  **/
814 _public_ struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum)
815 {
816         char path[UTIL_PATH_SIZE];
817         const char *type_str;
818
819         if (type == 'b')
820                 type_str = "block";
821         else if (type == 'c')
822                 type_str = "char";
823         else {
824                 errno = EINVAL;
825                 return NULL;
826         }
827
828         /* use /sys/dev/{block,char}/<maj>:<min> link */
829         snprintf(path, sizeof(path), "/sys/dev/%s/%u:%u",
830                  type_str, major(devnum), minor(devnum));
831         return udev_device_new_from_syspath(udev, path);
832 }
833
834 /**
835  * udev_device_new_from_device_id:
836  * @udev: udev library context
837  * @id: text string identifying a kernel device
838  *
839  * Create new udev device, and fill in information from the sys
840  * device and the udev database entry. The device is looked-up
841  * by a special string:
842  *   b8:2          - block device major:minor
843  *   c128:1        - char device major:minor
844  *   n3            - network device ifindex
845  *   +sound:card29 - kernel driver core subsystem:device name
846  *
847  * The initial refcount is 1, and needs to be decremented to
848  * release the resources of the udev device.
849  *
850  * Returns: a new udev device, or #NULL, if it does not exist
851  **/
852 _public_ struct udev_device *udev_device_new_from_device_id(struct udev *udev, const char *id)
853 {
854         char type;
855         int maj, min;
856         char subsys[UTIL_PATH_SIZE];
857         char *sysname;
858
859         switch(id[0]) {
860         case 'b':
861         case 'c':
862                 if (sscanf(id, "%c%i:%i", &type, &maj, &min) != 3)
863                         return NULL;
864                 return udev_device_new_from_devnum(udev, type, makedev(maj, min));
865         case 'n': {
866                 int sk;
867                 struct ifreq ifr;
868                 struct udev_device *dev;
869                 int ifindex;
870
871                 ifindex = strtoul(&id[1], NULL, 10);
872                 if (ifindex <= 0) {
873                         errno = EINVAL;
874                         return NULL;
875                 }
876
877                 sk = socket(PF_INET, SOCK_DGRAM, 0);
878                 if (sk < 0)
879                         return NULL;
880                 memzero(&ifr, sizeof(struct ifreq));
881                 ifr.ifr_ifindex = ifindex;
882                 if (ioctl(sk, SIOCGIFNAME, &ifr) != 0) {
883                         close(sk);
884                         return NULL;
885                 }
886                 close(sk);
887
888                 dev = udev_device_new_from_subsystem_sysname(udev, "net", ifr.ifr_name);
889                 if (dev == NULL)
890                         return NULL;
891                 if (udev_device_get_ifindex(dev) == ifindex)
892                         return dev;
893
894                 /* this is racy, so we may end up with the wrong device */
895                 udev_device_unref(dev);
896                 errno = ENODEV;
897                 return NULL;
898         }
899         case '+':
900                 strscpy(subsys, sizeof(subsys), &id[1]);
901                 sysname = strchr(subsys, ':');
902                 if (sysname == NULL) {
903                         errno = EINVAL;
904                         return NULL;
905                 }
906                 sysname[0] = '\0';
907                 sysname = &sysname[1];
908                 return udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
909         default:
910                 errno = EINVAL;
911                 return NULL;
912         }
913 }
914
915 /**
916  * udev_device_new_from_subsystem_sysname:
917  * @udev: udev library context
918  * @subsystem: the subsystem of the device
919  * @sysname: the name of the device
920  *
921  * Create new udev device, and fill in information from the sys device
922  * and the udev database entry. The device is looked up by the subsystem
923  * and name string of the device, like "mem" / "zero", or "block" / "sda".
924  *
925  * The initial refcount is 1, and needs to be decremented to
926  * release the resources of the udev device.
927  *
928  * Returns: a new udev device, or #NULL, if it does not exist
929  **/
930 _public_ struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname)
931 {
932         char path[UTIL_PATH_SIZE];
933         struct stat statbuf;
934
935         if (streq(subsystem, "subsystem")) {
936                 strscpyl(path, sizeof(path), "/sys/subsystem/", sysname, NULL);
937                 if (stat(path, &statbuf) == 0)
938                         goto found;
939
940                 strscpyl(path, sizeof(path), "/sys/bus/", sysname, NULL);
941                 if (stat(path, &statbuf) == 0)
942                         goto found;
943
944                 strscpyl(path, sizeof(path), "/sys/class/", sysname, NULL);
945                 if (stat(path, &statbuf) == 0)
946                         goto found;
947                 goto out;
948         }
949
950         if (streq(subsystem, "module")) {
951                 strscpyl(path, sizeof(path), "/sys/module/", sysname, NULL);
952                 if (stat(path, &statbuf) == 0)
953                         goto found;
954                 goto out;
955         }
956
957         if (streq(subsystem, "drivers")) {
958                 char subsys[UTIL_NAME_SIZE];
959                 char *driver;
960
961                 strscpy(subsys, sizeof(subsys), sysname);
962                 driver = strchr(subsys, ':');
963                 if (driver != NULL) {
964                         driver[0] = '\0';
965                         driver = &driver[1];
966
967                         strscpyl(path, sizeof(path), "/sys/subsystem/", subsys, "/drivers/", driver, NULL);
968                         if (stat(path, &statbuf) == 0)
969                                 goto found;
970
971                         strscpyl(path, sizeof(path), "/sys/bus/", subsys, "/drivers/", driver, NULL);
972                         if (stat(path, &statbuf) == 0)
973                                 goto found;
974                 } else
975                         errno = EINVAL;
976
977                 goto out;
978         }
979
980         strscpyl(path, sizeof(path), "/sys/subsystem/", subsystem, "/devices/", sysname, NULL);
981         if (stat(path, &statbuf) == 0)
982                 goto found;
983
984         strscpyl(path, sizeof(path), "/sys/bus/", subsystem, "/devices/", sysname, NULL);
985         if (stat(path, &statbuf) == 0)
986                 goto found;
987
988         strscpyl(path, sizeof(path), "/sys/class/", subsystem, "/", sysname, NULL);
989         if (stat(path, &statbuf) == 0)
990                 goto found;
991 out:
992         return NULL;
993 found:
994         return udev_device_new_from_syspath(udev, path);
995 }
996
997 /**
998  * udev_device_new_from_environment
999  * @udev: udev library context
1000  *
1001  * Create new udev device, and fill in information from the
1002  * current process environment. This only works reliable if
1003  * the process is called from a udev rule. It is usually used
1004  * for tools executed from IMPORT= rules.
1005  *
1006  * The initial refcount is 1, and needs to be decremented to
1007  * release the resources of the udev device.
1008  *
1009  * Returns: a new udev device, or #NULL, if it does not exist
1010  **/
1011 _public_ struct udev_device *udev_device_new_from_environment(struct udev *udev)
1012 {
1013         int i;
1014         struct udev_device *udev_device;
1015
1016         udev_device = udev_device_new(udev);
1017         if (udev_device == NULL)
1018                 return NULL;
1019         udev_device_set_info_loaded(udev_device);
1020
1021         for (i = 0; environ[i] != NULL; i++)
1022                 udev_device_add_property_from_string_parse(udev_device, environ[i]);
1023
1024         if (udev_device_add_property_from_string_parse_finish(udev_device) < 0) {
1025                 log_debug("missing values, invalid device");
1026                 udev_device_unref(udev_device);
1027                 udev_device = NULL;
1028         }
1029
1030         return udev_device;
1031 }
1032
1033 static struct udev_device *device_new_from_parent(struct udev_device *udev_device)
1034 {
1035         struct udev_device *udev_device_parent = NULL;
1036         char path[UTIL_PATH_SIZE];
1037         const char *subdir;
1038
1039         strscpy(path, sizeof(path), udev_device->syspath);
1040         subdir = path + strlen("/sys/");
1041         for (;;) {
1042                 char *pos;
1043
1044                 pos = strrchr(subdir, '/');
1045                 if (pos == NULL || pos < &subdir[2])
1046                         break;
1047                 pos[0] = '\0';
1048                 udev_device_parent = udev_device_new_from_syspath(udev_device->udev, path);
1049                 if (udev_device_parent != NULL)
1050                         return udev_device_parent;
1051         }
1052
1053         errno = ENOENT;
1054         return NULL;
1055 }
1056
1057 /**
1058  * udev_device_get_parent:
1059  * @udev_device: the device to start searching from
1060  *
1061  * Find the next parent device, and fill in information from the sys
1062  * device and the udev database entry.
1063  *
1064  * Returned device is not referenced. It is attached to the child
1065  * device, and will be cleaned up when the child device is cleaned up.
1066  *
1067  * It is not necessarily just the upper level directory, empty or not
1068  * recognized sys directories are ignored.
1069  *
1070  * It can be called as many times as needed, without caring about
1071  * references.
1072  *
1073  * Returns: a new udev device, or #NULL, if it no parent exist.
1074  **/
1075 _public_ struct udev_device *udev_device_get_parent(struct udev_device *udev_device)
1076 {
1077         if (udev_device == NULL) {
1078                 errno = EINVAL;
1079                 return NULL;
1080         }
1081         if (!udev_device->parent_set) {
1082                 udev_device->parent_set = true;
1083                 udev_device->parent_device = device_new_from_parent(udev_device);
1084         }
1085         return udev_device->parent_device;
1086 }
1087
1088 /**
1089  * udev_device_get_parent_with_subsystem_devtype:
1090  * @udev_device: udev device to start searching from
1091  * @subsystem: the subsystem of the device
1092  * @devtype: the type (DEVTYPE) of the device
1093  *
1094  * Find the next parent device, with a matching subsystem and devtype
1095  * value, and fill in information from the sys device and the udev
1096  * database entry.
1097  *
1098  * If devtype is #NULL, only subsystem is checked, and any devtype will
1099  * match.
1100  *
1101  * Returned device is not referenced. It is attached to the child
1102  * device, and will be cleaned up when the child device is cleaned up.
1103  *
1104  * It can be called as many times as needed, without caring about
1105  * references.
1106  *
1107  * Returns: a new udev device, or #NULL if no matching parent exists.
1108  **/
1109 _public_ struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device, const char *subsystem, const char *devtype)
1110 {
1111         struct udev_device *parent;
1112
1113         if (subsystem == NULL) {
1114                 errno = EINVAL;
1115                 return NULL;
1116         }
1117
1118         parent = udev_device_get_parent(udev_device);
1119         while (parent != NULL) {
1120                 const char *parent_subsystem;
1121                 const char *parent_devtype;
1122
1123                 parent_subsystem = udev_device_get_subsystem(parent);
1124                 if (parent_subsystem != NULL && streq(parent_subsystem, subsystem)) {
1125                         if (devtype == NULL)
1126                                 break;
1127                         parent_devtype = udev_device_get_devtype(parent);
1128                         if (parent_devtype != NULL && streq(parent_devtype, devtype))
1129                                 break;
1130                 }
1131                 parent = udev_device_get_parent(parent);
1132         }
1133
1134         if (!parent)
1135                 errno = ENOENT;
1136
1137         return parent;
1138 }
1139
1140 /**
1141  * udev_device_get_udev:
1142  * @udev_device: udev device
1143  *
1144  * Retrieve the udev library context the device was created with.
1145  *
1146  * Returns: the udev library context
1147  **/
1148 _public_ struct udev *udev_device_get_udev(struct udev_device *udev_device)
1149 {
1150         if (udev_device == NULL)
1151                 return NULL;
1152         return udev_device->udev;
1153 }
1154
1155 /**
1156  * udev_device_ref:
1157  * @udev_device: udev device
1158  *
1159  * Take a reference of a udev device.
1160  *
1161  * Returns: the passed udev device
1162  **/
1163 _public_ struct udev_device *udev_device_ref(struct udev_device *udev_device)
1164 {
1165         if (udev_device == NULL)
1166                 return NULL;
1167         udev_device->refcount++;
1168         return udev_device;
1169 }
1170
1171 /**
1172  * udev_device_unref:
1173  * @udev_device: udev device
1174  *
1175  * Drop a reference of a udev device. If the refcount reaches zero,
1176  * the resources of the device will be released.
1177  *
1178  * Returns: #NULL
1179  **/
1180 _public_ struct udev_device *udev_device_unref(struct udev_device *udev_device)
1181 {
1182         if (udev_device == NULL)
1183                 return NULL;
1184         udev_device->refcount--;
1185         if (udev_device->refcount > 0)
1186                 return NULL;
1187         if (udev_device->parent_device != NULL)
1188                 udev_device_unref(udev_device->parent_device);
1189         free(udev_device->syspath);
1190         free(udev_device->sysname);
1191         free(udev_device->devnode);
1192         free(udev_device->subsystem);
1193         free(udev_device->devtype);
1194         udev_list_cleanup(&udev_device->devlinks_list);
1195         udev_list_cleanup(&udev_device->properties_list);
1196         udev_list_cleanup(&udev_device->sysattr_value_list);
1197         udev_list_cleanup(&udev_device->sysattr_list);
1198         udev_list_cleanup(&udev_device->tags_list);
1199         free(udev_device->action);
1200         free(udev_device->driver);
1201         free(udev_device->devpath_old);
1202         free(udev_device->id_filename);
1203         free(udev_device->envp);
1204         free(udev_device->monitor_buf);
1205         free(udev_device);
1206         return NULL;
1207 }
1208
1209 /**
1210  * udev_device_get_devpath:
1211  * @udev_device: udev device
1212  *
1213  * Retrieve the kernel devpath value of the udev device. The path
1214  * does not contain the sys mount point, and starts with a '/'.
1215  *
1216  * Returns: the devpath of the udev device
1217  **/
1218 _public_ const char *udev_device_get_devpath(struct udev_device *udev_device)
1219 {
1220         if (udev_device == NULL)
1221                 return NULL;
1222         return udev_device->devpath;
1223 }
1224
1225 /**
1226  * udev_device_get_syspath:
1227  * @udev_device: udev device
1228  *
1229  * Retrieve the sys path of the udev device. The path is an
1230  * absolute path and starts with the sys mount point.
1231  *
1232  * Returns: the sys path of the udev device
1233  **/
1234 _public_ const char *udev_device_get_syspath(struct udev_device *udev_device)
1235 {
1236         if (udev_device == NULL)
1237                 return NULL;
1238         return udev_device->syspath;
1239 }
1240
1241 /**
1242  * udev_device_get_sysname:
1243  * @udev_device: udev device
1244  *
1245  * Get the kernel device name in /sys.
1246  *
1247  * Returns: the name string of the device device
1248  **/
1249 _public_ const char *udev_device_get_sysname(struct udev_device *udev_device)
1250 {
1251         if (udev_device == NULL)
1252                 return NULL;
1253         return udev_device->sysname;
1254 }
1255
1256 /**
1257  * udev_device_get_sysnum:
1258  * @udev_device: udev device
1259  *
1260  * Get the instance number of the device.
1261  *
1262  * Returns: the trailing number string of the device name
1263  **/
1264 _public_ const char *udev_device_get_sysnum(struct udev_device *udev_device)
1265 {
1266         if (udev_device == NULL)
1267                 return NULL;
1268         return udev_device->sysnum;
1269 }
1270
1271 /**
1272  * udev_device_get_devnode:
1273  * @udev_device: udev device
1274  *
1275  * Retrieve the device node file name belonging to the udev device.
1276  * The path is an absolute path, and starts with the device directory.
1277  *
1278  * Returns: the device node file name of the udev device, or #NULL if no device node exists
1279  **/
1280 _public_ const char *udev_device_get_devnode(struct udev_device *udev_device)
1281 {
1282         if (udev_device == NULL)
1283                 return NULL;
1284         if (udev_device->devnode != NULL)
1285                 return udev_device->devnode;
1286         if (!udev_device->info_loaded)
1287                 udev_device_read_uevent_file(udev_device);
1288         return udev_device->devnode;
1289 }
1290
1291 /**
1292  * udev_device_get_devlinks_list_entry:
1293  * @udev_device: udev device
1294  *
1295  * Retrieve the list of device links pointing to the device file of
1296  * the udev device. The next list entry can be retrieved with
1297  * udev_list_entry_get_next(), which returns #NULL if no more entries exist.
1298  * The devlink path can be retrieved from the list entry by
1299  * udev_list_entry_get_name(). The path is an absolute path, and starts with
1300  * the device directory.
1301  *
1302  * Returns: the first entry of the device node link list
1303  **/
1304 _public_ struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device)
1305 {
1306         if (udev_device == NULL)
1307                 return NULL;
1308         if (!udev_device->info_loaded)
1309                 udev_device_read_db(udev_device, NULL);
1310         return udev_list_get_entry(&udev_device->devlinks_list);
1311 }
1312
1313 void udev_device_cleanup_devlinks_list(struct udev_device *udev_device)
1314 {
1315         udev_device->devlinks_uptodate = false;
1316         udev_list_cleanup(&udev_device->devlinks_list);
1317 }
1318
1319 /**
1320  * udev_device_get_properties_list_entry:
1321  * @udev_device: udev device
1322  *
1323  * Retrieve the list of key/value device properties of the udev
1324  * device. The next list entry can be retrieved with udev_list_entry_get_next(),
1325  * which returns #NULL if no more entries exist. The property name
1326  * can be retrieved from the list entry by udev_list_entry_get_name(),
1327  * the property value by udev_list_entry_get_value().
1328  *
1329  * Returns: the first entry of the property list
1330  **/
1331 _public_ struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device)
1332 {
1333         if (udev_device == NULL)
1334                 return NULL;
1335         if (!udev_device->info_loaded) {
1336                 udev_device_read_uevent_file(udev_device);
1337                 udev_device_read_db(udev_device, NULL);
1338         }
1339         if (!udev_device->devlinks_uptodate) {
1340                 char symlinks[UTIL_PATH_SIZE];
1341                 struct udev_list_entry *list_entry;
1342
1343                 udev_device->devlinks_uptodate = true;
1344                 list_entry = udev_device_get_devlinks_list_entry(udev_device);
1345                 if (list_entry != NULL) {
1346                         char *s;
1347                         size_t l;
1348
1349                         s = symlinks;
1350                         l = strpcpyl(&s, sizeof(symlinks), udev_list_entry_get_name(list_entry), NULL);
1351                         udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
1352                                 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry), NULL);
1353                         udev_device_add_property_internal(udev_device, "DEVLINKS", symlinks);
1354                 }
1355         }
1356         if (!udev_device->tags_uptodate) {
1357                 udev_device->tags_uptodate = true;
1358                 if (udev_device_get_tags_list_entry(udev_device) != NULL) {
1359                         char tags[UTIL_PATH_SIZE];
1360                         struct udev_list_entry *list_entry;
1361                         char *s;
1362                         size_t l;
1363
1364                         s = tags;
1365                         l = strpcpyl(&s, sizeof(tags), ":", NULL);
1366                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
1367                                 l = strpcpyl(&s, l, udev_list_entry_get_name(list_entry), ":", NULL);
1368                         udev_device_add_property_internal(udev_device, "TAGS", tags);
1369                 }
1370         }
1371         return udev_list_get_entry(&udev_device->properties_list);
1372 }
1373
1374 /**
1375  * udev_device_get_action:
1376  * @udev_device: udev device
1377  *
1378  * This is only valid if the device was received through a monitor. Devices read from
1379  * sys do not have an action string. Usual actions are: add, remove, change, online,
1380  * offline.
1381  *
1382  * Returns: the kernel action value, or #NULL if there is no action value available.
1383  **/
1384 _public_ const char *udev_device_get_action(struct udev_device *udev_device)
1385 {
1386         if (udev_device == NULL)
1387                 return NULL;
1388         return udev_device->action;
1389 }
1390
1391 /**
1392  * udev_device_get_usec_since_initialized:
1393  * @udev_device: udev device
1394  *
1395  * Return the number of microseconds passed since udev set up the
1396  * device for the first time.
1397  *
1398  * This is only implemented for devices with need to store properties
1399  * in the udev database. All other devices return 0 here.
1400  *
1401  * Returns: the number of microseconds since the device was first seen.
1402  **/
1403 _public_ unsigned long long int udev_device_get_usec_since_initialized(struct udev_device *udev_device)
1404 {
1405         usec_t now_ts;
1406
1407         if (udev_device == NULL)
1408                 return 0;
1409         if (!udev_device->info_loaded)
1410                 udev_device_read_db(udev_device, NULL);
1411         if (udev_device->usec_initialized == 0)
1412                 return 0;
1413         now_ts = now(CLOCK_MONOTONIC);
1414         if (now_ts == 0)
1415                 return 0;
1416         return now_ts - udev_device->usec_initialized;
1417 }
1418
1419 usec_t udev_device_get_usec_initialized(struct udev_device *udev_device)
1420 {
1421         return udev_device->usec_initialized;
1422 }
1423
1424 void udev_device_set_usec_initialized(struct udev_device *udev_device, usec_t usec_initialized)
1425 {
1426         char num[32];
1427
1428         udev_device->usec_initialized = usec_initialized;
1429         snprintf(num, sizeof(num), USEC_FMT, usec_initialized);
1430         udev_device_add_property_internal(udev_device, "USEC_INITIALIZED", num);
1431 }
1432
1433 /**
1434  * udev_device_get_sysattr_value:
1435  * @udev_device: udev device
1436  * @sysattr: attribute name
1437  *
1438  * The retrieved value is cached in the device. Repeated calls will return the same
1439  * value and not open the attribute again.
1440  *
1441  * Returns: the content of a sys attribute file, or #NULL if there is no sys attribute value.
1442  **/
1443 _public_ const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr)
1444 {
1445         struct udev_list_entry *list_entry;
1446         char path[UTIL_PATH_SIZE];
1447         char value[4096];
1448         struct stat statbuf;
1449         int fd;
1450         ssize_t size;
1451         const char *val = NULL;
1452
1453         if (udev_device == NULL)
1454                 return NULL;
1455         if (sysattr == NULL)
1456                 return NULL;
1457
1458         /* look for possibly already cached result */
1459         list_entry = udev_list_get_entry(&udev_device->sysattr_value_list);
1460         list_entry = udev_list_entry_get_by_name(list_entry, sysattr);
1461         if (list_entry != NULL)
1462                 return udev_list_entry_get_value(list_entry);
1463
1464         strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", sysattr, NULL);
1465         if (lstat(path, &statbuf) != 0) {
1466                 udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, NULL);
1467                 goto out;
1468         }
1469
1470         if (S_ISLNK(statbuf.st_mode)) {
1471                 /*
1472                  * Some core links return only the last element of the target path,
1473                  * these are just values, the paths should not be exposed.
1474                  */
1475                 if (streq(sysattr, "driver") ||
1476                     streq(sysattr, "subsystem") ||
1477                     streq(sysattr, "module")) {
1478                         if (util_get_sys_core_link_value(udev_device->udev, sysattr,
1479                                                          udev_device->syspath, value, sizeof(value)) < 0)
1480                                 return NULL;
1481                         list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
1482                         val = udev_list_entry_get_value(list_entry);
1483                         goto out;
1484                 }
1485
1486                 goto out;
1487         }
1488
1489         /* skip directories */
1490         if (S_ISDIR(statbuf.st_mode))
1491                 goto out;
1492
1493         /* skip non-readable files */
1494         if ((statbuf.st_mode & S_IRUSR) == 0)
1495                 goto out;
1496
1497         /* read attribute value */
1498         fd = open(path, O_RDONLY|O_CLOEXEC);
1499         if (fd < 0)
1500                 goto out;
1501         size = read(fd, value, sizeof(value));
1502         close(fd);
1503         if (size < 0)
1504                 goto out;
1505         if (size == sizeof(value))
1506                 goto out;
1507
1508         /* got a valid value, store it in cache and return it */
1509         value[size] = '\0';
1510         util_remove_trailing_chars(value, '\n');
1511         list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
1512         val = udev_list_entry_get_value(list_entry);
1513 out:
1514         return val;
1515 }
1516
1517 /**
1518  * udev_device_set_sysattr_value:
1519  * @udev_device: udev device
1520  * @sysattr: attribute name
1521  * @value: new value to be set
1522  *
1523  * Update the contents of the sys attribute and the cached value of the device.
1524  *
1525  * Returns: Negative error code on failure or 0 on success.
1526  **/
1527 _public_ int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *sysattr, char *value)
1528 {
1529         struct udev_device *dev;
1530         char path[UTIL_PATH_SIZE];
1531         struct stat statbuf;
1532         int fd;
1533         ssize_t size, value_len;
1534         int ret = 0;
1535
1536         if (udev_device == NULL)
1537                 return -EINVAL;
1538         dev = udev_device;
1539         if (sysattr == NULL)
1540                 return -EINVAL;
1541         if (value == NULL)
1542                 value_len = 0;
1543         else
1544                 value_len = strlen(value);
1545
1546         strscpyl(path, sizeof(path), udev_device_get_syspath(dev), "/", sysattr, NULL);
1547         if (lstat(path, &statbuf) != 0) {
1548                 udev_list_entry_add(&dev->sysattr_value_list, sysattr, NULL);
1549                 ret = -ENXIO;
1550                 goto out;
1551         }
1552
1553         if (S_ISLNK(statbuf.st_mode)) {
1554                 ret = -EINVAL;
1555                 goto out;
1556         }
1557
1558         /* skip directories */
1559         if (S_ISDIR(statbuf.st_mode)) {
1560                 ret = -EISDIR;
1561                 goto out;
1562         }
1563
1564         /* skip non-readable files */
1565         if ((statbuf.st_mode & S_IRUSR) == 0) {
1566                 ret = -EACCES;
1567                 goto out;
1568         }
1569
1570         /* Value is limited to 4k */
1571         if (value_len > 4096) {
1572                 ret = -EINVAL;
1573                 goto out;
1574         }
1575         util_remove_trailing_chars(value, '\n');
1576
1577         /* write attribute value */
1578         fd = open(path, O_WRONLY|O_CLOEXEC);
1579         if (fd < 0) {
1580                 ret = -errno;
1581                 goto out;
1582         }
1583         size = write(fd, value, value_len);
1584         close(fd);
1585         if (size < 0) {
1586                 ret = -errno;
1587                 goto out;
1588         }
1589         if (size < value_len) {
1590                 ret = -EIO;
1591                 goto out;
1592         }
1593
1594         /* wrote a valid value, store it in cache and return it */
1595         udev_list_entry_add(&dev->sysattr_value_list, sysattr, value);
1596 out:
1597         if (dev != udev_device)
1598                 udev_device_unref(dev);
1599         return ret;
1600 }
1601
1602 static int udev_device_sysattr_list_read(struct udev_device *udev_device)
1603 {
1604         struct dirent *dent;
1605         DIR *dir;
1606         int num = 0;
1607
1608         if (udev_device == NULL)
1609                 return -EINVAL;
1610         if (udev_device->sysattr_list_read)
1611                 return 0;
1612
1613         dir = opendir(udev_device_get_syspath(udev_device));
1614         if (!dir)
1615                 return -errno;
1616
1617         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
1618                 char path[UTIL_PATH_SIZE];
1619                 struct stat statbuf;
1620
1621                 /* only handle symlinks and regular files */
1622                 if (dent->d_type != DT_LNK && dent->d_type != DT_REG)
1623                         continue;
1624
1625                 strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", dent->d_name, NULL);
1626                 if (lstat(path, &statbuf) != 0)
1627                         continue;
1628                 if ((statbuf.st_mode & S_IRUSR) == 0)
1629                         continue;
1630
1631                 udev_list_entry_add(&udev_device->sysattr_list, dent->d_name, NULL);
1632                 num++;
1633         }
1634
1635         closedir(dir);
1636         udev_device->sysattr_list_read = true;
1637
1638         return num;
1639 }
1640
1641 /**
1642  * udev_device_get_sysattr_list_entry:
1643  * @udev_device: udev device
1644  *
1645  * Retrieve the list of available sysattrs, with value being empty;
1646  * This just return all available sysfs attributes for a particular
1647  * device without reading their values.
1648  *
1649  * Returns: the first entry of the property list
1650  **/
1651 _public_ struct udev_list_entry *udev_device_get_sysattr_list_entry(struct udev_device *udev_device)
1652 {
1653         if (!udev_device->sysattr_list_read) {
1654                 int ret;
1655                 ret = udev_device_sysattr_list_read(udev_device);
1656                 if (0 > ret)
1657                         return NULL;
1658         }
1659
1660         return udev_list_get_entry(&udev_device->sysattr_list);
1661 }
1662
1663 static int udev_device_set_devnode(struct udev_device *udev_device, const char *devnode)
1664 {
1665         free(udev_device->devnode);
1666         if (devnode[0] != '/') {
1667                 if (asprintf(&udev_device->devnode, "/dev/%s", devnode) < 0)
1668                         udev_device->devnode = NULL;
1669         } else {
1670                 udev_device->devnode = strdup(devnode);
1671         }
1672         if (udev_device->devnode == NULL)
1673                 return -ENOMEM;
1674         udev_device_add_property_internal(udev_device, "DEVNAME", udev_device->devnode);
1675         return 0;
1676 }
1677
1678 int udev_device_add_devlink(struct udev_device *udev_device, const char *devlink)
1679 {
1680         struct udev_list_entry *list_entry;
1681
1682         udev_device->devlinks_uptodate = false;
1683         list_entry = udev_list_entry_add(&udev_device->devlinks_list, devlink, NULL);
1684         if (list_entry == NULL)
1685                 return -ENOMEM;
1686         return 0;
1687 }
1688
1689 const char *udev_device_get_id_filename(struct udev_device *udev_device)
1690 {
1691         if (udev_device->id_filename == NULL) {
1692                 if (udev_device_get_subsystem(udev_device) == NULL)
1693                         return NULL;
1694
1695                 if (major(udev_device_get_devnum(udev_device)) > 0) {
1696                         /* use dev_t -- b259:131072, c254:0 */
1697                         if (asprintf(&udev_device->id_filename, "%c%u:%u",
1698                                      streq(udev_device_get_subsystem(udev_device), "block") ? 'b' : 'c',
1699                                      major(udev_device_get_devnum(udev_device)),
1700                                      minor(udev_device_get_devnum(udev_device))) < 0)
1701                                 udev_device->id_filename = NULL;
1702                 } else if (udev_device_get_ifindex(udev_device) > 0) {
1703                         /* use netdev ifindex -- n3 */
1704                         if (asprintf(&udev_device->id_filename, "n%i", udev_device_get_ifindex(udev_device)) < 0)
1705                                 udev_device->id_filename = NULL;
1706                 } else {
1707                         /*
1708                          * use $subsys:$syname -- pci:0000:00:1f.2
1709                          * sysname() has '!' translated, get it from devpath
1710                          */
1711                         const char *sysname;
1712                         sysname = strrchr(udev_device->devpath, '/');
1713                         if (sysname == NULL)
1714                                 return NULL;
1715                         sysname = &sysname[1];
1716                         if (asprintf(&udev_device->id_filename, "+%s:%s", udev_device_get_subsystem(udev_device), sysname) < 0)
1717                                 udev_device->id_filename = NULL;
1718                 }
1719         }
1720         return udev_device->id_filename;
1721 }
1722
1723 /**
1724  * udev_device_get_is_initialized:
1725  * @udev_device: udev device
1726  *
1727  * Check if udev has already handled the device and has set up
1728  * device node permissions and context, or has renamed a network
1729  * device.
1730  *
1731  * This is only implemented for devices with a device node
1732  * or network interfaces. All other devices return 1 here.
1733  *
1734  * Returns: 1 if the device is set up. 0 otherwise.
1735  **/
1736 _public_ int udev_device_get_is_initialized(struct udev_device *udev_device)
1737 {
1738         if (!udev_device->info_loaded)
1739                 udev_device_read_db(udev_device, NULL);
1740         return udev_device->is_initialized;
1741 }
1742
1743 void udev_device_set_is_initialized(struct udev_device *udev_device)
1744 {
1745         udev_device->is_initialized = true;
1746 }
1747
1748 static bool is_valid_tag(const char *tag)
1749 {
1750         return !strchr(tag, ':') && !strchr(tag, ' ');
1751 }
1752
1753 int udev_device_add_tag(struct udev_device *udev_device, const char *tag)
1754 {
1755         if (!is_valid_tag(tag))
1756                 return -EINVAL;
1757         udev_device->tags_uptodate = false;
1758         if (udev_list_entry_add(&udev_device->tags_list, tag, NULL) != NULL)
1759                 return 0;
1760         return -ENOMEM;
1761 }
1762
1763 void udev_device_remove_tag(struct udev_device *udev_device, const char *tag)
1764 {
1765         struct udev_list_entry *e;
1766
1767         if (!is_valid_tag(tag))
1768                 return;
1769         e = udev_list_get_entry(&udev_device->tags_list);
1770         e = udev_list_entry_get_by_name(e, tag);
1771         if (e) {
1772                 udev_device->tags_uptodate = false;
1773                 udev_list_entry_delete(e);
1774         }
1775 }
1776
1777 void udev_device_cleanup_tags_list(struct udev_device *udev_device)
1778 {
1779         udev_device->tags_uptodate = false;
1780         udev_list_cleanup(&udev_device->tags_list);
1781 }
1782
1783 /**
1784  * udev_device_get_tags_list_entry:
1785  * @udev_device: udev device
1786  *
1787  * Retrieve the list of tags attached to the udev device. The next
1788  * list entry can be retrieved with udev_list_entry_get_next(),
1789  * which returns #NULL if no more entries exist. The tag string
1790  * can be retrieved from the list entry by udev_list_entry_get_name().
1791  *
1792  * Returns: the first entry of the tag list
1793  **/
1794 _public_ struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device)
1795 {
1796         if (udev_device == NULL)
1797                 return NULL;
1798         if (!udev_device->info_loaded)
1799                 udev_device_read_db(udev_device, NULL);
1800         return udev_list_get_entry(&udev_device->tags_list);
1801 }
1802
1803 /**
1804  * udev_device_has_tag:
1805  * @udev_device: udev device
1806  * @tag: tag name
1807  *
1808  * Check if a given device has a certain tag associated.
1809  *
1810  * Returns: 1 if the tag is found. 0 otherwise.
1811  **/
1812 _public_ int udev_device_has_tag(struct udev_device *udev_device, const char *tag)
1813 {
1814         struct udev_list_entry *list_entry;
1815
1816         if (udev_device == NULL)
1817                 return false;
1818         if (!udev_device->info_loaded)
1819                 udev_device_read_db(udev_device, NULL);
1820         list_entry = udev_device_get_tags_list_entry(udev_device);
1821         if (udev_list_entry_get_by_name(list_entry, tag) != NULL)
1822                 return true;
1823         return false;
1824 }
1825
1826 #define ENVP_SIZE                        128
1827 #define MONITOR_BUF_SIZE                4096
1828 static int update_envp_monitor_buf(struct udev_device *udev_device)
1829 {
1830         struct udev_list_entry *list_entry;
1831         char *s;
1832         size_t l;
1833         unsigned int i;
1834
1835         /* monitor buffer of property strings */
1836         free(udev_device->monitor_buf);
1837         udev_device->monitor_buf_len = 0;
1838         udev_device->monitor_buf = malloc(MONITOR_BUF_SIZE);
1839         if (udev_device->monitor_buf == NULL)
1840                 return -ENOMEM;
1841
1842         /* envp array, strings will point into monitor buffer */
1843         if (udev_device->envp == NULL)
1844                 udev_device->envp = malloc(sizeof(char *) * ENVP_SIZE);
1845         if (udev_device->envp == NULL)
1846                 return -ENOMEM;
1847
1848         i = 0;
1849         s = udev_device->monitor_buf;
1850         l = MONITOR_BUF_SIZE;
1851         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
1852                 const char *key;
1853
1854                 key = udev_list_entry_get_name(list_entry);
1855                 /* skip private variables */
1856                 if (key[0] == '.')
1857                         continue;
1858
1859                 /* add string to envp array */
1860                 udev_device->envp[i++] = s;
1861                 if (i+1 >= ENVP_SIZE)
1862                         return -EINVAL;
1863
1864                 /* add property string to monitor buffer */
1865                 l = strpcpyl(&s, l, key, "=", udev_list_entry_get_value(list_entry), NULL);
1866                 if (l == 0)
1867                         return -EINVAL;
1868                 /* advance past the trailing '\0' that strpcpyl() guarantees */
1869                 s++;
1870                 l--;
1871         }
1872         udev_device->envp[i] = NULL;
1873         udev_device->monitor_buf_len = s - udev_device->monitor_buf;
1874         udev_device->envp_uptodate = true;
1875         return 0;
1876 }
1877
1878 char **udev_device_get_properties_envp(struct udev_device *udev_device)
1879 {
1880         if (!udev_device->envp_uptodate)
1881                 if (update_envp_monitor_buf(udev_device) != 0)
1882                         return NULL;
1883         return udev_device->envp;
1884 }
1885
1886 ssize_t udev_device_get_properties_monitor_buf(struct udev_device *udev_device, const char **buf)
1887 {
1888         if (!udev_device->envp_uptodate)
1889                 if (update_envp_monitor_buf(udev_device) != 0)
1890                         return -EINVAL;
1891         *buf = udev_device->monitor_buf;
1892         return udev_device->monitor_buf_len;
1893 }
1894
1895 int udev_device_set_action(struct udev_device *udev_device, const char *action)
1896 {
1897         free(udev_device->action);
1898         udev_device->action = strdup(action);
1899         if (udev_device->action == NULL)
1900                 return -ENOMEM;
1901         udev_device_add_property_internal(udev_device, "ACTION", udev_device->action);
1902         return 0;
1903 }
1904
1905 int udev_device_get_devlink_priority(struct udev_device *udev_device)
1906 {
1907         if (!udev_device->info_loaded)
1908                 udev_device_read_db(udev_device, NULL);
1909         return udev_device->devlink_priority;
1910 }
1911
1912 int udev_device_set_devlink_priority(struct udev_device *udev_device, int prio)
1913 {
1914          udev_device->devlink_priority = prio;
1915         return 0;
1916 }
1917
1918 int udev_device_get_watch_handle(struct udev_device *udev_device)
1919 {
1920         if (!udev_device->info_loaded)
1921                 udev_device_read_db(udev_device, NULL);
1922         return udev_device->watch_handle;
1923 }
1924
1925 int udev_device_set_watch_handle(struct udev_device *udev_device, int handle)
1926 {
1927         udev_device->watch_handle = handle;
1928         return 0;
1929 }
1930
1931 bool udev_device_get_db_persist(struct udev_device *udev_device)
1932 {
1933         return udev_device->db_persist;
1934 }
1935
1936 void udev_device_set_db_persist(struct udev_device *udev_device)
1937 {
1938         udev_device->db_persist = true;
1939 }
1940
1941 int udev_device_rename(struct udev_device *udev_device, const char *name)
1942 {
1943         _cleanup_free_ char *dirname = NULL;
1944         const char *interface;
1945         char *new_syspath;
1946         int r;
1947
1948         if (udev_device == NULL || name == NULL)
1949                 return -EINVAL;
1950
1951         dirname = dirname_malloc(udev_device->syspath);
1952         if (!dirname)
1953                 return -ENOMEM;
1954
1955         new_syspath = strjoina(dirname, "/", name);
1956
1957         r = udev_device_set_syspath(udev_device, new_syspath);
1958         if (r < 0)
1959                 return r;
1960
1961         interface = udev_device_get_property_value(udev_device, "INTERFACE");
1962         if (interface) {
1963                 /* like DEVPATH_OLD, INTERFACE_OLD is not saved to the db, but only stays around for the current event */
1964                 udev_device_add_property_internal(udev_device, "INTERFACE_OLD", interface);
1965                 udev_device_add_property_internal(udev_device, "INTERFACE", name);
1966         }
1967
1968         return 0;
1969 }
1970
1971 struct udev_device *udev_device_shallow_clone(struct udev_device *old_device)
1972 {
1973         struct udev_device *device;
1974
1975         if (old_device == NULL)
1976                 return NULL;
1977
1978         device = udev_device_new(old_device->udev);
1979         if (!device) {
1980                 errno = ENOMEM;
1981
1982                 return NULL;
1983         }
1984
1985         udev_device_set_syspath(device, udev_device_get_syspath(old_device));
1986         udev_device_set_subsystem(device, udev_device_get_subsystem(old_device));
1987         udev_device_set_devnum(device, udev_device_get_devnum(old_device));
1988
1989         return device;
1990 }
1991
1992 struct udev_device *udev_device_new_from_nulstr(struct udev *udev, char *nulstr, ssize_t buflen) {
1993         struct udev_device *device;
1994         ssize_t bufpos = 0;
1995
1996         if (nulstr == NULL || buflen <= 0) {
1997                 errno = EINVAL;
1998
1999                 return NULL;
2000         }
2001
2002         device = udev_device_new(udev);
2003         if (!device) {
2004                 errno = ENOMEM;
2005
2006                 return NULL;
2007         }
2008
2009         udev_device_set_info_loaded(device);
2010
2011         while (bufpos < buflen) {
2012                 char *key;
2013                 size_t keylen;
2014
2015                 key = nulstr + bufpos;
2016                 keylen = strlen(key);
2017                 if (keylen == 0)
2018                         break;
2019
2020                 bufpos += keylen + 1;
2021                 udev_device_add_property_from_string_parse(device, key);
2022         }
2023
2024         if (udev_device_add_property_from_string_parse_finish(device) < 0) {
2025                 log_debug("missing values, invalid device");
2026
2027                 udev_device_unref(device);
2028
2029                 errno = EINVAL;
2030
2031                 return NULL;
2032         }
2033
2034         return device;
2035 }