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