chiark / gitweb /
udev: downgrade "has devpath" and "filled with db file" messages
[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 static void udev_device_set_usec_initialized(struct udev_device *udev_device, usec_t usec_initialized)
449 {
450         char num[DECIMAL_STR_MAX(usec_t)];
451
452         udev_device->usec_initialized = usec_initialized;
453         snprintf(num, sizeof(num), USEC_FMT, usec_initialized);
454         udev_device_add_property_internal(udev_device, "USEC_INITIALIZED", num);
455 }
456
457 void udev_device_ensure_usec_initialized(struct udev_device *udev_device, struct udev_device *old_device)
458 {
459         if (old_device && old_device->usec_initialized != 0)
460                 udev_device_set_usec_initialized(udev_device, old_device->usec_initialized);
461         else
462                 udev_device_set_usec_initialized(udev_device, now(CLOCK_MONOTONIC));
463 }
464
465 /*
466  * parse property string, and if needed, update internal values accordingly
467  *
468  * udev_device_add_property_from_string_parse_finish() needs to be
469  * called after adding properties, and its return value checked
470  *
471  * udev_device_set_info_loaded() needs to be set, to avoid trying
472  * to use a device without a DEVPATH set
473  */
474 static void udev_device_add_property_from_string_parse(struct udev_device *udev_device, const char *property)
475 {
476         if (startswith(property, "DEVPATH=")) {
477                 char path[UTIL_PATH_SIZE];
478
479                 strscpyl(path, sizeof(path), "/sys", &property[8], NULL);
480                 udev_device_set_syspath(udev_device, path);
481         } else if (startswith(property, "SUBSYSTEM=")) {
482                 udev_device_set_subsystem(udev_device, &property[10]);
483         } else if (startswith(property, "DEVTYPE=")) {
484                 udev_device_set_devtype(udev_device, &property[8]);
485         } else if (startswith(property, "DEVNAME=")) {
486                 udev_device_set_devnode(udev_device, &property[8]);
487         } else if (startswith(property, "DEVLINKS=")) {
488                 char devlinks[UTIL_PATH_SIZE];
489                 char *slink;
490                 char *next;
491
492                 strscpy(devlinks, sizeof(devlinks), &property[9]);
493                 slink = devlinks;
494                 next = strchr(slink, ' ');
495                 while (next != NULL) {
496                         next[0] = '\0';
497                         udev_device_add_devlink(udev_device, slink);
498                         slink = &next[1];
499                         next = strchr(slink, ' ');
500                 }
501                 if (slink[0] != '\0')
502                         udev_device_add_devlink(udev_device, slink);
503         } else if (startswith(property, "TAGS=")) {
504                 char tags[UTIL_PATH_SIZE];
505                 char *next;
506
507                 strscpy(tags, sizeof(tags), &property[5]);
508                 next = strchr(tags, ':');
509                 if (next != NULL) {
510                         next++;
511                         while (next[0] != '\0') {
512                                 char *tag;
513
514                                 tag = next;
515                                 next = strchr(tag, ':');
516                                 if (next == NULL)
517                                         break;
518                                 next[0] = '\0';
519                                 next++;
520                                 udev_device_add_tag(udev_device, tag);
521                         }
522                 }
523         } else if (startswith(property, "USEC_INITIALIZED=")) {
524                 udev_device_set_usec_initialized(udev_device, strtoull(&property[19], NULL, 10));
525         } else if (startswith(property, "DRIVER=")) {
526                 udev_device_set_driver(udev_device, &property[7]);
527         } else if (startswith(property, "ACTION=")) {
528                 udev_device_set_action(udev_device, &property[7]);
529         } else if (startswith(property, "MAJOR=")) {
530                 udev_device->maj = strtoull(&property[6], NULL, 10);
531         } else if (startswith(property, "MINOR=")) {
532                 udev_device->min = strtoull(&property[6], NULL, 10);
533         } else if (startswith(property, "DEVPATH_OLD=")) {
534                 udev_device_set_devpath_old(udev_device, &property[12]);
535         } else if (startswith(property, "SEQNUM=")) {
536                 udev_device_set_seqnum(udev_device, strtoull(&property[7], NULL, 10));
537         } else if (startswith(property, "IFINDEX=")) {
538                 udev_device_set_ifindex(udev_device, strtoull(&property[8], NULL, 10));
539         } else if (startswith(property, "DEVMODE=")) {
540                 udev_device_set_devnode_mode(udev_device, strtoul(&property[8], NULL, 8));
541         } else if (startswith(property, "DEVUID=")) {
542                 udev_device_set_devnode_uid(udev_device, strtoul(&property[7], NULL, 10));
543         } else if (startswith(property, "DEVGID=")) {
544                 udev_device_set_devnode_gid(udev_device, strtoul(&property[7], NULL, 10));
545         } else {
546                 udev_device_add_property_from_string(udev_device, property);
547         }
548 }
549
550 static int udev_device_add_property_from_string_parse_finish(struct udev_device *udev_device)
551 {
552         if (udev_device->maj > 0)
553                 udev_device_set_devnum(udev_device, makedev(udev_device->maj, udev_device->min));
554         udev_device->maj = 0;
555         udev_device->min = 0;
556
557         if (udev_device->devpath == NULL || udev_device->subsystem == NULL)
558                 return -EINVAL;
559         return 0;
560 }
561
562 /**
563  * udev_device_get_property_value:
564  * @udev_device: udev device
565  * @key: property name
566  *
567  * Get the value of a given property.
568  *
569  * Returns: the property string, or #NULL if there is no such property.
570  **/
571 _public_ const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key)
572 {
573         struct udev_list_entry *list_entry;
574
575         if (udev_device == NULL)
576                 return NULL;
577         if (key == NULL)
578                 return NULL;
579
580         list_entry = udev_device_get_properties_list_entry(udev_device);
581         list_entry = udev_list_entry_get_by_name(list_entry, key);
582         return udev_list_entry_get_value(list_entry);
583 }
584
585 int udev_device_read_db(struct udev_device *udev_device)
586 {
587         char filename[UTIL_PATH_SIZE];
588         char line[UTIL_LINE_SIZE];
589         const char *id;
590         FILE *f;
591
592         if (udev_device->db_loaded)
593                 return 0;
594
595         udev_device->db_loaded = true;
596
597         id = udev_device_get_id_filename(udev_device);
598         if (id == NULL)
599                 return -1;
600
601         strscpyl(filename, sizeof(filename), "/run/udev/data/", id, NULL);
602
603         f = fopen(filename, "re");
604         if (f == NULL)
605                 return log_debug_errno(errno, "no db file to read %s: %m", filename);
606
607         /* devices with a database entry are initialized */
608         udev_device->is_initialized = true;
609
610         while (fgets(line, sizeof(line), f)) {
611                 ssize_t len;
612                 const char *val;
613                 struct udev_list_entry *entry;
614
615                 len = strlen(line);
616                 if (len < 4)
617                         break;
618                 line[len-1] = '\0';
619                 val = &line[2];
620                 switch(line[0]) {
621                 case 'S':
622                         strscpyl(filename, sizeof(filename), "/dev/", val, NULL);
623                         udev_device_add_devlink(udev_device, filename);
624                         break;
625                 case 'L':
626                         udev_device_set_devlink_priority(udev_device, atoi(val));
627                         break;
628                 case 'E':
629                         entry = udev_device_add_property_from_string(udev_device, val);
630                         udev_list_entry_set_num(entry, true);
631                         break;
632                 case 'G':
633                         udev_device_add_tag(udev_device, val);
634                         break;
635                 case 'W':
636                         udev_device_set_watch_handle(udev_device, atoi(val));
637                         break;
638                 case 'I':
639                         udev_device_set_usec_initialized(udev_device, strtoull(val, NULL, 10));
640                         break;
641                 }
642         }
643         fclose(f);
644
645         log_trace("device %p filled with db file data", udev_device);
646         return 0;
647 }
648
649 int udev_device_read_uevent_file(struct udev_device *udev_device)
650 {
651         char filename[UTIL_PATH_SIZE];
652         FILE *f;
653         char line[UTIL_LINE_SIZE];
654         int maj = 0;
655         int min = 0;
656
657         if (udev_device->uevent_loaded)
658                 return 0;
659
660         strscpyl(filename, sizeof(filename), udev_device->syspath, "/uevent", NULL);
661         f = fopen(filename, "re");
662         if (f == NULL)
663                 return -errno;
664         udev_device->uevent_loaded = true;
665
666         while (fgets(line, sizeof(line), f)) {
667                 char *pos;
668
669                 pos = strchr(line, '\n');
670                 if (pos == NULL)
671                         continue;
672                 pos[0] = '\0';
673
674                 if (startswith(line, "DEVTYPE=")) {
675                         udev_device_set_devtype(udev_device, &line[8]);
676                         continue;
677                 }
678                 if (startswith(line, "IFINDEX=")) {
679                         udev_device_set_ifindex(udev_device, strtoull(&line[8], NULL, 10));
680                         continue;
681                 }
682                 if (startswith(line, "DEVNAME=")) {
683                         udev_device_set_devnode(udev_device, &line[8]);
684                         continue;
685                 }
686
687                 if (startswith(line, "MAJOR="))
688                         maj = strtoull(&line[6], NULL, 10);
689                 else if (startswith(line, "MINOR="))
690                         min = strtoull(&line[6], NULL, 10);
691                 else if (startswith(line, "DEVMODE="))
692                         udev_device->devnode_mode = strtoul(&line[8], NULL, 8);
693
694                 udev_device_add_property_from_string(udev_device, line);
695         }
696
697         udev_device->devnum = makedev(maj, min);
698         fclose(f);
699         return 0;
700 }
701
702 void udev_device_set_info_loaded(struct udev_device *device)
703 {
704         device->info_loaded = true;
705 }
706
707 static struct udev_device *udev_device_new(struct udev *udev)
708 {
709         struct udev_device *udev_device;
710
711         if (udev == NULL) {
712                 errno = EINVAL;
713                 return NULL;
714         }
715
716         udev_device = new0(struct udev_device, 1);
717         if (udev_device == NULL) {
718                 errno = ENOMEM;
719                 return NULL;
720         }
721         udev_device->refcount = 1;
722         udev_device->udev = udev;
723         udev_list_init(udev, &udev_device->devlinks_list, true);
724         udev_list_init(udev, &udev_device->properties_list, true);
725         udev_list_init(udev, &udev_device->sysattr_value_list, true);
726         udev_list_init(udev, &udev_device->sysattr_list, false);
727         udev_list_init(udev, &udev_device->tags_list, true);
728         udev_device->watch_handle = -1;
729
730         return udev_device;
731 }
732
733 /**
734  * udev_device_new_from_syspath:
735  * @udev: udev library context
736  * @syspath: sys device path including sys directory
737  *
738  * Create new udev device, and fill in information from the sys
739  * device and the udev database entry. The syspath is the absolute
740  * path to the device, including the sys mount point.
741  *
742  * The initial refcount is 1, and needs to be decremented to
743  * release the resources of the udev device.
744  *
745  * Returns: a new udev device, or #NULL, if it does not exist
746  **/
747 _public_ struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath)
748 {
749         const char *subdir;
750         char path[UTIL_PATH_SIZE];
751         char *pos;
752         struct stat statbuf;
753         struct udev_device *udev_device;
754
755         if (udev == NULL) {
756                 errno = EINVAL;
757                 return NULL;
758         }
759
760         if (syspath == NULL) {
761                 errno = EINVAL;
762                 return NULL;
763         }
764
765         /* path starts in sys */
766         if (!startswith(syspath, "/sys")) {
767                 log_debug("not in sys :%s", syspath);
768                 errno = EINVAL;
769                 return NULL;
770         }
771
772         /* path is not a root directory */
773         subdir = syspath + strlen("/sys");
774         pos = strrchr(subdir, '/');
775         if (pos == NULL || pos[1] == '\0' || pos < &subdir[2]) {
776                 errno = EINVAL;
777                 return NULL;
778         }
779
780         /* resolve possible symlink to real path */
781         strscpy(path, sizeof(path), syspath);
782         util_resolve_sys_link(udev, path, sizeof(path));
783
784         if (startswith(path + strlen("/sys"), "/devices/")) {
785                 char file[UTIL_PATH_SIZE];
786
787                 /* all "devices" require a "uevent" file */
788                 strscpyl(file, sizeof(file), path, "/uevent", NULL);
789                 if (stat(file, &statbuf) != 0)
790                         return NULL;
791         } else {
792                 /* everything else just needs to be a directory */
793                 if (stat(path, &statbuf) != 0)
794                         return NULL;
795
796                 if (!S_ISDIR(statbuf.st_mode)) {
797                         errno = EISDIR;
798                         return NULL;
799                 }
800         }
801
802         udev_device = udev_device_new(udev);
803         if (udev_device == NULL)
804                 return NULL;
805
806         udev_device_set_syspath(udev_device, path);
807         log_trace("device %p has devpath '%s'", udev_device, udev_device_get_devpath(udev_device));
808
809         return udev_device;
810 }
811
812 /**
813  * udev_device_new_from_devnum:
814  * @udev: udev library context
815  * @type: char or block device
816  * @devnum: device major/minor number
817  *
818  * Create new udev device, and fill in information from the sys
819  * device and the udev database entry. The device is looked-up
820  * by its major/minor number and type. Character and block device
821  * numbers are not unique across the two types.
822  *
823  * The initial refcount is 1, and needs to be decremented to
824  * release the resources of the udev device.
825  *
826  * Returns: a new udev device, or #NULL, if it does not exist
827  **/
828 _public_ struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum)
829 {
830         char path[UTIL_PATH_SIZE];
831         const char *type_str;
832
833         if (type == 'b')
834                 type_str = "block";
835         else if (type == 'c')
836                 type_str = "char";
837         else {
838                 errno = EINVAL;
839                 return NULL;
840         }
841
842         /* use /sys/dev/{block,char}/<maj>:<min> link */
843         snprintf(path, sizeof(path), "/sys/dev/%s/%u:%u",
844                  type_str, major(devnum), minor(devnum));
845         return udev_device_new_from_syspath(udev, path);
846 }
847
848 /**
849  * udev_device_new_from_device_id:
850  * @udev: udev library context
851  * @id: text string identifying a kernel device
852  *
853  * Create new udev device, and fill in information from the sys
854  * device and the udev database entry. The device is looked-up
855  * by a special string:
856  *   b8:2          - block device major:minor
857  *   c128:1        - char device major:minor
858  *   n3            - network device ifindex
859  *   +sound:card29 - kernel driver core subsystem:device name
860  *
861  * The initial refcount is 1, and needs to be decremented to
862  * release the resources of the udev device.
863  *
864  * Returns: a new udev device, or #NULL, if it does not exist
865  **/
866 _public_ struct udev_device *udev_device_new_from_device_id(struct udev *udev, const char *id)
867 {
868         char type;
869         int maj, min;
870         char subsys[UTIL_PATH_SIZE];
871         char *sysname;
872
873         switch(id[0]) {
874         case 'b':
875         case 'c':
876                 if (sscanf(id, "%c%i:%i", &type, &maj, &min) != 3)
877                         return NULL;
878                 return udev_device_new_from_devnum(udev, type, makedev(maj, min));
879         case 'n': {
880                 int sk;
881                 struct ifreq ifr;
882                 struct udev_device *dev;
883                 int ifindex;
884
885                 ifindex = strtoul(&id[1], NULL, 10);
886                 if (ifindex <= 0) {
887                         errno = EINVAL;
888                         return NULL;
889                 }
890
891                 sk = socket(PF_INET, SOCK_DGRAM, 0);
892                 if (sk < 0)
893                         return NULL;
894                 memzero(&ifr, sizeof(struct ifreq));
895                 ifr.ifr_ifindex = ifindex;
896                 if (ioctl(sk, SIOCGIFNAME, &ifr) != 0) {
897                         close(sk);
898                         return NULL;
899                 }
900                 close(sk);
901
902                 dev = udev_device_new_from_subsystem_sysname(udev, "net", ifr.ifr_name);
903                 if (dev == NULL)
904                         return NULL;
905                 if (udev_device_get_ifindex(dev) == ifindex)
906                         return dev;
907
908                 /* this is racy, so we may end up with the wrong device */
909                 udev_device_unref(dev);
910                 errno = ENODEV;
911                 return NULL;
912         }
913         case '+':
914                 strscpy(subsys, sizeof(subsys), &id[1]);
915                 sysname = strchr(subsys, ':');
916                 if (sysname == NULL) {
917                         errno = EINVAL;
918                         return NULL;
919                 }
920                 sysname[0] = '\0';
921                 sysname = &sysname[1];
922                 return udev_device_new_from_subsystem_sysname(udev, subsys, sysname);
923         default:
924                 errno = EINVAL;
925                 return NULL;
926         }
927 }
928
929 /**
930  * udev_device_new_from_subsystem_sysname:
931  * @udev: udev library context
932  * @subsystem: the subsystem of the device
933  * @sysname: the name of the device
934  *
935  * Create new udev device, and fill in information from the sys device
936  * and the udev database entry. The device is looked up by the subsystem
937  * and name string of the device, like "mem" / "zero", or "block" / "sda".
938  *
939  * The initial refcount is 1, and needs to be decremented to
940  * release the resources of the udev device.
941  *
942  * Returns: a new udev device, or #NULL, if it does not exist
943  **/
944 _public_ struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname)
945 {
946         char path[UTIL_PATH_SIZE];
947         struct stat statbuf;
948
949         if (streq(subsystem, "subsystem")) {
950                 strscpyl(path, sizeof(path), "/sys/subsystem/", sysname, NULL);
951                 if (stat(path, &statbuf) == 0)
952                         goto found;
953
954                 strscpyl(path, sizeof(path), "/sys/bus/", sysname, NULL);
955                 if (stat(path, &statbuf) == 0)
956                         goto found;
957
958                 strscpyl(path, sizeof(path), "/sys/class/", sysname, NULL);
959                 if (stat(path, &statbuf) == 0)
960                         goto found;
961                 goto out;
962         }
963
964         if (streq(subsystem, "module")) {
965                 strscpyl(path, sizeof(path), "/sys/module/", sysname, NULL);
966                 if (stat(path, &statbuf) == 0)
967                         goto found;
968                 goto out;
969         }
970
971         if (streq(subsystem, "drivers")) {
972                 char subsys[UTIL_NAME_SIZE];
973                 char *driver;
974
975                 strscpy(subsys, sizeof(subsys), sysname);
976                 driver = strchr(subsys, ':');
977                 if (driver != NULL) {
978                         driver[0] = '\0';
979                         driver = &driver[1];
980
981                         strscpyl(path, sizeof(path), "/sys/subsystem/", subsys, "/drivers/", driver, NULL);
982                         if (stat(path, &statbuf) == 0)
983                                 goto found;
984
985                         strscpyl(path, sizeof(path), "/sys/bus/", subsys, "/drivers/", driver, NULL);
986                         if (stat(path, &statbuf) == 0)
987                                 goto found;
988                 } else
989                         errno = EINVAL;
990
991                 goto out;
992         }
993
994         strscpyl(path, sizeof(path), "/sys/subsystem/", subsystem, "/devices/", sysname, NULL);
995         if (stat(path, &statbuf) == 0)
996                 goto found;
997
998         strscpyl(path, sizeof(path), "/sys/bus/", subsystem, "/devices/", sysname, NULL);
999         if (stat(path, &statbuf) == 0)
1000                 goto found;
1001
1002         strscpyl(path, sizeof(path), "/sys/class/", subsystem, "/", sysname, NULL);
1003         if (stat(path, &statbuf) == 0)
1004                 goto found;
1005 out:
1006         return NULL;
1007 found:
1008         return udev_device_new_from_syspath(udev, path);
1009 }
1010
1011 /**
1012  * udev_device_new_from_environment
1013  * @udev: udev library context
1014  *
1015  * Create new udev device, and fill in information from the
1016  * current process environment. This only works reliable if
1017  * the process is called from a udev rule. It is usually used
1018  * for tools executed from IMPORT= rules.
1019  *
1020  * The initial refcount is 1, and needs to be decremented to
1021  * release the resources of the udev device.
1022  *
1023  * Returns: a new udev device, or #NULL, if it does not exist
1024  **/
1025 _public_ struct udev_device *udev_device_new_from_environment(struct udev *udev)
1026 {
1027         int i;
1028         struct udev_device *udev_device;
1029
1030         udev_device = udev_device_new(udev);
1031         if (udev_device == NULL)
1032                 return NULL;
1033         udev_device_set_info_loaded(udev_device);
1034
1035         for (i = 0; environ[i] != NULL; i++)
1036                 udev_device_add_property_from_string_parse(udev_device, environ[i]);
1037
1038         if (udev_device_add_property_from_string_parse_finish(udev_device) < 0) {
1039                 log_debug("missing values, invalid device");
1040                 udev_device_unref(udev_device);
1041                 udev_device = NULL;
1042         }
1043
1044         return udev_device;
1045 }
1046
1047 static struct udev_device *device_new_from_parent(struct udev_device *udev_device)
1048 {
1049         struct udev_device *udev_device_parent = NULL;
1050         char path[UTIL_PATH_SIZE];
1051         const char *subdir;
1052
1053         strscpy(path, sizeof(path), udev_device->syspath);
1054         subdir = path + strlen("/sys/");
1055         for (;;) {
1056                 char *pos;
1057
1058                 pos = strrchr(subdir, '/');
1059                 if (pos == NULL || pos < &subdir[2])
1060                         break;
1061                 pos[0] = '\0';
1062                 udev_device_parent = udev_device_new_from_syspath(udev_device->udev, path);
1063                 if (udev_device_parent != NULL)
1064                         return udev_device_parent;
1065         }
1066
1067         errno = ENOENT;
1068         return NULL;
1069 }
1070
1071 /**
1072  * udev_device_get_parent:
1073  * @udev_device: the device to start searching from
1074  *
1075  * Find the next parent device, and fill in information from the sys
1076  * device and the udev database entry.
1077  *
1078  * Returned device is not referenced. It is attached to the child
1079  * device, and will be cleaned up when the child device is cleaned up.
1080  *
1081  * It is not necessarily just the upper level directory, empty or not
1082  * recognized sys directories are ignored.
1083  *
1084  * It can be called as many times as needed, without caring about
1085  * references.
1086  *
1087  * Returns: a new udev device, or #NULL, if it no parent exist.
1088  **/
1089 _public_ struct udev_device *udev_device_get_parent(struct udev_device *udev_device)
1090 {
1091         if (udev_device == NULL) {
1092                 errno = EINVAL;
1093                 return NULL;
1094         }
1095         if (!udev_device->parent_set) {
1096                 udev_device->parent_set = true;
1097                 udev_device->parent_device = device_new_from_parent(udev_device);
1098         }
1099         return udev_device->parent_device;
1100 }
1101
1102 /**
1103  * udev_device_get_parent_with_subsystem_devtype:
1104  * @udev_device: udev device to start searching from
1105  * @subsystem: the subsystem of the device
1106  * @devtype: the type (DEVTYPE) of the device
1107  *
1108  * Find the next parent device, with a matching subsystem and devtype
1109  * value, and fill in information from the sys device and the udev
1110  * database entry.
1111  *
1112  * If devtype is #NULL, only subsystem is checked, and any devtype will
1113  * match.
1114  *
1115  * Returned device is not referenced. It is attached to the child
1116  * device, and will be cleaned up when the child device is cleaned up.
1117  *
1118  * It can be called as many times as needed, without caring about
1119  * references.
1120  *
1121  * Returns: a new udev device, or #NULL if no matching parent exists.
1122  **/
1123 _public_ struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device, const char *subsystem, const char *devtype)
1124 {
1125         struct udev_device *parent;
1126
1127         if (subsystem == NULL) {
1128                 errno = EINVAL;
1129                 return NULL;
1130         }
1131
1132         parent = udev_device_get_parent(udev_device);
1133         while (parent != NULL) {
1134                 const char *parent_subsystem;
1135                 const char *parent_devtype;
1136
1137                 parent_subsystem = udev_device_get_subsystem(parent);
1138                 if (parent_subsystem != NULL && streq(parent_subsystem, subsystem)) {
1139                         if (devtype == NULL)
1140                                 break;
1141                         parent_devtype = udev_device_get_devtype(parent);
1142                         if (parent_devtype != NULL && streq(parent_devtype, devtype))
1143                                 break;
1144                 }
1145                 parent = udev_device_get_parent(parent);
1146         }
1147
1148         if (!parent)
1149                 errno = ENOENT;
1150
1151         return parent;
1152 }
1153
1154 /**
1155  * udev_device_get_udev:
1156  * @udev_device: udev device
1157  *
1158  * Retrieve the udev library context the device was created with.
1159  *
1160  * Returns: the udev library context
1161  **/
1162 _public_ struct udev *udev_device_get_udev(struct udev_device *udev_device)
1163 {
1164         if (udev_device == NULL)
1165                 return NULL;
1166         return udev_device->udev;
1167 }
1168
1169 /**
1170  * udev_device_ref:
1171  * @udev_device: udev device
1172  *
1173  * Take a reference of a udev device.
1174  *
1175  * Returns: the passed udev device
1176  **/
1177 _public_ struct udev_device *udev_device_ref(struct udev_device *udev_device)
1178 {
1179         if (udev_device == NULL)
1180                 return NULL;
1181         udev_device->refcount++;
1182         return udev_device;
1183 }
1184
1185 /**
1186  * udev_device_unref:
1187  * @udev_device: udev device
1188  *
1189  * Drop a reference of a udev device. If the refcount reaches zero,
1190  * the resources of the device will be released.
1191  *
1192  * Returns: #NULL
1193  **/
1194 _public_ struct udev_device *udev_device_unref(struct udev_device *udev_device)
1195 {
1196         if (udev_device == NULL)
1197                 return NULL;
1198         udev_device->refcount--;
1199         if (udev_device->refcount > 0)
1200                 return NULL;
1201         if (udev_device->parent_device != NULL)
1202                 udev_device_unref(udev_device->parent_device);
1203         free(udev_device->syspath);
1204         free(udev_device->sysname);
1205         free(udev_device->devnode);
1206         free(udev_device->subsystem);
1207         free(udev_device->devtype);
1208         udev_list_cleanup(&udev_device->devlinks_list);
1209         udev_list_cleanup(&udev_device->properties_list);
1210         udev_list_cleanup(&udev_device->sysattr_value_list);
1211         udev_list_cleanup(&udev_device->sysattr_list);
1212         udev_list_cleanup(&udev_device->tags_list);
1213         free(udev_device->action);
1214         free(udev_device->driver);
1215         free(udev_device->devpath_old);
1216         free(udev_device->id_filename);
1217         free(udev_device->envp);
1218         free(udev_device->monitor_buf);
1219         free(udev_device);
1220         return NULL;
1221 }
1222
1223 /**
1224  * udev_device_get_devpath:
1225  * @udev_device: udev device
1226  *
1227  * Retrieve the kernel devpath value of the udev device. The path
1228  * does not contain the sys mount point, and starts with a '/'.
1229  *
1230  * Returns: the devpath of the udev device
1231  **/
1232 _public_ const char *udev_device_get_devpath(struct udev_device *udev_device)
1233 {
1234         if (udev_device == NULL)
1235                 return NULL;
1236         return udev_device->devpath;
1237 }
1238
1239 /**
1240  * udev_device_get_syspath:
1241  * @udev_device: udev device
1242  *
1243  * Retrieve the sys path of the udev device. The path is an
1244  * absolute path and starts with the sys mount point.
1245  *
1246  * Returns: the sys path of the udev device
1247  **/
1248 _public_ const char *udev_device_get_syspath(struct udev_device *udev_device)
1249 {
1250         if (udev_device == NULL)
1251                 return NULL;
1252         return udev_device->syspath;
1253 }
1254
1255 /**
1256  * udev_device_get_sysname:
1257  * @udev_device: udev device
1258  *
1259  * Get the kernel device name in /sys.
1260  *
1261  * Returns: the name string of the device device
1262  **/
1263 _public_ const char *udev_device_get_sysname(struct udev_device *udev_device)
1264 {
1265         if (udev_device == NULL)
1266                 return NULL;
1267         return udev_device->sysname;
1268 }
1269
1270 /**
1271  * udev_device_get_sysnum:
1272  * @udev_device: udev device
1273  *
1274  * Get the instance number of the device.
1275  *
1276  * Returns: the trailing number string of the device name
1277  **/
1278 _public_ const char *udev_device_get_sysnum(struct udev_device *udev_device)
1279 {
1280         if (udev_device == NULL)
1281                 return NULL;
1282         return udev_device->sysnum;
1283 }
1284
1285 /**
1286  * udev_device_get_devnode:
1287  * @udev_device: udev device
1288  *
1289  * Retrieve the device node file name belonging to the udev device.
1290  * The path is an absolute path, and starts with the device directory.
1291  *
1292  * Returns: the device node file name of the udev device, or #NULL if no device node exists
1293  **/
1294 _public_ const char *udev_device_get_devnode(struct udev_device *udev_device)
1295 {
1296         if (udev_device == NULL)
1297                 return NULL;
1298         if (udev_device->devnode != NULL)
1299                 return udev_device->devnode;
1300         if (!udev_device->info_loaded)
1301                 udev_device_read_uevent_file(udev_device);
1302         return udev_device->devnode;
1303 }
1304
1305 /**
1306  * udev_device_get_devlinks_list_entry:
1307  * @udev_device: udev device
1308  *
1309  * Retrieve the list of device links pointing to the device file of
1310  * the udev device. The next list entry can be retrieved with
1311  * udev_list_entry_get_next(), which returns #NULL if no more entries exist.
1312  * The devlink path can be retrieved from the list entry by
1313  * udev_list_entry_get_name(). The path is an absolute path, and starts with
1314  * the device directory.
1315  *
1316  * Returns: the first entry of the device node link list
1317  **/
1318 _public_ struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device)
1319 {
1320         if (udev_device == NULL)
1321                 return NULL;
1322         if (!udev_device->info_loaded)
1323                 udev_device_read_db(udev_device);
1324         return udev_list_get_entry(&udev_device->devlinks_list);
1325 }
1326
1327 void udev_device_cleanup_devlinks_list(struct udev_device *udev_device)
1328 {
1329         udev_device->devlinks_uptodate = false;
1330         udev_list_cleanup(&udev_device->devlinks_list);
1331 }
1332
1333 /**
1334  * udev_device_get_properties_list_entry:
1335  * @udev_device: udev device
1336  *
1337  * Retrieve the list of key/value device properties of the udev
1338  * device. The next list entry can be retrieved with udev_list_entry_get_next(),
1339  * which returns #NULL if no more entries exist. The property name
1340  * can be retrieved from the list entry by udev_list_entry_get_name(),
1341  * the property value by udev_list_entry_get_value().
1342  *
1343  * Returns: the first entry of the property list
1344  **/
1345 _public_ struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device)
1346 {
1347         if (udev_device == NULL)
1348                 return NULL;
1349         if (!udev_device->info_loaded) {
1350                 udev_device_read_uevent_file(udev_device);
1351                 udev_device_read_db(udev_device);
1352         }
1353         if (!udev_device->devlinks_uptodate) {
1354                 char symlinks[UTIL_PATH_SIZE];
1355                 struct udev_list_entry *list_entry;
1356
1357                 udev_device->devlinks_uptodate = true;
1358                 list_entry = udev_device_get_devlinks_list_entry(udev_device);
1359                 if (list_entry != NULL) {
1360                         char *s;
1361                         size_t l;
1362
1363                         s = symlinks;
1364                         l = strpcpyl(&s, sizeof(symlinks), udev_list_entry_get_name(list_entry), NULL);
1365                         udev_list_entry_foreach(list_entry, udev_list_entry_get_next(list_entry))
1366                                 l = strpcpyl(&s, l, " ", udev_list_entry_get_name(list_entry), NULL);
1367                         udev_device_add_property_internal(udev_device, "DEVLINKS", symlinks);
1368                 }
1369         }
1370         if (!udev_device->tags_uptodate) {
1371                 udev_device->tags_uptodate = true;
1372                 if (udev_device_get_tags_list_entry(udev_device) != NULL) {
1373                         char tags[UTIL_PATH_SIZE];
1374                         struct udev_list_entry *list_entry;
1375                         char *s;
1376                         size_t l;
1377
1378                         s = tags;
1379                         l = strpcpyl(&s, sizeof(tags), ":", NULL);
1380                         udev_list_entry_foreach(list_entry, udev_device_get_tags_list_entry(udev_device))
1381                                 l = strpcpyl(&s, l, udev_list_entry_get_name(list_entry), ":", NULL);
1382                         udev_device_add_property_internal(udev_device, "TAGS", tags);
1383                 }
1384         }
1385         return udev_list_get_entry(&udev_device->properties_list);
1386 }
1387
1388 /**
1389  * udev_device_get_action:
1390  * @udev_device: udev device
1391  *
1392  * This is only valid if the device was received through a monitor. Devices read from
1393  * sys do not have an action string. Usual actions are: add, remove, change, online,
1394  * offline.
1395  *
1396  * Returns: the kernel action value, or #NULL if there is no action value available.
1397  **/
1398 _public_ const char *udev_device_get_action(struct udev_device *udev_device)
1399 {
1400         if (udev_device == NULL)
1401                 return NULL;
1402         return udev_device->action;
1403 }
1404
1405 /**
1406  * udev_device_get_usec_since_initialized:
1407  * @udev_device: udev device
1408  *
1409  * Return the number of microseconds passed since udev set up the
1410  * device for the first time.
1411  *
1412  * This is only implemented for devices with need to store properties
1413  * in the udev database. All other devices return 0 here.
1414  *
1415  * Returns: the number of microseconds since the device was first seen.
1416  **/
1417 _public_ unsigned long long int udev_device_get_usec_since_initialized(struct udev_device *udev_device)
1418 {
1419         usec_t now_ts;
1420
1421         if (udev_device == NULL)
1422                 return 0;
1423         if (!udev_device->info_loaded)
1424                 udev_device_read_db(udev_device);
1425         if (udev_device->usec_initialized == 0)
1426                 return 0;
1427         now_ts = now(CLOCK_MONOTONIC);
1428         if (now_ts == 0)
1429                 return 0;
1430         return now_ts - udev_device->usec_initialized;
1431 }
1432
1433 usec_t udev_device_get_usec_initialized(struct udev_device *udev_device)
1434 {
1435         return udev_device->usec_initialized;
1436 }
1437
1438 /**
1439  * udev_device_get_sysattr_value:
1440  * @udev_device: udev device
1441  * @sysattr: attribute name
1442  *
1443  * The retrieved value is cached in the device. Repeated calls will return the same
1444  * value and not open the attribute again.
1445  *
1446  * Returns: the content of a sys attribute file, or #NULL if there is no sys attribute value.
1447  **/
1448 _public_ const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr)
1449 {
1450         struct udev_list_entry *list_entry;
1451         char path[UTIL_PATH_SIZE];
1452         char value[4096];
1453         struct stat statbuf;
1454         int fd;
1455         ssize_t size;
1456         const char *val = NULL;
1457
1458         if (udev_device == NULL)
1459                 return NULL;
1460         if (sysattr == NULL)
1461                 return NULL;
1462
1463         /* look for possibly already cached result */
1464         list_entry = udev_list_get_entry(&udev_device->sysattr_value_list);
1465         list_entry = udev_list_entry_get_by_name(list_entry, sysattr);
1466         if (list_entry != NULL)
1467                 return udev_list_entry_get_value(list_entry);
1468
1469         strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", sysattr, NULL);
1470         if (lstat(path, &statbuf) != 0) {
1471                 udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, NULL);
1472                 goto out;
1473         }
1474
1475         if (S_ISLNK(statbuf.st_mode)) {
1476                 /*
1477                  * Some core links return only the last element of the target path,
1478                  * these are just values, the paths should not be exposed.
1479                  */
1480                 if (streq(sysattr, "driver") ||
1481                     streq(sysattr, "subsystem") ||
1482                     streq(sysattr, "module")) {
1483                         if (util_get_sys_core_link_value(udev_device->udev, sysattr,
1484                                                          udev_device->syspath, value, sizeof(value)) < 0)
1485                                 return NULL;
1486                         list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
1487                         val = udev_list_entry_get_value(list_entry);
1488                         goto out;
1489                 }
1490
1491                 goto out;
1492         }
1493
1494         /* skip directories */
1495         if (S_ISDIR(statbuf.st_mode))
1496                 goto out;
1497
1498         /* skip non-readable files */
1499         if ((statbuf.st_mode & S_IRUSR) == 0)
1500                 goto out;
1501
1502         /* read attribute value */
1503         fd = open(path, O_RDONLY|O_CLOEXEC);
1504         if (fd < 0)
1505                 goto out;
1506         size = read(fd, value, sizeof(value));
1507         close(fd);
1508         if (size < 0)
1509                 goto out;
1510         if (size == sizeof(value))
1511                 goto out;
1512
1513         /* got a valid value, store it in cache and return it */
1514         value[size] = '\0';
1515         util_remove_trailing_chars(value, '\n');
1516         list_entry = udev_list_entry_add(&udev_device->sysattr_value_list, sysattr, value);
1517         val = udev_list_entry_get_value(list_entry);
1518 out:
1519         return val;
1520 }
1521
1522 /**
1523  * udev_device_set_sysattr_value:
1524  * @udev_device: udev device
1525  * @sysattr: attribute name
1526  * @value: new value to be set
1527  *
1528  * Update the contents of the sys attribute and the cached value of the device.
1529  *
1530  * Returns: Negative error code on failure or 0 on success.
1531  **/
1532 _public_ int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *sysattr, char *value)
1533 {
1534         struct udev_device *dev;
1535         char path[UTIL_PATH_SIZE];
1536         struct stat statbuf;
1537         int fd;
1538         ssize_t size, value_len;
1539         int ret = 0;
1540
1541         if (udev_device == NULL)
1542                 return -EINVAL;
1543         dev = udev_device;
1544         if (sysattr == NULL)
1545                 return -EINVAL;
1546         if (value == NULL)
1547                 value_len = 0;
1548         else
1549                 value_len = strlen(value);
1550
1551         strscpyl(path, sizeof(path), udev_device_get_syspath(dev), "/", sysattr, NULL);
1552         if (lstat(path, &statbuf) != 0) {
1553                 udev_list_entry_add(&dev->sysattr_value_list, sysattr, NULL);
1554                 ret = -ENXIO;
1555                 goto out;
1556         }
1557
1558         if (S_ISLNK(statbuf.st_mode)) {
1559                 ret = -EINVAL;
1560                 goto out;
1561         }
1562
1563         /* skip directories */
1564         if (S_ISDIR(statbuf.st_mode)) {
1565                 ret = -EISDIR;
1566                 goto out;
1567         }
1568
1569         /* skip non-readable files */
1570         if ((statbuf.st_mode & S_IRUSR) == 0) {
1571                 ret = -EACCES;
1572                 goto out;
1573         }
1574
1575         /* Value is limited to 4k */
1576         if (value_len > 4096) {
1577                 ret = -EINVAL;
1578                 goto out;
1579         }
1580         util_remove_trailing_chars(value, '\n');
1581
1582         /* write attribute value */
1583         fd = open(path, O_WRONLY|O_CLOEXEC);
1584         if (fd < 0) {
1585                 ret = -errno;
1586                 goto out;
1587         }
1588         size = write(fd, value, value_len);
1589         close(fd);
1590         if (size < 0) {
1591                 ret = -errno;
1592                 goto out;
1593         }
1594         if (size < value_len) {
1595                 ret = -EIO;
1596                 goto out;
1597         }
1598
1599         /* wrote a valid value, store it in cache and return it */
1600         udev_list_entry_add(&dev->sysattr_value_list, sysattr, value);
1601 out:
1602         if (dev != udev_device)
1603                 udev_device_unref(dev);
1604         return ret;
1605 }
1606
1607 static int udev_device_sysattr_list_read(struct udev_device *udev_device)
1608 {
1609         struct dirent *dent;
1610         DIR *dir;
1611         int num = 0;
1612
1613         if (udev_device == NULL)
1614                 return -EINVAL;
1615         if (udev_device->sysattr_list_read)
1616                 return 0;
1617
1618         dir = opendir(udev_device_get_syspath(udev_device));
1619         if (!dir)
1620                 return -errno;
1621
1622         for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
1623                 char path[UTIL_PATH_SIZE];
1624                 struct stat statbuf;
1625
1626                 /* only handle symlinks and regular files */
1627                 if (dent->d_type != DT_LNK && dent->d_type != DT_REG)
1628                         continue;
1629
1630                 strscpyl(path, sizeof(path), udev_device_get_syspath(udev_device), "/", dent->d_name, NULL);
1631                 if (lstat(path, &statbuf) != 0)
1632                         continue;
1633                 if ((statbuf.st_mode & S_IRUSR) == 0)
1634                         continue;
1635
1636                 udev_list_entry_add(&udev_device->sysattr_list, dent->d_name, NULL);
1637                 num++;
1638         }
1639
1640         closedir(dir);
1641         udev_device->sysattr_list_read = true;
1642
1643         return num;
1644 }
1645
1646 /**
1647  * udev_device_get_sysattr_list_entry:
1648  * @udev_device: udev device
1649  *
1650  * Retrieve the list of available sysattrs, with value being empty;
1651  * This just return all available sysfs attributes for a particular
1652  * device without reading their values.
1653  *
1654  * Returns: the first entry of the property list
1655  **/
1656 _public_ struct udev_list_entry *udev_device_get_sysattr_list_entry(struct udev_device *udev_device)
1657 {
1658         if (!udev_device->sysattr_list_read) {
1659                 int ret;
1660                 ret = udev_device_sysattr_list_read(udev_device);
1661                 if (0 > ret)
1662                         return NULL;
1663         }
1664
1665         return udev_list_get_entry(&udev_device->sysattr_list);
1666 }
1667
1668 static int udev_device_set_devnode(struct udev_device *udev_device, const char *devnode)
1669 {
1670         free(udev_device->devnode);
1671         if (devnode[0] != '/') {
1672                 if (asprintf(&udev_device->devnode, "/dev/%s", devnode) < 0)
1673                         udev_device->devnode = NULL;
1674         } else {
1675                 udev_device->devnode = strdup(devnode);
1676         }
1677         if (udev_device->devnode == NULL)
1678                 return -ENOMEM;
1679         udev_device_add_property_internal(udev_device, "DEVNAME", udev_device->devnode);
1680         return 0;
1681 }
1682
1683 int udev_device_add_devlink(struct udev_device *udev_device, const char *devlink)
1684 {
1685         struct udev_list_entry *list_entry;
1686
1687         udev_device->devlinks_uptodate = false;
1688         list_entry = udev_list_entry_add(&udev_device->devlinks_list, devlink, NULL);
1689         if (list_entry == NULL)
1690                 return -ENOMEM;
1691         return 0;
1692 }
1693
1694 const char *udev_device_get_id_filename(struct udev_device *udev_device)
1695 {
1696         if (udev_device->id_filename == NULL) {
1697                 if (udev_device_get_subsystem(udev_device) == NULL)
1698                         return NULL;
1699
1700                 if (major(udev_device_get_devnum(udev_device)) > 0) {
1701                         /* use dev_t -- b259:131072, c254:0 */
1702                         if (asprintf(&udev_device->id_filename, "%c%u:%u",
1703                                      streq(udev_device_get_subsystem(udev_device), "block") ? 'b' : 'c',
1704                                      major(udev_device_get_devnum(udev_device)),
1705                                      minor(udev_device_get_devnum(udev_device))) < 0)
1706                                 udev_device->id_filename = NULL;
1707                 } else if (udev_device_get_ifindex(udev_device) > 0) {
1708                         /* use netdev ifindex -- n3 */
1709                         if (asprintf(&udev_device->id_filename, "n%i", udev_device_get_ifindex(udev_device)) < 0)
1710                                 udev_device->id_filename = NULL;
1711                 } else {
1712                         /*
1713                          * use $subsys:$syname -- pci:0000:00:1f.2
1714                          * sysname() has '!' translated, get it from devpath
1715                          */
1716                         const char *sysname;
1717                         sysname = strrchr(udev_device->devpath, '/');
1718                         if (sysname == NULL)
1719                                 return NULL;
1720                         sysname = &sysname[1];
1721                         if (asprintf(&udev_device->id_filename, "+%s:%s", udev_device_get_subsystem(udev_device), sysname) < 0)
1722                                 udev_device->id_filename = NULL;
1723                 }
1724         }
1725         return udev_device->id_filename;
1726 }
1727
1728 /**
1729  * udev_device_get_is_initialized:
1730  * @udev_device: udev device
1731  *
1732  * Check if udev has already handled the device and has set up
1733  * device node permissions and context, or has renamed a network
1734  * device.
1735  *
1736  * This is only implemented for devices with a device node
1737  * or network interfaces. All other devices return 1 here.
1738  *
1739  * Returns: 1 if the device is set up. 0 otherwise.
1740  **/
1741 _public_ int udev_device_get_is_initialized(struct udev_device *udev_device)
1742 {
1743         if (!udev_device->info_loaded)
1744                 udev_device_read_db(udev_device);
1745         return udev_device->is_initialized;
1746 }
1747
1748 void udev_device_set_is_initialized(struct udev_device *udev_device)
1749 {
1750         udev_device->is_initialized = true;
1751 }
1752
1753 static bool is_valid_tag(const char *tag)
1754 {
1755         return !strchr(tag, ':') && !strchr(tag, ' ');
1756 }
1757
1758 int udev_device_add_tag(struct udev_device *udev_device, const char *tag)
1759 {
1760         if (!is_valid_tag(tag))
1761                 return -EINVAL;
1762         udev_device->tags_uptodate = false;
1763         if (udev_list_entry_add(&udev_device->tags_list, tag, NULL) != NULL)
1764                 return 0;
1765         return -ENOMEM;
1766 }
1767
1768 void udev_device_remove_tag(struct udev_device *udev_device, const char *tag)
1769 {
1770         struct udev_list_entry *e;
1771
1772         if (!is_valid_tag(tag))
1773                 return;
1774         e = udev_list_get_entry(&udev_device->tags_list);
1775         e = udev_list_entry_get_by_name(e, tag);
1776         if (e) {
1777                 udev_device->tags_uptodate = false;
1778                 udev_list_entry_delete(e);
1779         }
1780 }
1781
1782 void udev_device_cleanup_tags_list(struct udev_device *udev_device)
1783 {
1784         udev_device->tags_uptodate = false;
1785         udev_list_cleanup(&udev_device->tags_list);
1786 }
1787
1788 /**
1789  * udev_device_get_tags_list_entry:
1790  * @udev_device: udev device
1791  *
1792  * Retrieve the list of tags attached to the udev device. The next
1793  * list entry can be retrieved with udev_list_entry_get_next(),
1794  * which returns #NULL if no more entries exist. The tag string
1795  * can be retrieved from the list entry by udev_list_entry_get_name().
1796  *
1797  * Returns: the first entry of the tag list
1798  **/
1799 _public_ struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device)
1800 {
1801         if (udev_device == NULL)
1802                 return NULL;
1803         if (!udev_device->info_loaded)
1804                 udev_device_read_db(udev_device);
1805         return udev_list_get_entry(&udev_device->tags_list);
1806 }
1807
1808 /**
1809  * udev_device_has_tag:
1810  * @udev_device: udev device
1811  * @tag: tag name
1812  *
1813  * Check if a given device has a certain tag associated.
1814  *
1815  * Returns: 1 if the tag is found. 0 otherwise.
1816  **/
1817 _public_ int udev_device_has_tag(struct udev_device *udev_device, const char *tag)
1818 {
1819         struct udev_list_entry *list_entry;
1820
1821         if (udev_device == NULL)
1822                 return false;
1823         if (!udev_device->info_loaded)
1824                 udev_device_read_db(udev_device);
1825         list_entry = udev_device_get_tags_list_entry(udev_device);
1826         if (udev_list_entry_get_by_name(list_entry, tag) != NULL)
1827                 return true;
1828         return false;
1829 }
1830
1831 #define ENVP_SIZE                        128
1832 #define MONITOR_BUF_SIZE                4096
1833 static int update_envp_monitor_buf(struct udev_device *udev_device)
1834 {
1835         struct udev_list_entry *list_entry;
1836         char *s;
1837         size_t l;
1838         unsigned int i;
1839
1840         /* monitor buffer of property strings */
1841         free(udev_device->monitor_buf);
1842         udev_device->monitor_buf_len = 0;
1843         udev_device->monitor_buf = malloc(MONITOR_BUF_SIZE);
1844         if (udev_device->monitor_buf == NULL)
1845                 return -ENOMEM;
1846
1847         /* envp array, strings will point into monitor buffer */
1848         if (udev_device->envp == NULL)
1849                 udev_device->envp = malloc(sizeof(char *) * ENVP_SIZE);
1850         if (udev_device->envp == NULL)
1851                 return -ENOMEM;
1852
1853         i = 0;
1854         s = udev_device->monitor_buf;
1855         l = MONITOR_BUF_SIZE;
1856         udev_list_entry_foreach(list_entry, udev_device_get_properties_list_entry(udev_device)) {
1857                 const char *key;
1858
1859                 key = udev_list_entry_get_name(list_entry);
1860                 /* skip private variables */
1861                 if (key[0] == '.')
1862                         continue;
1863
1864                 /* add string to envp array */
1865                 udev_device->envp[i++] = s;
1866                 if (i+1 >= ENVP_SIZE)
1867                         return -EINVAL;
1868
1869                 /* add property string to monitor buffer */
1870                 l = strpcpyl(&s, l, key, "=", udev_list_entry_get_value(list_entry), NULL);
1871                 if (l == 0)
1872                         return -EINVAL;
1873                 /* advance past the trailing '\0' that strpcpyl() guarantees */
1874                 s++;
1875                 l--;
1876         }
1877         udev_device->envp[i] = NULL;
1878         udev_device->monitor_buf_len = s - udev_device->monitor_buf;
1879         udev_device->envp_uptodate = true;
1880         return 0;
1881 }
1882
1883 char **udev_device_get_properties_envp(struct udev_device *udev_device)
1884 {
1885         if (!udev_device->envp_uptodate)
1886                 if (update_envp_monitor_buf(udev_device) != 0)
1887                         return NULL;
1888         return udev_device->envp;
1889 }
1890
1891 ssize_t udev_device_get_properties_monitor_buf(struct udev_device *udev_device, const char **buf)
1892 {
1893         if (!udev_device->envp_uptodate)
1894                 if (update_envp_monitor_buf(udev_device) != 0)
1895                         return -EINVAL;
1896         *buf = udev_device->monitor_buf;
1897         return udev_device->monitor_buf_len;
1898 }
1899
1900 int udev_device_set_action(struct udev_device *udev_device, const char *action)
1901 {
1902         free(udev_device->action);
1903         udev_device->action = strdup(action);
1904         if (udev_device->action == NULL)
1905                 return -ENOMEM;
1906         udev_device_add_property_internal(udev_device, "ACTION", udev_device->action);
1907         return 0;
1908 }
1909
1910 int udev_device_get_devlink_priority(struct udev_device *udev_device)
1911 {
1912         if (!udev_device->info_loaded)
1913                 udev_device_read_db(udev_device);
1914         return udev_device->devlink_priority;
1915 }
1916
1917 int udev_device_set_devlink_priority(struct udev_device *udev_device, int prio)
1918 {
1919          udev_device->devlink_priority = prio;
1920         return 0;
1921 }
1922
1923 int udev_device_get_watch_handle(struct udev_device *udev_device)
1924 {
1925         if (!udev_device->info_loaded)
1926                 udev_device_read_db(udev_device);
1927         return udev_device->watch_handle;
1928 }
1929
1930 int udev_device_set_watch_handle(struct udev_device *udev_device, int handle)
1931 {
1932         udev_device->watch_handle = handle;
1933         return 0;
1934 }
1935
1936 bool udev_device_get_db_persist(struct udev_device *udev_device)
1937 {
1938         return udev_device->db_persist;
1939 }
1940
1941 void udev_device_set_db_persist(struct udev_device *udev_device)
1942 {
1943         udev_device->db_persist = true;
1944 }
1945
1946 int udev_device_rename(struct udev_device *udev_device, const char *name)
1947 {
1948         _cleanup_free_ char *dirname = NULL;
1949         const char *interface;
1950         char *new_syspath;
1951         int r;
1952
1953         if (udev_device == NULL || name == NULL)
1954                 return -EINVAL;
1955
1956         dirname = dirname_malloc(udev_device->syspath);
1957         if (!dirname)
1958                 return -ENOMEM;
1959
1960         new_syspath = strjoina(dirname, "/", name);
1961
1962         r = udev_device_set_syspath(udev_device, new_syspath);
1963         if (r < 0)
1964                 return r;
1965
1966         interface = udev_device_get_property_value(udev_device, "INTERFACE");
1967         if (interface) {
1968                 /* like DEVPATH_OLD, INTERFACE_OLD is not saved to the db, but only stays around for the current event */
1969                 udev_device_add_property_internal(udev_device, "INTERFACE_OLD", interface);
1970                 udev_device_add_property_internal(udev_device, "INTERFACE", name);
1971         }
1972
1973         return 0;
1974 }
1975
1976 struct udev_device *udev_device_shallow_clone(struct udev_device *old_device)
1977 {
1978         struct udev_device *device;
1979
1980         if (old_device == NULL)
1981                 return NULL;
1982
1983         device = udev_device_new(old_device->udev);
1984         if (!device) {
1985                 errno = ENOMEM;
1986
1987                 return NULL;
1988         }
1989
1990         udev_device_set_syspath(device, udev_device_get_syspath(old_device));
1991         udev_device_set_subsystem(device, udev_device_get_subsystem(old_device));
1992         udev_device_set_devnum(device, udev_device_get_devnum(old_device));
1993
1994         return device;
1995 }
1996
1997 struct udev_device *udev_device_clone_with_db(struct udev_device *old_device)
1998 {
1999         struct udev_device *device;
2000
2001         device = udev_device_shallow_clone(old_device);
2002         if (!device)
2003                 return NULL;
2004
2005         udev_device_read_db(device);
2006         udev_device_set_info_loaded(device);
2007
2008         return device;
2009 }
2010
2011 struct udev_device *udev_device_new_from_nulstr(struct udev *udev, char *nulstr, ssize_t buflen) {
2012         struct udev_device *device;
2013         ssize_t bufpos = 0;
2014
2015         if (nulstr == NULL || buflen <= 0) {
2016                 errno = EINVAL;
2017
2018                 return NULL;
2019         }
2020
2021         device = udev_device_new(udev);
2022         if (!device) {
2023                 errno = ENOMEM;
2024
2025                 return NULL;
2026         }
2027
2028         udev_device_set_info_loaded(device);
2029
2030         while (bufpos < buflen) {
2031                 char *key;
2032                 size_t keylen;
2033
2034                 key = nulstr + bufpos;
2035                 keylen = strlen(key);
2036                 if (keylen == 0)
2037                         break;
2038
2039                 bufpos += keylen + 1;
2040                 udev_device_add_property_from_string_parse(device, key);
2041         }
2042
2043         if (udev_device_add_property_from_string_parse_finish(device) < 0) {
2044                 log_debug("missing values, invalid device");
2045
2046                 udev_device_unref(device);
2047
2048                 errno = EINVAL;
2049
2050                 return NULL;
2051         }
2052
2053         return device;
2054 }
2055
2056 int udev_device_copy_properties(struct udev_device *dst, struct udev_device *src) {
2057         struct udev_list_entry *entry;
2058
2059         for ((entry = udev_device_get_properties_list_entry(src)); entry; entry = udev_list_entry_get_next(entry)) {
2060                 const char *key, *value;
2061
2062                 key = udev_list_entry_get_name(entry);
2063                 value = udev_list_entry_get_value(entry);
2064
2065                 udev_device_add_property(dst, key, value);
2066         }
2067
2068         return 0;
2069 }