• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ueventd_device_handler.h"
17 
18 #include <errno.h>
19 #include <libgen.h>
20 #include <limits.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/sysmacros.h>
26 #include "init_utils.h"
27 #include "ueventd.h"
28 #ifndef __RAMDISK__
29 #include "ueventd_parameter.h"
30 #endif
31 #include "ueventd_read_cfg.h"
32 #include "ueventd_utils.h"
33 #include "securec.h"
34 #define INIT_LOG_TAG "ueventd"
35 #include "init_log.h"
36 #ifdef WITH_SELINUX
37 #include <selinux/selinux.h>
38 #include <policycoreutils.h>
39 #endif
40 
AdjustDeviceNodePermissions(const char * deviceNode,uid_t uid,gid_t gid,mode_t mode)41 static inline void AdjustDeviceNodePermissions(const char *deviceNode, uid_t uid, gid_t gid, mode_t mode)
42 {
43     if (INVALIDSTRING(deviceNode)) {
44         return;
45     }
46     if (chown(deviceNode, uid, gid) != 0) {
47         INIT_LOGW("Failed to change \" %s \" owner, errno %d", deviceNode, errno);
48     }
49 
50     if (chmod(deviceNode, mode) != 0) {
51         INIT_LOGW("Failed to change \" %s \" mode, errno %d", deviceNode, errno);
52     }
53 }
54 
CreateSymbolLinks(const char * deviceNode,char ** symLinks)55 static void CreateSymbolLinks(const char *deviceNode, char **symLinks)
56 {
57     if (INVALIDSTRING(deviceNode) || symLinks == NULL) {
58         return;
59     }
60 
61     uid_t uid = 0;
62     gid_t gid = 0;
63     mode_t mode = DEVMODE;
64 
65     for (int i = 0; symLinks[i] != NULL; i++) {
66         const char *linkName = symLinks[i];
67         char linkBuf[DEVICE_FILE_SIZE] = {};
68 
69         if (strstr(linkName, "/dev/block/by-name") != NULL) {
70             int res = GetDeviceNodePermissions(linkName, &uid, &gid, &mode);
71             INIT_CHECK(res != 0, AdjustDeviceNodePermissions(deviceNode, uid, gid, mode));
72         }
73 
74         if (strncpy_s(linkBuf, DEVICE_FILE_SIZE - 1, linkName, strlen(linkName)) != EOK) {
75             INIT_LOGE("Failed to copy link name");
76             return;
77         }
78         const char *linkDir = dirname(linkBuf);
79         if (MakeDirRecursive(linkDir, DIRMODE) < 0) {
80             INIT_LOGE("[uevent] Failed to create dir \" %s \", err = %d", linkDir, errno);
81             return;
82         }
83 
84         errno = 0;
85         INIT_LOGI("symlink %s->%s", deviceNode, linkName);
86         int rc = symlink(deviceNode, linkName);
87         if (rc != 0) {
88             if (errno != EEXIST) {
89                 INIT_LOGE("Failed to link \" %s \" to \" %s \", err = %d", deviceNode, linkName, errno);
90             }
91         }
92     }
93 }
94 
95 #if defined(WITH_SELINUX) && !defined(__RAMDISK__)
SetDeviceLable(const char * path,char ** symLinks)96 static void SetDeviceLable(const char *path, char **symLinks)
97 {
98     int rc = 0;
99     char buffer[PATH_MAX] = {};
100     const char *p = NULL;
101     char *slash = NULL;
102 
103     p = path;
104     slash = strchr(path, '/');
105     while (slash != NULL) {
106         int gap = slash - p;
107         p = slash + 1;
108         if (gap == 0) {
109             slash = strchr(p, '/');
110             continue;
111         }
112         if (gap < 0) { // end with '/'
113             return;
114         }
115 
116         if (memcpy_s(buffer, PATH_MAX, path, p - path - 1) != EOK) {
117             INIT_LOGE("[uevent] Failed to memcpy path %s", path);
118             return;
119         }
120         rc += Restorecon(buffer);
121         slash = strchr(p, '/');
122     }
123 
124     rc += Restorecon(path);
125     if (rc != 0) {
126         INIT_LOGE("[uevent] Failed to Restorecon \" %s \"", path);
127     }
128 
129     INIT_CHECK_ONLY_RETURN(symLinks != NULL);
130     char *context = NULL;
131     for (int i = 0; symLinks[i] != NULL; i++) {
132         const char *linkName = symLinks[i];
133         const char *byNamePath = "/dev/block/by-name";
134         if (strncmp(linkName, byNamePath, strlen(byNamePath)) == 0) {
135             (void)Restorecon(linkName);
136             lgetfilecon(linkName, &context);
137             if (context != NULL) {
138                 setfilecon(path, context);
139             }
140             return;
141         }
142     }
143 
144     return;
145 }
146 #endif
147 
CreateDeviceNode(const struct Uevent * uevent,const char * deviceNode,char ** symLinks,bool isBlock)148 static int CreateDeviceNode(const struct Uevent *uevent, const char *deviceNode, char **symLinks, bool isBlock)
149 {
150     int rc = -1;
151     int major = uevent->major;
152     int minor = uevent->minor;
153     uid_t uid = uevent->ug.uid;
154     gid_t gid = uevent->ug.gid;
155     mode_t mode = DEVMODE;
156 
157     if (deviceNode == NULL || *deviceNode == '\0') {
158         INIT_LOGE("Invalid device file");
159         return rc;
160     }
161 
162     char deviceNodeBuffer[DEVICE_FILE_SIZE] = {};
163     if (strncpy_s(deviceNodeBuffer, DEVICE_FILE_SIZE - 1, deviceNode, strlen(deviceNode)) != EOK) {
164         INIT_LOGE("Failed to copy device node");
165         return rc;
166     }
167     const char *devicePath = dirname(deviceNodeBuffer);
168     // device node always installed in /dev, should not be other locations.
169     if (STRINGEQUAL(devicePath, ".") || STRINGEQUAL(devicePath, "/")) {
170         INIT_LOGE("device path is not valid. should be starts with /dev");
171         return rc;
172     }
173 
174     rc = MakeDirRecursive(devicePath, DIRMODE);
175     if (rc < 0) {
176         INIT_LOGE("Create path \" %s \" failed", devicePath);
177         return rc;
178     }
179 
180     (void)GetDeviceNodePermissions(deviceNode, &uid, &gid, &mode);
181     mode |= isBlock ? S_IFBLK : S_IFCHR;
182     dev_t dev = makedev(major, minor);
183     setegid(0);
184     rc = mknod(deviceNode, mode, dev);
185     if (rc < 0) {
186         if (errno != EEXIST) {
187             INIT_LOGE("Create device node[%s %d, %d] failed. %d", deviceNode, major, minor, errno);
188             return rc;
189         }
190     }
191     AdjustDeviceNodePermissions(deviceNode, uid, gid, mode);
192     if (symLinks != NULL) {
193         CreateSymbolLinks(deviceNode, symLinks);
194     }
195 #if defined(WITH_SELINUX) && !defined(__RAMDISK__)
196     SetDeviceLable(deviceNode, symLinks);
197 #endif
198     // No matter what result the symbol links returns,
199     // as long as create device node done, just returns success.
200     rc = 0;
201     return rc;
202 }
203 
RemoveDeviceNode(const char * deviceNode,char ** symLinks)204 static int RemoveDeviceNode(const char *deviceNode, char **symLinks)
205 {
206     if (INVALIDSTRING(deviceNode)) {
207         INIT_LOGE("Invalid device node");
208         return -1;
209     }
210     if (symLinks != NULL) {
211         for (int i = 0; symLinks[i] != NULL; i++) {
212             char realPath[DEVICE_FILE_SIZE] = {0};
213             const char *linkName = symLinks[i];
214             ssize_t ret = readlink(linkName, realPath, DEVICE_FILE_SIZE - 1);
215             if (ret < 0) {
216                 continue;
217             }
218             if (STRINGEQUAL(deviceNode, realPath)) {
219                 INIT_LOGI("unlink %s", linkName);
220                 unlink(linkName);
221             }
222         }
223     }
224     INIT_LOGI("unlink %s", deviceNode);
225     return unlink(deviceNode);
226 }
227 
FindPlatformDeviceName(char * path)228 static char *FindPlatformDeviceName(char *path)
229 {
230     if (INVALIDSTRING(path)) {
231         return NULL;
232     }
233 
234     if (STARTSWITH(path, "/sys/devices/platform/")) {
235         path += strlen("/sys/devices/platform/");
236         return path;
237     }
238 
239     // Some platform devices may not be registered under platform device.
240     if (STARTSWITH(path, "/sys/devices/")) {
241         path += strlen("/sys/devices/");
242         return path;
243     }
244     return NULL;
245 }
246 
BuildDeviceSymbolLinks(char ** links,int linkNum,const char * parent,const char * partitionName,const char * deviceName)247 static int BuildDeviceSymbolLinks(char **links, int linkNum, const char *parent,
248     const char *partitionName, const char *deviceName)
249 {
250     int num = linkNum;
251     links[num] = calloc(DEVICE_FILE_SIZE, sizeof(char));
252     if (links[num] == NULL) {
253         INIT_LOGE("Failed to allocate memory for link, err = %d", errno);
254         return num;
255     }
256 
257     // If a block device without partition name.
258     // For now, we will not create symbol link for it.
259     if (!INVALIDSTRING(partitionName)) {
260         if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
261             "/dev/block/platform/%s/by-name/%s", parent, partitionName) == -1) {
262             INIT_LOGE("Failed to build link");
263         }
264         if (STRINGEQUAL(parent, bootDevice)) {
265             num = linkNum + 1;
266             links[num] = calloc(DEVICE_FILE_SIZE, sizeof(char));
267             if (links[num] == NULL) {
268                 INIT_LOGE("Failed to allocate memory for link, err = %d", errno);
269                 return linkNum;
270             }
271             if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
272                 "/dev/block/by-name/%s", partitionName) == -1) {
273                 INIT_LOGE("Failed to build link");
274             }
275         }
276     } else if (!INVALIDSTRING(deviceName)) {
277         if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
278             "/dev/block/platform/%s/%s", parent, deviceName) == -1) {
279             INIT_LOGE("Failed to build link");
280         }
281     }
282 
283     return num;
284 }
285 
FreeSymbolLinks(char ** links,int length)286 static void FreeSymbolLinks(char **links, int length)
287 {
288     if (links != NULL) {
289         for (int i = 0; i < length && links[i] != NULL; i++) {
290             free(links[i]);
291             links[i] = NULL;
292         }
293         free(links);
294         links = NULL;
295     }
296 }
297 
GetBlockDeviceSymbolLinks(const struct Uevent * uevent)298 static char **GetBlockDeviceSymbolLinks(const struct Uevent *uevent)
299 {
300     if (uevent == NULL || uevent->subsystem == NULL || STRINGEQUAL(uevent->subsystem, "block") == 0) {
301         INIT_LOGW("Invalid arguments, Skip to get device symbol links.");
302         return NULL;
303     }
304 
305     // Only if current uevent is for real device.
306     if (!STARTSWITH(uevent->syspath, "/devices")) {
307         return NULL;
308     }
309     // For block device under one platform device.
310     // check subsystem file under directory, see if it links to bus/platform.
311     // For now, only support platform device.
312     char sysPath[SYSPATH_SIZE] = {};
313     if (snprintf_s(sysPath, SYSPATH_SIZE, SYSPATH_SIZE - 1, "/sys%s", uevent->syspath) == -1) {
314         INIT_LOGE("Failed to build sys path for device %s", uevent->syspath);
315         return NULL;
316     }
317     char **links = calloc(BLOCKDEVICE_LINKS, sizeof(char *));
318     int linkNum = 0;
319     if (links == NULL) {
320         INIT_LOGE("Failed to allocate memory for links, err = %d", errno);
321         return NULL;
322     }
323 
324     // Reverse walk through sysPath, and check subsystem file under each directory.
325     char *parent = dirname(sysPath);
326     while (parent != NULL && !STRINGEQUAL(parent, "/") && !STRINGEQUAL(parent, ".")) {
327         char subsystem[SYSPATH_SIZE];
328         if (snprintf_s(subsystem, SYSPATH_SIZE, SYSPATH_SIZE - 1, "%s/subsystem", parent) == -1) {
329             INIT_LOGE("Failed to build subsystem path for device \" %s \"", uevent->syspath);
330             FreeSymbolLinks(links, BLOCKDEVICE_LINKS);
331             return NULL;
332         }
333         char *bus = GetRealPath(subsystem);
334         if (bus == NULL) {
335             parent = dirname(parent);
336             continue;
337         }
338         if (STRINGEQUAL(bus, "/sys/bus/platform")) {
339             INIT_LOGV("Find a platform device: %s", parent);
340             parent = FindPlatformDeviceName(parent);
341             if (parent != NULL) {
342                 INIT_WARNING_CHECK(linkNum < BLOCKDEVICE_LINKS - 1, links[linkNum] = NULL;
343                     return links, "Too many links, ignore");
344                 linkNum = BuildDeviceSymbolLinks(links, linkNum, parent, uevent->partitionName, uevent->deviceName);
345                 linkNum++;
346             }
347         }
348         free(bus);
349         parent = dirname(parent);
350     }
351 
352     links[linkNum] = NULL;
353     return links;
354 }
355 
HandleDeviceNode(const struct Uevent * uevent,const char * deviceNode,bool isBlock)356 static void HandleDeviceNode(const struct Uevent *uevent, const char *deviceNode, bool isBlock)
357 {
358     ACTION action = uevent->action;
359     char **symLinks = NULL;
360 
361     // Block device path and name maybe not human readable.
362     // Consider to create symbol links for them.
363     // Make block device more readable.
364     if (isBlock) {
365         symLinks = GetBlockDeviceSymbolLinks(uevent);
366     }
367 
368     if (action == ACTION_ADD) {
369         if (CreateDeviceNode(uevent, deviceNode, symLinks, isBlock) < 0) {
370             INIT_LOGE("Create device \" %s \" failed", deviceNode);
371         } else {
372 #ifndef __RAMDISK__
373             if (SetUeventDeviceParameter(deviceNode, action) != 0) {
374                 INIT_LOGE("Set device parameter added failed");
375             }
376 #endif
377         }
378     } else if (action == ACTION_REMOVE) {
379         if (RemoveDeviceNode(deviceNode, symLinks) < 0) {
380             INIT_LOGE("Remove device \" %s \" failed", deviceNode);
381         } else {
382 #ifndef __RAMDISK__
383             if (SetUeventDeviceParameter(deviceNode, action) != 0) {
384                 INIT_LOGE("Set device parameter removed failed");
385             }
386 #endif
387         }
388     } else if (action == ACTION_CHANGE) {
389         INIT_LOGV("Device %s changed", uevent->syspath);
390     }
391     // Ignore other actions
392     FreeSymbolLinks(symLinks, BLOCKDEVICE_LINKS);
393 }
394 
GetDeviceName(char * sysPath,const char * deviceName)395 static const char *GetDeviceName(char *sysPath, const char *deviceName)
396 {
397     const char *devName = NULL;
398     if (INVALIDSTRING(sysPath)) {
399         INIT_LOGE("Invalid sys path");
400         return NULL;
401     }
402     if (deviceName != NULL && deviceName[0] != '\0') {
403         // if device name reported by kernel includes '/', skip it.
404         // use entire device name reported by kernel
405         devName = basename((char *)deviceName);
406         char *p = strrchr(deviceName, '/');
407         if (p != NULL) { // device name includes slash
408             p++;
409             if (p == NULL || *p == '\0') {
410                 // device name ends with '/', which should never happen.
411                 // Get name from sys path.
412                 devName = basename(sysPath);
413             } else {
414                 devName = p;
415             }
416         }
417     } else {
418         // kernel does not report DEVNAME, which is possible. use base name of syspath instead.
419         devName = basename(sysPath);
420     }
421     return devName;
422 }
423 
GetDeviceBasePath(const char * subsystem)424 static const char *GetDeviceBasePath(const char *subsystem)
425 {
426     char *devPath = NULL;
427     if (INVALIDSTRING(subsystem)) {
428         return devPath;
429     }
430 
431     if (STRINGEQUAL(subsystem, "block")) {
432         devPath = "/dev/block";
433     } else if (STRINGEQUAL(subsystem, "input")) {
434         devPath = "/dev/input";
435     } else if (STRINGEQUAL(subsystem, "drm")) {
436         devPath = "/dev/dri";
437     } else if (STRINGEQUAL(subsystem, "graphics")) {
438         devPath = "/dev/graphics";
439     } else if (STRINGEQUAL(subsystem, "sound")) {
440         devPath = "/dev/snd";
441     } else if (STRINGEQUAL(subsystem, "functionfs")) {
442         devPath = "/dev/functionfs";
443     } else if (STRINGEQUAL(subsystem, "dma_heap")) {
444         devPath = "/dev/dma_heap";
445     } else {
446         devPath = "/dev";
447     }
448     return devPath;
449 }
450 
HandleBlockDeviceEvent(const struct Uevent * uevent)451 void HandleBlockDeviceEvent(const struct Uevent *uevent)
452 {
453     // Sanity checks
454     if (uevent == NULL || uevent->subsystem == NULL) {
455         INIT_LOGE("Invalid uevent message received");
456         return;
457     }
458 
459     if (strcmp(uevent->subsystem, "block") != 0) {
460         INIT_LOGE("Unexpected uevent subsystem \" %s \" received in block device handler", uevent->subsystem);
461         return;
462     }
463 
464     if (uevent->major < 0 || uevent->minor < 0) {
465         return;
466     }
467 
468     bool isBlock = true;
469     // Block device always installed into /dev/block
470     const char *devPath = GetDeviceBasePath(uevent->subsystem);
471     char deviceNode[DEVICE_FILE_SIZE] = {};
472     char sysPath[SYSPATH_SIZE] = {};
473 
474     if (uevent->syspath == NULL) {
475         return;
476     }
477     if (strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath) != EOK)) {
478         INIT_LOGE("Failed to copy sys path");
479         return;
480     }
481     const char *devName = GetDeviceName(sysPath, uevent->deviceName);
482 
483     if (devPath == NULL || devName == NULL) {
484         INIT_LOGE("Cannot get device path or device name");
485         return;
486     }
487     if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "%s/%s", devPath, devName) == -1) {
488         INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
489         return;
490     }
491     HandleDeviceNode(uevent, deviceNode, isBlock);
492 }
493 
HandleOtherDeviceEvent(const struct Uevent * uevent)494 void HandleOtherDeviceEvent(const struct Uevent *uevent)
495 {
496     if (uevent == NULL || uevent->subsystem == NULL || uevent->syspath == NULL) {
497         INIT_LOGE("Invalid uevent received");
498         return;
499     }
500 
501     if (uevent->major < 0 || uevent->minor < 0) {
502         return;
503     }
504 
505     char deviceNode[DEVICE_FILE_SIZE] = {};
506     char sysPath[SYSPATH_SIZE] = {};
507     if (strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath)) != EOK) {
508         INIT_LOGE("Failed to copy sys path");
509         return;
510     }
511     const char *devName = GetDeviceName(sysPath, uevent->deviceName);
512     const char *devPath = GetDeviceBasePath(uevent->subsystem);
513 
514     if (devPath == NULL || devName == NULL) {
515         INIT_LOGE("Cannot get device path or device name");
516         return;
517     }
518     INIT_LOGV("HandleOtherDeviceEvent, devPath = %s, devName = %s", devPath, devName);
519 
520     // For usb devices, should take care of it specially.
521     // if usb devices report DEVNAME, just create device node.
522     // otherwise, create deviceNode with bus number and device number.
523     if (STRINGEQUAL(uevent->subsystem, "usb")) {
524         if (uevent->deviceName != NULL) {
525             if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "/dev/%s", uevent->deviceName) == -1) {
526                 INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
527                 return;
528             }
529         } else {
530             if (uevent->busNum < 0 || uevent->devNum < 0) {
531                 // usb device should always report bus number and device number.
532                 INIT_LOGE("usb device with invalid bus number or device number");
533                 return;
534             }
535             if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
536                 "/dev/bus/usb/%03d/%03d", uevent->busNum, uevent->devNum) == -1) {
537                 INIT_LOGE("Make usb device node for device [%d : %d]", uevent->busNum, uevent->devNum);
538             }
539         }
540     } else if (STARTSWITH(uevent->subsystem, "usb")) {
541         // Other usb devies, do not handle it.
542         return;
543     } else {
544         if (strcmp(uevent->deviceName, "mapper/control") == 0) {
545             devName = "mapper/control";
546         }
547         if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "%s/%s", devPath, devName) == -1) {
548             INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
549             return;
550         }
551     }
552     HandleDeviceNode(uevent, deviceNode, false);
553 }
554