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
CreateDeviceNodeWithPermissions(const struct Uevent * uevent,const char * deviceNode,bool isBlock)148 static int CreateDeviceNodeWithPermissions(const struct Uevent *uevent, const char *deviceNode, bool isBlock)
149 {
150 int major = uevent->major;
151 int minor = uevent->minor;
152 uid_t uid = uevent->ug.uid;
153 gid_t gid = uevent->ug.gid;
154 mode_t mode = DEVMODE;
155
156 (void)GetDeviceNodePermissions(deviceNode, &uid, &gid, &mode);
157 mode |= isBlock ? S_IFBLK : S_IFCHR;
158 dev_t dev = makedev((unsigned int)major, (unsigned int)minor);
159
160 (void)setegid(gid);
161 mode_t originalMask = umask(000);
162 int rc = mknod(deviceNode, mode, dev);
163 (void)umask(originalMask);
164 if (rc < 0 && errno != EEXIST) {
165 INIT_LOGE("Create device node[%s %d, %d] failed. %d", deviceNode, major, minor, errno);
166 return rc;
167 }
168 AdjustDeviceNodePermissions(deviceNode, uid, gid, mode);
169 (void)setegid(0);
170 return 0;
171 }
172
CreateDeviceNode(const struct Uevent * uevent,const char * deviceNode,char ** symLinks,bool isBlock)173 static int CreateDeviceNode(const struct Uevent *uevent, const char *deviceNode, char **symLinks, bool isBlock)
174 {
175 int rc = -1;
176
177 if (deviceNode == NULL || *deviceNode == '\0') {
178 INIT_LOGE("Invalid device file");
179 return rc;
180 }
181
182 char deviceNodeBuffer[DEVICE_FILE_SIZE] = {};
183 if (strncpy_s(deviceNodeBuffer, DEVICE_FILE_SIZE - 1, deviceNode, strlen(deviceNode)) != EOK) {
184 INIT_LOGE("Failed to copy device node");
185 return rc;
186 }
187 const char *devicePath = dirname(deviceNodeBuffer);
188 // device node always installed in /dev, should not be other locations.
189 if (STRINGEQUAL(devicePath, ".") || STRINGEQUAL(devicePath, "/")) {
190 INIT_LOGE("device path is not valid. should be starts with /dev");
191 return rc;
192 }
193
194 rc = MakeDirRecursive(devicePath, DIRMODE);
195 if (rc < 0) {
196 INIT_LOGE("Create path \" %s \" failed", devicePath);
197 return rc;
198 }
199
200 rc = CreateDeviceNodeWithPermissions(uevent, deviceNode, isBlock);
201 if (rc < 0) {
202 return rc;
203 }
204 if (symLinks != NULL) {
205 CreateSymbolLinks(deviceNode, symLinks);
206 }
207 #if defined(WITH_SELINUX) && !defined(__RAMDISK__)
208 SetDeviceLable(deviceNode, symLinks);
209 #endif
210 // No matter what result the symbol links returns,
211 // as long as create device node done, just returns success.
212 rc = 0;
213 return rc;
214 }
215
RemoveDeviceNode(const char * deviceNode,char ** symLinks)216 static int RemoveDeviceNode(const char *deviceNode, char **symLinks)
217 {
218 if (INVALIDSTRING(deviceNode)) {
219 INIT_LOGE("Invalid device node");
220 return -1;
221 }
222 if (symLinks != NULL) {
223 for (int i = 0; symLinks[i] != NULL; i++) {
224 char realPath[DEVICE_FILE_SIZE] = {0};
225 const char *linkName = symLinks[i];
226 ssize_t ret = readlink(linkName, realPath, DEVICE_FILE_SIZE - 1);
227 if (ret < 0) {
228 continue;
229 }
230 if (STRINGEQUAL(deviceNode, realPath)) {
231 INIT_LOGI("unlink %s", linkName);
232 unlink(linkName);
233 }
234 }
235 }
236 INIT_LOGI("unlink %s", deviceNode);
237 return unlink(deviceNode);
238 }
239
FindPlatformDeviceName(char * path)240 static char *FindPlatformDeviceName(char *path)
241 {
242 if (INVALIDSTRING(path)) {
243 return NULL;
244 }
245
246 if (STARTSWITH(path, "/sys/devices/platform/")) {
247 path += strlen("/sys/devices/platform/");
248 return path;
249 }
250
251 // Some platform devices may not be registered under platform device.
252 if (STARTSWITH(path, "/sys/devices/")) {
253 path += strlen("/sys/devices/");
254 return path;
255 }
256 return NULL;
257 }
258
BuildDeviceSymbolLinks(char ** links,int linkNum,const char * parent,const char * partitionName,const char * deviceName)259 static int BuildDeviceSymbolLinks(char **links, int linkNum, const char *parent,
260 const char *partitionName, const char *deviceName)
261 {
262 int num = linkNum;
263 links[num] = calloc(DEVICE_FILE_SIZE, sizeof(char));
264 if (links[num] == NULL) {
265 INIT_LOGE("Failed to allocate memory for link, err = %d", errno);
266 return num;
267 }
268
269 // If a block device without partition name.
270 // For now, we will not create symbol link for it.
271 if (!INVALIDSTRING(partitionName)) {
272 if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
273 "/dev/block/platform/%s/by-name/%s", parent, partitionName) == -1) {
274 INIT_LOGE("Failed to build link");
275 }
276 if (STRINGEQUAL(parent, bootDevice)) {
277 num = linkNum + 1;
278 links[num] = calloc(DEVICE_FILE_SIZE, sizeof(char));
279 if (links[num] == NULL) {
280 INIT_LOGE("Failed to allocate memory for link, err = %d", errno);
281 return linkNum;
282 }
283 if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
284 "/dev/block/by-name/%s", partitionName) == -1) {
285 INIT_LOGE("Failed to build link");
286 }
287 } else {
288 INIT_LOGI("%s and %s is not match", parent, bootDevice);
289 }
290 } else if (!INVALIDSTRING(deviceName)) {
291 if (snprintf_s(links[num], DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
292 "/dev/block/platform/%s/%s", parent, deviceName) == -1) {
293 INIT_LOGE("Failed to build link");
294 }
295 }
296
297 return num;
298 }
299
FreeSymbolLinks(char ** links,int length)300 static void FreeSymbolLinks(char **links, int length)
301 {
302 if (links != NULL) {
303 for (int i = 0; i < length && links[i] != NULL; i++) {
304 free(links[i]);
305 links[i] = NULL;
306 }
307 free(links);
308 links = NULL;
309 }
310 }
311
GetBlockDeviceSymbolLinks(const struct Uevent * uevent)312 static char **GetBlockDeviceSymbolLinks(const struct Uevent *uevent)
313 {
314 if (uevent == NULL || uevent->subsystem == NULL || STRINGEQUAL(uevent->subsystem, "block") == 0) {
315 INIT_LOGW("Invalid arguments, Skip to get device symbol links.");
316 return NULL;
317 }
318
319 // Only if current uevent is for real device.
320 if (!STARTSWITH(uevent->syspath, "/devices")) {
321 return NULL;
322 }
323 // For block device under one platform device.
324 // check subsystem file under directory, see if it links to bus/platform.
325 // For now, only support platform device.
326 char sysPath[SYSPATH_SIZE] = {};
327 if (snprintf_s(sysPath, SYSPATH_SIZE, SYSPATH_SIZE - 1, "/sys%s", uevent->syspath) == -1) {
328 INIT_LOGE("Failed to build sys path for device %s", uevent->syspath);
329 return NULL;
330 }
331 char **links = calloc(BLOCKDEVICE_LINKS, sizeof(char *));
332 int linkNum = 0;
333 if (links == NULL) {
334 INIT_LOGE("Failed to allocate memory for links, err = %d", errno);
335 return NULL;
336 }
337
338 // Reverse walk through sysPath, and check subsystem file under each directory.
339 char *parent = dirname(sysPath);
340 while (parent != NULL && !STRINGEQUAL(parent, "/") && !STRINGEQUAL(parent, ".")) {
341 char subsystem[SYSPATH_SIZE];
342 if (snprintf_s(subsystem, SYSPATH_SIZE, SYSPATH_SIZE - 1, "%s/subsystem", parent) == -1) {
343 INIT_LOGE("Failed to build subsystem path for device \" %s \"", uevent->syspath);
344 FreeSymbolLinks(links, BLOCKDEVICE_LINKS);
345 return NULL;
346 }
347 char *bus = GetRealPath(subsystem);
348 if (bus == NULL) {
349 parent = dirname(parent);
350 continue;
351 }
352 if (STRINGEQUAL(bus, "/sys/bus/platform")) {
353 INIT_LOGV("Find a platform device: %s", parent);
354 parent = FindPlatformDeviceName(parent);
355 if (parent != NULL) {
356 INIT_WARNING_CHECK(linkNum < BLOCKDEVICE_LINKS - 1, free(bus); links[linkNum] = NULL;
357 return links, "Too many links, ignore");
358 linkNum = BuildDeviceSymbolLinks(links, linkNum, parent, uevent->partitionName, uevent->deviceName);
359 linkNum++;
360 }
361 }
362 free(bus);
363 parent = dirname(parent);
364 }
365
366 links[linkNum] = NULL;
367 return links;
368 }
369
HandleDeviceNode(const struct Uevent * uevent,const char * deviceNode,bool isBlock)370 static void HandleDeviceNode(const struct Uevent *uevent, const char *deviceNode, bool isBlock)
371 {
372 ACTION action = uevent->action;
373 char **symLinks = NULL;
374
375 // Block device path and name maybe not human readable.
376 // Consider to create symbol links for them.
377 // Make block device more readable.
378 if (isBlock) {
379 symLinks = GetBlockDeviceSymbolLinks(uevent);
380 }
381
382 if (action == ACTION_ADD) {
383 if (CreateDeviceNode(uevent, deviceNode, symLinks, isBlock) < 0) {
384 INIT_LOGE("Create device \" %s \" failed", deviceNode);
385 } else {
386 #ifndef __RAMDISK__
387 if (SetUeventDeviceParameter(deviceNode, action) != 0) {
388 INIT_LOGE("Set device parameter added failed");
389 }
390 #endif
391 }
392 } else if (action == ACTION_REMOVE) {
393 if (RemoveDeviceNode(deviceNode, symLinks) < 0) {
394 INIT_LOGE("Remove device \" %s \" failed", deviceNode);
395 } else {
396 #ifndef __RAMDISK__
397 if (SetUeventDeviceParameter(deviceNode, action) != 0) {
398 INIT_LOGE("Set device parameter removed failed");
399 }
400 #endif
401 }
402 } else if (action == ACTION_CHANGE) {
403 INIT_LOGV("Device %s changed", uevent->syspath);
404 }
405 // Ignore other actions
406 FreeSymbolLinks(symLinks, BLOCKDEVICE_LINKS);
407 }
408
GetDeviceName(char * sysPath,const char * deviceName)409 static const char *GetDeviceName(char *sysPath, const char *deviceName)
410 {
411 const char *devName = NULL;
412 if (INVALIDSTRING(sysPath)) {
413 INIT_LOGE("Invalid sys path");
414 return NULL;
415 }
416 if (deviceName != NULL && deviceName[0] != '\0') {
417 // if device name reported by kernel includes '/', skip it.
418 // use entire device name reported by kernel
419 devName = basename((char *)deviceName);
420 char *p = strrchr(deviceName, '/');
421 if (p != NULL) { // device name includes slash
422 p++;
423 if (p == NULL || *p == '\0') {
424 // device name ends with '/', which should never happen.
425 // Get name from sys path.
426 devName = basename(sysPath);
427 } else {
428 devName = p;
429 }
430 }
431 } else {
432 // kernel does not report DEVNAME, which is possible. use base name of syspath instead.
433 devName = basename(sysPath);
434 }
435 return devName;
436 }
437
GetDeviceBasePath(const char * subsystem)438 static const char *GetDeviceBasePath(const char *subsystem)
439 {
440 char *devPath = NULL;
441 if (INVALIDSTRING(subsystem)) {
442 return devPath;
443 }
444
445 if (STRINGEQUAL(subsystem, "block")) {
446 devPath = "/dev/block";
447 } else if (STRINGEQUAL(subsystem, "input")) {
448 devPath = "/dev/input";
449 } else if (STRINGEQUAL(subsystem, "drm")) {
450 devPath = "/dev/dri";
451 } else if (STRINGEQUAL(subsystem, "graphics")) {
452 devPath = "/dev/graphics";
453 } else if (STRINGEQUAL(subsystem, "sound")) {
454 devPath = "/dev/snd";
455 } else if (STRINGEQUAL(subsystem, "functionfs")) {
456 devPath = "/dev/functionfs";
457 } else if (STRINGEQUAL(subsystem, "dma_heap")) {
458 devPath = "/dev/dma_heap";
459 } else {
460 devPath = "/dev";
461 }
462 return devPath;
463 }
464
HandleBlockDeviceEvent(const struct Uevent * uevent)465 void HandleBlockDeviceEvent(const struct Uevent *uevent)
466 {
467 // Sanity checks
468 if (uevent == NULL || uevent->subsystem == NULL) {
469 INIT_LOGE("Invalid uevent message received");
470 return;
471 }
472
473 if (strcmp(uevent->subsystem, "block") != 0) {
474 INIT_LOGE("Unexpected uevent subsystem \" %s \" received in block device handler", uevent->subsystem);
475 return;
476 }
477
478 if (uevent->major < 0 || uevent->minor < 0) {
479 return;
480 }
481
482 bool isBlock = true;
483 // Block device always installed into /dev/block
484 const char *devPath = GetDeviceBasePath(uevent->subsystem);
485 char deviceNode[DEVICE_FILE_SIZE] = {};
486 char sysPath[SYSPATH_SIZE] = {};
487
488 if (uevent->syspath == NULL) {
489 return;
490 }
491 if (strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath) != EOK)) {
492 INIT_LOGE("Failed to copy sys path");
493 return;
494 }
495 const char *devName = GetDeviceName(sysPath, uevent->deviceName);
496
497 if (devPath == NULL || devName == NULL) {
498 INIT_LOGE("Cannot get device path or device name");
499 return;
500 }
501 if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "%s/%s", devPath, devName) == -1) {
502 INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
503 return;
504 }
505 HandleDeviceNode(uevent, deviceNode, isBlock);
506 }
507
SplitUsbDeviceNode(const struct Uevent * uevent,char * deviceNode)508 static int SplitUsbDeviceNode(const struct Uevent *uevent, char *deviceNode)
509 {
510 if (uevent->deviceName != NULL) {
511 if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "/dev/%s", uevent->deviceName) == -1) {
512 INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
513 return -1;
514 }
515 return 0;
516 } else {
517 if (uevent->busNum < 0 || uevent->devNum < 0) {
518 // usb device should always report bus number and device number.
519 INIT_LOGE("usb device with invalid bus number or device number");
520 return -1;
521 }
522 if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1,
523 "/dev/bus/usb/%03d/%03d", uevent->busNum, uevent->devNum) == -1) {
524 INIT_LOGE("Make usb device node for device [%d : %d]", uevent->busNum, uevent->devNum);
525 return 0;
526 }
527 return 0;
528 }
529 }
530
HandleOtherDeviceEvent(const struct Uevent * uevent)531 void HandleOtherDeviceEvent(const struct Uevent *uevent)
532 {
533 if (uevent == NULL || uevent->subsystem == NULL || uevent->syspath == NULL) {
534 INIT_LOGE("Invalid uevent received");
535 return;
536 }
537
538 if (uevent->major < 0 || uevent->minor < 0) {
539 return;
540 }
541
542 char deviceNode[DEVICE_FILE_SIZE] = {};
543 char sysPath[SYSPATH_SIZE] = {};
544 if (strncpy_s(sysPath, SYSPATH_SIZE - 1, uevent->syspath, strlen(uevent->syspath)) != EOK) {
545 INIT_LOGE("Failed to copy sys path");
546 return;
547 }
548 const char *devName = GetDeviceName(sysPath, uevent->deviceName);
549 const char *devPath = GetDeviceBasePath(uevent->subsystem);
550
551 if (devPath == NULL || devName == NULL) {
552 INIT_LOGE("Cannot get device path or device name");
553 return;
554 }
555 if (strcmp(devPath, "/dev/input") == 0) {
556 INIT_LOGI("HandleOtherDeviceEvent, devPath = %s, devName = %s", devPath, devName);
557 }
558 INIT_LOGV("HandleOtherDeviceEvent, devPath = %s, devName = %s", devPath, devName);
559
560 // For usb devices, should take care of it specially.
561 // if usb devices report DEVNAME, just create device node.
562 // otherwise, create deviceNode with bus number and device number.
563 if (STRINGEQUAL(uevent->subsystem, "usb")) {
564 if (SplitUsbDeviceNode(uevent, deviceNode) != 0) {
565 return;
566 }
567 } else if (STARTSWITH(uevent->subsystem, "usb")) {
568 // Other usb devies, do not handle it.
569 return;
570 } else {
571 if (strcmp(uevent->deviceName, "mapper/control") == 0) {
572 devName = "mapper/control";
573 }
574 if (snprintf_s(deviceNode, DEVICE_FILE_SIZE, DEVICE_FILE_SIZE - 1, "%s/%s", devPath, devName) == -1) {
575 INIT_LOGE("Make device file for device [%d : %d]", uevent->major, uevent->minor);
576 return;
577 }
578 }
579 HandleDeviceNode(uevent, deviceNode, false);
580 }
581