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