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