Coverage Report

Created: 2026-10-16 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lvm2/libdm/libdm-common.c
Line
Count
Source
1
/*
2
 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3
 * Copyright (C) 2004-2025 Red Hat, Inc. All rights reserved.
4
 *
5
 * This file is part of the device-mapper userspace tools.
6
 *
7
 * This copyrighted material is made available to anyone wishing to use,
8
 * modify, copy, or redistribute it subject to the terms and conditions
9
 * of the GNU Lesser General Public License v.2.1.
10
 *
11
 * You should have received a copy of the GNU Lesser General Public License
12
 * along with this program; if not, write to the Free Software Foundation,
13
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
14
 */
15
16
#include "libdm/misc/dmlib.h"
17
#include "libdm/ioctl/libdm-targets.h"
18
#include "libdm-common.h"
19
#include "libdm/misc/kdev_t.h"
20
#include "libdm/misc/dm-ioctl.h"
21
22
#include <stdarg.h>
23
#include <pthread.h>
24
#include <sys/param.h>
25
#include <sys/ioctl.h>
26
#include <fcntl.h>
27
#include <dirent.h>
28
29
#ifdef UDEV_SYNC_SUPPORT
30
#  include <sys/types.h>
31
#  include <sys/ipc.h>
32
#  include <sys/sem.h>
33
#endif
34
35
#ifdef __linux__
36
#  include <linux/fs.h>
37
#endif
38
39
#ifdef HAVE_SELINUX
40
#  include <selinux/selinux.h>
41
#endif
42
#ifdef HAVE_SELINUX_LABEL_H
43
#  include <selinux/label.h>
44
#endif
45
46
2
#define DM_DEFAULT_NAME_MANGLING_MODE_ENV_VAR_NAME "DM_DEFAULT_NAME_MANGLING_MODE"
47
48
0
#define DEV_DIR "/dev/"
49
50
#define UDEV_CONTROL_PATH "/run/udev/control"
51
#define UDEV_LEGACY_QUEUE_PATH "/dev/.udev/queue.bin"
52
53
#ifdef UDEV_SYNC_SUPPORT
54
#ifdef _SEM_SEMUN_UNDEFINED
55
union semun
56
{
57
  int val;      /* value for SETVAL */
58
  struct semid_ds *buf;   /* buffer for IPC_STAT & IPC_SET */
59
  unsigned short int *array;  /* array for GETALL & SETALL */
60
  struct seminfo *__buf;    /* buffer for IPC_INFO */
61
};
62
#endif
63
#endif
64
65
static char _dm_dir[PATH_MAX] = DEV_DIR DM_DIR;
66
static char _sysfs_dir[PATH_MAX] = "/sys/";
67
static const char _mountinfo[] = "/proc/self/mountinfo";
68
69
0
#define DM_MAX_UUID_PREFIX_LEN  15
70
static char _default_uuid_prefix[DM_MAX_UUID_PREFIX_LEN + 1] = "LVM-";
71
72
static int _verbose = 0;
73
static int _suspended_dev_counter = 0;
74
static dm_string_mangling_t _name_mangling_mode = DEFAULT_DM_NAME_MANGLING;
75
76
#ifdef HAVE_SELINUX_LABEL_H
77
static struct selabel_handle *_selabel_handle = NULL;
78
static pthread_once_t _selabel_once = PTHREAD_ONCE_INIT;
79
80
static void _init_selabel_handle(void)
81
{
82
  _selabel_handle = selabel_open(SELABEL_CTX_FILE, NULL, 0);
83
}
84
85
static struct selabel_handle *_get_selabel_handle(void)
86
{
87
  pthread_once(&_selabel_once, _init_selabel_handle);
88
89
  return _selabel_handle;
90
}
91
#endif
92
93
/* Set once in dm_lib_init(), immutable after -- safe for concurrent reads */
94
static int _udev_disabled = 0;
95
96
/* Thread that called dm_lib_init() -- only this thread may call set-once setters */
97
static pthread_t _init_tid;
98
99
static int _is_init_thread(const char *action)
100
0
{
101
0
  if (pthread_equal(pthread_self(), _init_tid))
102
0
    return 1;
103
104
0
  log_warn("WARNING: Only main thread can %s.", action);
105
106
0
  return 0;
107
0
}
108
109
#ifdef UDEV_SYNC_SUPPORT
110
static int _semaphore_supported = 0;
111
static int _udev_running = 0;
112
#endif
113
114
static pthread_once_t _lib_init_once = PTHREAD_ONCE_INIT;
115
116
static void _do_lib_init(void)
117
2
{
118
2
  const char *env;
119
120
2
  _init_tid = pthread_self();
121
122
2
  if (getenv("DM_DISABLE_UDEV"))
123
0
    _udev_disabled = 1;
124
125
2
  _name_mangling_mode = DEFAULT_DM_NAME_MANGLING;
126
2
  if ((env = getenv(DM_DEFAULT_NAME_MANGLING_MODE_ENV_VAR_NAME))) {
127
0
    if (!strcasecmp(env, "none"))
128
0
      _name_mangling_mode = DM_STRING_MANGLING_NONE;
129
0
    else if (!strcasecmp(env, "auto"))
130
0
      _name_mangling_mode = DM_STRING_MANGLING_AUTO;
131
0
    else if (!strcasecmp(env, "hex"))
132
0
      _name_mangling_mode = DM_STRING_MANGLING_HEX;
133
0
  }
134
2
}
135
136
void dm_lib_init(void)
137
2
{
138
2
  pthread_once(&_lib_init_once, _do_lib_init);
139
2
}
140
141
static void _dm_lib_init(void) __attribute__((constructor));
142
143
static void _dm_lib_init(void)
144
2
{
145
2
  dm_lib_init();
146
2
}
147
148
/*
149
 * Library users can provide their own logging
150
 * function.
151
 */
152
153
static int _abort_on_internal_errors = 0;
154
static int _debug_with_line_numbers = 0;
155
static pthread_once_t _log_env_once = PTHREAD_ONCE_INIT;
156
157
static void _init_log_env_vars(void)
158
0
{
159
0
  _abort_on_internal_errors =
160
0
    strcmp(getenv("DM_ABORT_ON_INTERNAL_ERRORS") ? : "0", "0") != 0;
161
0
  _debug_with_line_numbers =
162
0
    strcmp(getenv("DM_DEBUG_WITH_LINE_NUMBERS") ? : "0", "0") != 0;
163
0
}
164
165
__attribute__((format(printf, 5, 0)))
166
static void _default_log_line(int level, const char *file,
167
            int line, int dm_errno_or_class,
168
            const char *f, va_list ap)
169
0
{
170
0
  FILE *out = log_stderr(level) ? stderr : stdout;
171
172
0
  pthread_once(&_log_env_once, _init_log_env_vars);
173
174
0
  level = log_level(level);
175
176
0
  if (level <= _LOG_WARN || _verbose) {
177
0
    if (level < _LOG_WARN)
178
0
      out = stderr;
179
180
0
    if (_verbose && _debug_with_line_numbers)
181
0
      fprintf(out, "%s:%d     ", file, line);
182
183
0
    vfprintf(out, f, ap);
184
0
    fputc('\n', out);
185
0
  }
186
187
0
  if (_abort_on_internal_errors &&
188
0
      !strncmp(f, INTERNAL_ERROR, sizeof(INTERNAL_ERROR) - 1))
189
0
    abort();
190
0
}
191
192
__attribute__((format(printf, 5, 6)))
193
static void _default_log_with_errno(int level,
194
      const char *file, int line, int dm_errno_or_class,
195
      const char *f, ...)
196
0
{
197
0
  va_list ap;
198
199
0
  va_start(ap, f);
200
0
  _default_log_line(level, file, line, dm_errno_or_class, f, ap);
201
0
  va_end(ap);
202
0
}
203
204
__attribute__((format(printf, 4, 5)))
205
static void _default_log(int level, const char *file,
206
       int line, const char *f, ...)
207
0
{
208
0
  va_list ap;
209
210
0
  va_start(ap, f);
211
0
  _default_log_line(level, file, line, 0, f, ap);
212
0
  va_end(ap);
213
0
}
214
215
dm_log_fn dm_log = _default_log;
216
dm_log_with_errno_fn dm_log_with_errno = _default_log_with_errno;
217
218
/*
219
 * Wrapper function to reformat new messages to and
220
 * old style logging which had not used errno parameter
221
 *
222
 * As we cannot simply pass '...' to old function we
223
 * need to process arg list locally and just pass '%s' + buffer
224
 */
225
__attribute__((format(printf, 5, 6)))
226
static void _log_to_default_log(int level,
227
      const char *file, int line, int dm_errno_or_class,
228
      const char *f, ...)
229
0
{
230
0
  int n;
231
0
  va_list ap;
232
0
  char buf[2 * PATH_MAX + 256]; /* big enough for most messages */
233
234
0
  va_start(ap, f);
235
0
  n = vsnprintf(buf, sizeof(buf), f, ap);
236
0
  va_end(ap);
237
238
0
  if (n > 0) /* Could be truncated */
239
0
    dm_log(level, file, line, "%s", buf);
240
0
}
241
242
/*
243
 * Wrapper function take 'old' style message without errno
244
 * and log it via new logging function with errno arg
245
 *
246
 * This minor case may happen if new libdm is used with old
247
 * recompiled tool that would decided to use new logging,
248
 * but still would like to use old binary plugins.
249
 */
250
__attribute__((format(printf, 4, 5)))
251
static void _log_to_default_log_with_errno(int level,
252
      const char *file, int line, const char *f, ...)
253
0
{
254
0
  int n;
255
0
  va_list ap;
256
0
  char buf[2 * PATH_MAX + 256]; /* big enough for most messages */
257
258
0
  va_start(ap, f);
259
0
  n = vsnprintf(buf, sizeof(buf), f, ap);
260
0
  va_end(ap);
261
262
0
  if (n > 0) /* Could be truncated */
263
0
    dm_log_with_errno(level, file, line, 0, "%s", buf);
264
0
}
265
266
void dm_log_init(dm_log_fn fn)
267
0
{
268
0
  if (fn ? (dm_log == fn) : !dm_log_is_non_default())
269
0
    return;
270
271
0
  if (!_is_init_thread("set log function"))
272
0
    return;
273
274
0
  if (fn)  {
275
0
    dm_log = fn;
276
0
    dm_log_with_errno = _log_to_default_log;
277
0
  } else {
278
0
    dm_log = _default_log;
279
0
    dm_log_with_errno = _default_log_with_errno;
280
0
  }
281
0
}
282
283
int dm_log_is_non_default(void)
284
0
{
285
0
  return (dm_log == _default_log && dm_log_with_errno == _default_log_with_errno) ? 0 : 1;
286
0
}
287
288
void dm_log_with_errno_init(dm_log_with_errno_fn fn)
289
0
{
290
0
  if (fn ? (dm_log_with_errno == fn) : !dm_log_is_non_default())
291
0
    return;
292
293
0
  if (!_is_init_thread("set log function"))
294
0
    return;
295
296
0
  if (fn) {
297
0
    dm_log = _log_to_default_log_with_errno;
298
0
    dm_log_with_errno = fn;
299
0
  } else {
300
0
    dm_log = _default_log;
301
0
    dm_log_with_errno = _default_log_with_errno;
302
0
  }
303
0
}
304
305
void dm_log_init_verbose(int level)
306
0
{
307
0
  if (_verbose == level)
308
0
    return;
309
310
0
  if (!_is_init_thread("set log verbose level"))
311
0
    return;
312
313
0
  _verbose = level;
314
0
}
315
316
static int _build_dev_path(char *buffer, size_t len, const char *dev_name)
317
0
{
318
0
  int r;
319
320
  /* If there's a /, assume caller knows what they're doing */
321
0
  if (strchr(dev_name, '/'))
322
0
    r = dm_strncpy(buffer, dev_name, len);
323
0
  else
324
0
    r = (dm_snprintf(buffer, len, "%s/%s",
325
0
         _dm_dir, dev_name) < 0) ? 0 : 1;
326
0
  if (!r)
327
0
    log_error("Failed to build dev path for \"%s\".", dev_name);
328
329
0
  return r;
330
0
}
331
332
int dm_get_library_version(char *version, size_t size)
333
0
{
334
0
  return dm_strncpy(version, DM_LIB_VERSION, size);
335
0
}
336
337
void inc_suspended(void)
338
0
{
339
0
  _suspended_dev_counter++;
340
0
  log_debug_activation("Suspended device counter increased to %d", _suspended_dev_counter);
341
0
}
342
343
void dec_suspended(void)
344
0
{
345
0
  if (!_suspended_dev_counter) {
346
0
    log_error("Attempted to decrement suspended device counter below zero.");
347
0
    return;
348
0
  }
349
350
0
  _suspended_dev_counter--;
351
0
  log_debug_activation("Suspended device counter reduced to %d", _suspended_dev_counter);
352
0
}
353
354
int dm_get_suspended_counter(void)
355
0
{
356
0
  return _suspended_dev_counter;
357
0
}
358
359
int dm_set_name_mangling_mode(dm_string_mangling_t name_mangling_mode)
360
0
{
361
0
  if (_name_mangling_mode == name_mangling_mode)
362
0
    return 1;
363
364
0
  if (_is_init_thread("change mangling mode"))
365
0
    _name_mangling_mode = name_mangling_mode;
366
367
0
  return 1;
368
0
}
369
370
dm_string_mangling_t dm_get_name_mangling_mode(void)
371
0
{
372
0
  return _name_mangling_mode;
373
0
}
374
375
struct dm_task *dm_task_create(int type)
376
0
{
377
0
  struct dm_task *dmt = dm_zalloc(sizeof(*dmt));
378
379
0
  if (!dmt) {
380
0
    log_error("dm_task_create: dm_zalloc(%" PRIsize_t ") failed",
381
0
        sizeof(*dmt));
382
0
    return NULL;
383
0
  }
384
385
  /* DM_DEVICE_VERSION is the task that performs the version check itself */
386
0
  if (type != DM_DEVICE_VERSION && !dm_check_version()) {
387
0
    dm_free(dmt);
388
0
    return_NULL;
389
0
  }
390
391
0
  dmt->type = type;
392
0
  dmt->minor = -1;
393
0
  dmt->major = -1;
394
0
  dmt->allow_default_major_fallback = 1;
395
0
  dmt->uid = DM_DEVICE_UID;
396
0
  dmt->gid = DM_DEVICE_GID;
397
0
  dmt->mode = DM_DEVICE_MODE;
398
0
  dmt->no_open_count = 0;
399
0
  dmt->read_ahead = DM_READ_AHEAD_AUTO;
400
0
  dmt->read_ahead_flags = 0;
401
0
  dmt->event_nr = 0;
402
0
  dmt->cookie_set = 0;
403
0
  dmt->query_inactive_table = 0;
404
0
  dmt->new_uuid = 0;
405
0
  dmt->secure_data = 0;
406
0
  dmt->record_timestamp = 0;
407
0
  dmt->ima_measurement = 0;
408
409
0
  return dmt;
410
0
}
411
412
/*
413
 * Find the name associated with a given device number by scanning _dm_dir.
414
 */
415
static int _find_dm_name_of_device(dev_t st_rdev, char *buf, size_t buf_len)
416
0
{
417
0
  const char *name;
418
0
  char path[PATH_MAX];
419
0
  struct dirent *dirent;
420
0
  DIR *d;
421
0
  struct stat st;
422
0
  int r = 0;
423
424
0
  if (!(d = opendir(_dm_dir))) {
425
0
    log_sys_error("opendir", _dm_dir);
426
0
    return 0;
427
0
  }
428
429
0
  while ((dirent = readdir(d))) {
430
0
    name = dirent->d_name;
431
432
0
    if (!strcmp(name, ".") || !strcmp(name, ".."))
433
0
      continue;
434
435
0
    if (dm_snprintf(path, sizeof(path), "%s/%s", _dm_dir,
436
0
        name) == -1) {
437
0
      log_error("Couldn't create path for %s", name);
438
0
      continue;
439
0
    }
440
441
0
    if (stat(path, &st))
442
0
      continue;
443
444
0
    if (st.st_rdev == st_rdev) {
445
0
      dm_strncpy(buf, name, buf_len);
446
0
      r = 1;
447
0
      break;
448
0
    }
449
0
  }
450
451
0
  if (closedir(d))
452
0
    log_sys_debug("closedir", _dm_dir);
453
454
0
  return r;
455
0
}
456
457
static int _is_whitelisted_char(char c)
458
0
{
459
  /*
460
   * Actually, DM supports any character in a device name.
461
   * This whitelist is just for proper integration with udev.
462
   */
463
0
  if ((c >= '0' && c <= '9') ||
464
0
      (c >= 'A' && c <= 'Z') ||
465
0
      (c >= 'a' && c <= 'z') ||
466
0
      strchr("#+-.:=@_", c) != NULL)
467
0
    return 1;
468
469
0
  return 0;
470
0
}
471
472
int check_multiple_mangled_string_allowed(const char *str, const char *str_name,
473
           dm_string_mangling_t mode)
474
0
{
475
0
  if (mode == DM_STRING_MANGLING_AUTO && strstr(str, "\\x5cx")) {
476
0
    log_error("The %s \"%s\" seems to be mangled more than once. "
477
0
        "This is not allowed in auto mode.", str_name, str);
478
0
    return 0;
479
0
  }
480
481
0
  return 1;
482
0
}
483
484
/*
485
 * Mangle all characters in the input string which are not on a whitelist
486
 * with '\xNN' format where NN is the hex value of the character.
487
 */
488
int mangle_string(const char *str, const char *str_name, size_t len,
489
      char *buf, size_t buf_len, dm_string_mangling_t mode)
490
0
{
491
0
  int need_mangling = -1; /* -1 don't know yet, 0 no, 1 yes */
492
0
  size_t i, j;
493
494
0
  if (!str || !buf)
495
0
    return -1;
496
497
  /* Is there anything to do at all? */
498
0
  if (!*str || !len)
499
0
    return 0;
500
501
0
  if (buf_len < DM_NAME_LEN) {
502
0
    log_error(INTERNAL_ERROR "mangle_string: supplied buffer too small");
503
0
    return -1;
504
0
  }
505
506
0
  if (mode == DM_STRING_MANGLING_NONE)
507
0
    mode = DM_STRING_MANGLING_AUTO;
508
509
0
  for (i = 0, j = 0; str[i]; i++) {
510
0
    if (mode == DM_STRING_MANGLING_AUTO) {
511
      /*
512
       * Detect already mangled part of the string and keep it.
513
       * Return error on mixture of mangled/not mangled!
514
       */
515
0
      if (str[i] == '\\' && str[i+1] == 'x') {
516
0
        if ((len - i < 4) || (need_mangling == 1))
517
0
          goto bad1;
518
0
        if (buf_len - j < 4)
519
0
          goto bad2;
520
521
0
        memcpy(&buf[j], &str[i], 4);
522
0
        i+=3; j+=4;
523
524
0
        need_mangling = 0;
525
0
        continue;
526
0
      }
527
0
    }
528
529
0
    if (_is_whitelisted_char(str[i])) {
530
      /* whitelisted, keep it. */
531
0
      if (buf_len - j < 1)
532
0
        goto bad2;
533
0
      buf[j] = str[i];
534
0
      j++;
535
0
    } else {
536
      /*
537
       * Not on a whitelist, mangle it.
538
       * Return error on mixture of mangled/not mangled
539
       * unless a DM_STRING_MANGLING_HEX is used!.
540
       */
541
0
      if ((mode != DM_STRING_MANGLING_HEX) && (need_mangling == 0))
542
0
        goto bad1;
543
0
      if (buf_len - j < 4)
544
0
        goto bad2;
545
546
0
      (void) sprintf(&buf[j], "\\x%02x", (unsigned char) str[i]);
547
0
      j+=4;
548
549
0
      need_mangling = 1;
550
0
    }
551
0
  }
552
553
0
  if (buf_len - j < 1)
554
0
    goto bad2;
555
0
  buf[j] = '\0';
556
557
  /* All chars in the string whitelisted? */
558
0
  if (need_mangling == -1)
559
0
    need_mangling = 0;
560
561
0
  return need_mangling;
562
563
0
bad1:
564
0
  log_error("The %s \"%s\" contains mixed mangled and unmangled "
565
0
      "characters or it's already mangled improperly.", str_name, str);
566
0
  return -1;
567
0
bad2:
568
0
  log_error("Mangled form of the %s too long for \"%s\".", str_name, str);
569
0
  return -1;
570
0
}
571
572
/*
573
 * Try to unmangle supplied string.
574
 * Return value: -1 on error, 0 when no unmangling needed, 1 when unmangling applied
575
 */
576
int unmangle_string(const char *str, const char *str_name, size_t len,
577
        char *buf, size_t buf_len, dm_string_mangling_t mode)
578
0
{
579
0
  int strict = mode != DM_STRING_MANGLING_NONE;
580
0
  char str_rest[DM_NAME_LEN + 1];
581
0
  size_t i, j;
582
0
  unsigned int code;
583
0
  int r = 0;
584
585
0
  if (!str || !buf)
586
0
    return -1;
587
588
  /* Is there anything to do at all? */
589
0
  if (!*str || !len)
590
0
    return 0;
591
592
0
  if (buf_len < DM_NAME_LEN) {
593
0
    log_error(INTERNAL_ERROR "unmangle_string: supplied buffer too small");
594
0
    return -1;
595
0
  }
596
597
0
  for (i = 0, j = 0; str[i]; i++, j++) {
598
0
    if (strict && !(_is_whitelisted_char(str[i]) || str[i]=='\\')) {
599
0
      log_error("The %s \"%s\" should be mangled but "
600
0
          "it contains blacklisted characters.", str_name, str);
601
0
      j=0; r=-1;
602
0
      goto out;
603
0
    }
604
605
0
    if (str[i] == '\\' && str[i+1] == 'x') {
606
0
      if ((len - i < 4) ||
607
0
          !sscanf(&str[i+2], "%2x%" DM_TO_STRING(DM_NAME_LEN) "s",
608
0
            &code, str_rest)) {
609
0
        log_debug_activation("Hex encoding mismatch detected in %s \"%s\" "
610
0
                 "while trying to unmangle it.", str_name, str);
611
0
        goto out;
612
0
      }
613
0
      buf[j] = (unsigned char) code;
614
615
      /* skip the encoded part we've just decoded! */
616
0
      i+= 3;
617
618
      /* unmangling applied */
619
0
      r = 1;
620
0
    } else
621
0
      buf[j] = str[i];
622
0
  }
623
624
0
out:
625
0
  buf[j] = '\0';
626
0
  return r;
627
0
}
628
629
static int _dm_task_set_name(struct dm_task *dmt, const char *name,
630
           dm_string_mangling_t mangling_mode)
631
0
{
632
0
  char mangled_name[DM_NAME_LEN];
633
0
  int r = 0;
634
635
0
  dm_free(dmt->dev_name);
636
0
  dmt->dev_name = NULL;
637
0
  dm_free(dmt->mangled_dev_name);
638
0
  dmt->mangled_dev_name = NULL;
639
640
0
  if (strlen(name) >= DM_NAME_LEN) {
641
0
    log_error("Name \"%s\" too long.", name);
642
0
    return 0;
643
0
  }
644
645
0
  if (!check_multiple_mangled_string_allowed(name, "name", mangling_mode))
646
0
    return_0;
647
648
0
  if (mangling_mode != DM_STRING_MANGLING_NONE &&
649
0
      (r = mangle_string(name, "name", strlen(name), mangled_name,
650
0
             sizeof(mangled_name), mangling_mode)) < 0) {
651
0
    log_error("Failed to mangle device name \"%s\".", name);
652
0
    return 0;
653
0
  }
654
655
  /* Store mangled_dev_name only if it differs from dev_name! */
656
0
  if (r) {
657
0
    log_debug_activation("Device name mangled [%s]: %s --> %s",
658
0
             mangling_mode == DM_STRING_MANGLING_AUTO ? "auto" : "hex",
659
0
             name, mangled_name);
660
0
    if (!(dmt->mangled_dev_name = dm_strdup(mangled_name))) {
661
0
      log_error("_dm_task_set_name: dm_strdup(%s) failed", mangled_name);
662
0
      return 0;
663
0
    }
664
0
  }
665
666
0
  if (!(dmt->dev_name = dm_strdup(name))) {
667
0
    log_error("_dm_task_set_name: dm_strdup(%s) failed", name);
668
0
    return 0;
669
0
  }
670
671
0
  return 1;
672
0
}
673
674
static int _dm_task_set_name_from_path(struct dm_task *dmt, const char *path,
675
               const char *name)
676
0
{
677
0
  char buf[PATH_MAX];
678
0
  struct stat st1, st2;
679
0
  const char *final_name = NULL;
680
0
  size_t len;
681
682
0
  if (dmt->type == DM_DEVICE_CREATE) {
683
0
    log_error("Name \"%s\" invalid. It contains \"/\".", path);
684
0
    return 0;
685
0
  }
686
687
0
  if (!stat(path, &st1)) {
688
    /*
689
     * Found directly.
690
     * If supplied path points to same device as last component
691
     * under /dev/mapper, use that name directly.
692
     */
693
0
    if (dm_snprintf(buf, sizeof(buf), "%s/%s", _dm_dir, name) == -1) {
694
0
      log_error("Couldn't create path for %s", name);
695
0
      return 0;
696
0
    }
697
698
0
    if (!stat(buf, &st2) && (st1.st_rdev == st2.st_rdev))
699
0
      final_name = name;
700
0
  } else {
701
    /* Not found. */
702
    /* If there is exactly one '/' try a prefix of /dev */
703
0
    if ((len = strlen(path)) < 3 || path[0] == '/' ||
704
0
        dm_count_chars(path, len, '/') != 1) {
705
0
      log_error("Device %s not found", path);
706
0
      return 0;
707
0
    }
708
0
    if (dm_snprintf(buf, sizeof(buf), "%s/../%s", _dm_dir, path) == -1) {
709
0
      log_error("Couldn't create /dev path for %s", path);
710
0
      return 0;
711
0
    }
712
0
    if (stat(buf, &st1)) {
713
0
      log_error("Device %s not found", path);
714
0
      return 0;
715
0
    }
716
    /* Found */
717
0
  }
718
719
  /*
720
   * If we don't have the dm name yet, Call _find_dm_name_of_device() to
721
   * scan _dm_dir for a match.
722
   */
723
0
  if (!final_name) {
724
0
    if (_find_dm_name_of_device(st1.st_rdev, buf, sizeof(buf)))
725
0
      final_name = buf;
726
0
    else {
727
0
      log_error("Device %s not found", name);
728
0
      return 0;
729
0
    }
730
0
  }
731
732
  /* This is an already existing path - do not mangle! */
733
0
  return _dm_task_set_name(dmt, final_name, DM_STRING_MANGLING_NONE);
734
0
}
735
736
int dm_task_set_name(struct dm_task *dmt, const char *name)
737
0
{
738
0
  const char *pos;
739
740
  /* Path supplied for existing device? */
741
0
  if ((pos = strrchr(name, '/')))
742
0
    return _dm_task_set_name_from_path(dmt, name, pos + 1);
743
744
0
  return _dm_task_set_name(dmt, name, dm_get_name_mangling_mode());
745
0
}
746
747
const char *dm_task_get_name(const struct dm_task *dmt)
748
0
{
749
0
  return (dmt->dmi.v4->name);
750
0
}
751
752
static char *_task_get_string_mangled(const char *str, const char *str_name,
753
              char *buf, size_t buf_size,
754
              dm_string_mangling_t mode)
755
0
{
756
0
  char *rs;
757
0
  int r;
758
759
0
  if ((r = mangle_string(str, str_name, strlen(str), buf, buf_size, mode)) < 0)
760
0
    return NULL;
761
762
0
  if (!(rs = r ? dm_strdup(buf) : dm_strdup(str)))
763
0
    log_error("_task_get_string_mangled: dm_strdup failed");
764
765
0
  return rs;
766
0
}
767
768
static char *_task_get_string_unmangled(const char *str, const char *str_name,
769
          char *buf, size_t buf_size,
770
          dm_string_mangling_t mode)
771
0
{
772
0
  char *rs;
773
0
  int r = 0;
774
775
  /*
776
   * Unless the mode used is 'none', the string
777
   * is *already* unmangled on ioctl return!
778
   */
779
0
  if (mode == DM_STRING_MANGLING_NONE &&
780
0
      (r = unmangle_string(str, str_name, strlen(str), buf, buf_size, mode)) < 0)
781
0
    return NULL;
782
783
0
  if (!(rs = r ? dm_strdup(buf) : dm_strdup(str)))
784
0
    log_error("_task_get_string_unmangled: dm_strdup failed");
785
786
0
  return rs;
787
0
}
788
789
char *dm_task_get_name_mangled(const struct dm_task *dmt)
790
0
{
791
0
  const char *s = dm_task_get_name(dmt);
792
0
  char buf[DM_NAME_LEN];
793
0
  char *rs;
794
795
0
  if (!(rs = _task_get_string_mangled(s, "name", buf, sizeof(buf), dm_get_name_mangling_mode())))
796
0
    log_error("Failed to mangle device name \"%s\".", s);
797
798
0
  return rs;
799
0
}
800
801
char *dm_task_get_name_unmangled(const struct dm_task *dmt)
802
0
{
803
0
  const char *s = dm_task_get_name(dmt);
804
0
  char buf[DM_NAME_LEN];
805
0
  char *rs;
806
807
0
  if (!(rs = _task_get_string_unmangled(s, "name", buf, sizeof(buf), dm_get_name_mangling_mode())))
808
0
    log_error("Failed to unmangle device name \"%s\".", s);
809
810
0
  return rs;
811
0
}
812
813
const char *dm_task_get_uuid(const struct dm_task *dmt)
814
0
{
815
0
  return (dmt->dmi.v4->uuid);
816
0
}
817
818
char *dm_task_get_uuid_mangled(const struct dm_task *dmt)
819
0
{
820
0
  const char *s = dm_task_get_uuid(dmt);
821
0
  char buf[DM_UUID_LEN];
822
0
  char *rs;
823
824
0
  if (!(rs = _task_get_string_mangled(s, "UUID", buf, sizeof(buf), dm_get_name_mangling_mode())))
825
0
    log_error("Failed to mangle device uuid \"%s\".", s);
826
827
0
  return rs;
828
0
}
829
830
char *dm_task_get_uuid_unmangled(const struct dm_task *dmt)
831
0
{
832
0
  const char *s = dm_task_get_uuid(dmt);
833
0
  char buf[DM_UUID_LEN];
834
0
  char *rs;
835
836
0
  if (!(rs = _task_get_string_unmangled(s, "UUID", buf, sizeof(buf), dm_get_name_mangling_mode())))
837
0
    log_error("Failed to unmangle device uuid \"%s\".", s);
838
839
0
  return rs;
840
0
}
841
842
int dm_task_set_newname(struct dm_task *dmt, const char *newname)
843
0
{
844
0
  dm_string_mangling_t mangling_mode = dm_get_name_mangling_mode();
845
0
  char mangled_name[DM_NAME_LEN];
846
0
  int r = 0;
847
848
0
  if (strchr(newname, '/')) {
849
0
    log_error("Name \"%s\" invalid. It contains \"/\".", newname);
850
0
    return 0;
851
0
  }
852
853
0
  if (strlen(newname) >= DM_NAME_LEN) {
854
0
    log_error("Name \"%s\" too long", newname);
855
0
    return 0;
856
0
  }
857
858
0
  if (!*newname) {
859
0
    log_error("Non empty new name is required.");
860
0
    return 0;
861
0
  }
862
863
0
  if (!check_multiple_mangled_string_allowed(newname, "new name", mangling_mode))
864
0
    return_0;
865
866
0
  if (mangling_mode != DM_STRING_MANGLING_NONE &&
867
0
      (r = mangle_string(newname, "new name", strlen(newname), mangled_name,
868
0
             sizeof(mangled_name), mangling_mode)) < 0) {
869
0
    log_error("Failed to mangle new device name \"%s\"", newname);
870
0
    return 0;
871
0
  }
872
873
0
  if (r) {
874
0
    log_debug_activation("New device name mangled [%s]: %s --> %s",
875
0
             mangling_mode == DM_STRING_MANGLING_AUTO ? "auto" : "hex",
876
0
             newname, mangled_name);
877
0
    newname = mangled_name;
878
0
  }
879
880
0
  dm_free(dmt->newname);
881
0
  if (!(dmt->newname = dm_strdup(newname))) {
882
0
    log_error("dm_task_set_newname: dm_strdup(%s) failed", newname);
883
0
    return 0;
884
0
  }
885
886
0
  dmt->new_uuid = 0;
887
888
0
  return 1;
889
0
}
890
891
int dm_task_set_uuid(struct dm_task *dmt, const char *uuid)
892
0
{
893
0
  char mangled_uuid[DM_UUID_LEN];
894
0
  dm_string_mangling_t mangling_mode = dm_get_name_mangling_mode();
895
0
  int r = 0;
896
897
0
  dm_free(dmt->uuid);
898
0
  dmt->uuid = NULL;
899
0
  dm_free(dmt->mangled_uuid);
900
0
  dmt->mangled_uuid = NULL;
901
902
0
  if (!check_multiple_mangled_string_allowed(uuid, "UUID", mangling_mode))
903
0
    return_0;
904
905
0
  if (mangling_mode != DM_STRING_MANGLING_NONE &&
906
0
      (r = mangle_string(uuid, "UUID", strlen(uuid), mangled_uuid,
907
0
             sizeof(mangled_uuid), mangling_mode)) < 0) {
908
0
    log_error("Failed to mangle device uuid \"%s\".", uuid);
909
0
    return 0;
910
0
  }
911
912
0
  if (r) {
913
0
    log_debug_activation("Device uuid mangled [%s]: %s --> %s",
914
0
             mangling_mode == DM_STRING_MANGLING_AUTO ? "auto" : "hex",
915
0
             uuid, mangled_uuid);
916
917
0
    if (!(dmt->mangled_uuid = dm_strdup(mangled_uuid))) {
918
0
      log_error("dm_task_set_uuid: dm_strdup(%s) failed", mangled_uuid);
919
0
      return 0;
920
0
    }
921
0
  }
922
923
0
  if (!(dmt->uuid = dm_strdup(uuid))) {
924
0
    log_error("dm_task_set_uuid: dm_strdup(%s) failed", uuid);
925
0
    return 0;
926
0
  }
927
928
0
  return 1;
929
0
}
930
931
int dm_task_set_major(struct dm_task *dmt, int major)
932
0
{
933
0
  dmt->major = major;
934
0
  dmt->allow_default_major_fallback = 0;
935
936
0
  return 1;
937
0
}
938
939
int dm_task_set_minor(struct dm_task *dmt, int minor)
940
0
{
941
0
  dmt->minor = minor;
942
943
0
  return 1;
944
0
}
945
946
int dm_task_set_major_minor(struct dm_task *dmt, int major, int minor,
947
          int allow_default_major_fallback)
948
0
{
949
0
  dmt->major = major;
950
0
  dmt->minor = minor;
951
0
  dmt->allow_default_major_fallback = allow_default_major_fallback;
952
953
0
  return 1;
954
0
}
955
956
int dm_task_set_uid(struct dm_task *dmt, uid_t uid)
957
0
{
958
0
  dmt->uid = uid;
959
960
0
  return 1;
961
0
}
962
963
int dm_task_set_gid(struct dm_task *dmt, gid_t gid)
964
0
{
965
0
  dmt->gid = gid;
966
967
0
  return 1;
968
0
}
969
970
int dm_task_set_mode(struct dm_task *dmt, mode_t mode)
971
0
{
972
0
  dmt->mode = mode;
973
974
0
  return 1;
975
0
}
976
977
int dm_task_enable_checks(struct dm_task *dmt)
978
0
{
979
0
  dmt->enable_checks = 1;
980
981
0
  return 1;
982
0
}
983
984
int dm_task_add_target(struct dm_task *dmt, uint64_t start, uint64_t size,
985
           const char *ttype, const char *params)
986
0
{
987
0
  struct target *t = create_target(start, size, ttype, params);
988
0
  if (!t)
989
0
    return_0;
990
991
0
  if (!dmt->head)
992
0
    dmt->head = dmt->tail = t;
993
0
  else {
994
0
    dmt->tail->next = t;
995
0
    dmt->tail = t;
996
0
  }
997
998
0
  return 1;
999
0
}
1000
1001
#ifdef HAVE_SELINUX
1002
static int _selabel_lookup(const char *path, mode_t mode,
1003
         char **scontext)
1004
{
1005
#ifdef HAVE_SELINUX_LABEL_H
1006
  if (!_get_selabel_handle()) {
1007
    log_error("selabel_open failed: %s", strerror(errno));
1008
    return 0;
1009
  }
1010
1011
  if (selabel_lookup(_get_selabel_handle(), scontext, path, mode)) {
1012
    log_debug_activation("selabel_lookup failed for %s: %s",
1013
             path, strerror(errno));
1014
    return 0;
1015
  }
1016
#else
1017
  if (matchpathcon(path, mode, scontext)) {
1018
    log_debug_activation("matchpathcon failed for %s: %s",
1019
             path, strerror(errno));
1020
    return 0;
1021
  }
1022
#endif
1023
  return 1;
1024
}
1025
#endif
1026
1027
#ifdef HAVE_SELINUX
1028
static int _selinux_enabled;
1029
static pthread_once_t _selinux_enabled_once = PTHREAD_ONCE_INIT;
1030
1031
static void _init_selinux_enabled(void)
1032
{
1033
  _selinux_enabled = is_selinux_enabled();
1034
}
1035
1036
static int _is_selinux_enabled(void)
1037
{
1038
  pthread_once(&_selinux_enabled_once, _init_selinux_enabled);
1039
1040
  return _selinux_enabled;
1041
}
1042
#endif
1043
1044
int dm_prepare_selinux_context(const char *path, mode_t mode)
1045
0
{
1046
#ifdef HAVE_SELINUX
1047
  char *scontext = NULL;
1048
1049
  if (_is_selinux_enabled() <= 0)
1050
    return 1;
1051
1052
  if (path) {
1053
    if (!_selabel_lookup(path, mode, &scontext))
1054
      return_0;
1055
1056
    log_debug_activation("Preparing SELinux context for %s to %s.", path, scontext);
1057
  }
1058
  else
1059
    log_debug_activation("Resetting SELinux context to default value.");
1060
1061
  if (setfscreatecon(scontext) < 0) {
1062
    log_sys_error("setfscreatecon", (path ? : "SELinux context reset"));
1063
    freecon(scontext);
1064
    return 0;
1065
  }
1066
1067
  freecon(scontext);
1068
#endif
1069
0
  return 1;
1070
0
}
1071
1072
int dm_set_selinux_context(const char *path, mode_t mode)
1073
0
{
1074
#ifdef HAVE_SELINUX
1075
  char *scontext = NULL;
1076
1077
  if (_is_selinux_enabled() <= 0)
1078
    return 1;
1079
1080
  if (!_selabel_lookup(path, mode, &scontext))
1081
    return_0;
1082
1083
  log_debug_activation("Setting SELinux context for %s to %s.", path, scontext);
1084
1085
  if ((lsetfilecon(path, scontext) < 0) && (errno != ENOTSUP)) {
1086
    log_sys_error("lsetfilecon", path);
1087
    freecon(scontext);
1088
    return 0;
1089
  }
1090
1091
  freecon(scontext);
1092
#endif
1093
0
  return 1;
1094
0
}
1095
1096
void selinux_release(void)
1097
0
{
1098
#ifdef HAVE_SELINUX_LABEL_H
1099
  if (_selabel_handle)
1100
    selabel_close(_selabel_handle);
1101
  _selabel_handle = NULL;
1102
#endif
1103
0
}
1104
1105
static int _warn_if_op_needed(int warn_if_udev_failed)
1106
0
{
1107
0
  return warn_if_udev_failed && dm_udev_get_sync_support() && dm_udev_get_checking();
1108
0
}
1109
1110
static int _add_dev_node(const char *dev_name, uint32_t major, uint32_t minor,
1111
       uid_t uid, gid_t gid, mode_t mode, int warn_if_udev_failed)
1112
0
{
1113
0
  char path[PATH_MAX];
1114
0
  struct stat info;
1115
0
  struct stat linfo;
1116
0
  dev_t dev = MKDEV(major, minor);
1117
0
  mode_t old_mask;
1118
1119
0
  if (!_build_dev_path(path, sizeof(path), dev_name))
1120
0
    return_0;
1121
1122
  /*
1123
   * Check if the device node already exists.
1124
   * Note: stat() follows symlinks, so this checks the target device,
1125
   * not the symlink itself. This works correctly for both real nodes
1126
   * and symlinks pointing to the right device.
1127
   */
1128
0
  if (stat(path, &info) >= 0) {
1129
0
    if (!S_ISBLK(info.st_mode)) {
1130
0
      log_error("A non-block device file at '%s' "
1131
0
          "is already present", path);
1132
0
      return 0;
1133
0
    }
1134
1135
    /* If right inode already exists we don't touch uid etc. */
1136
0
    if (info.st_rdev == dev) {
1137
      /*
1138
       * Correct device exists (either as real node or symlink).
1139
       * Use lstat() to distinguish between them for logging.
1140
       */
1141
0
      if (lstat(path, &linfo) >= 0 && S_ISLNK(linfo.st_mode))
1142
0
        log_debug_activation("Symlink %s to correct device already exists", path);
1143
0
      return 1;
1144
0
    }
1145
1146
    /* Wrong device exists, remove it before creating correct one */
1147
    /* coverity[toctou] stat check is for validation; ENOENT is handled */
1148
0
    if (unlink(path) && (errno != ENOENT)) {
1149
0
      log_sys_error("unlink", path);
1150
0
      return 0;
1151
0
    }
1152
0
  } else {
1153
    /*
1154
     * stat() failed. Check for dangling symlinks (where lstat succeeds
1155
     * but stat fails with ENOENT because the symlink target doesn't exist).
1156
     * Remove the dangling symlink before attempting to create a new node.
1157
     */
1158
0
    if (errno == ENOENT && lstat(path, &linfo) >= 0 && S_ISLNK(linfo.st_mode)) {
1159
0
      log_debug_activation("Removing dangling symlink %s", path);
1160
      /* coverity[toctou] lstat check is only for logging; ENOENT is handled */
1161
0
      if (unlink(path) && (errno != ENOENT)) {
1162
0
        log_sys_error("unlink", path);
1163
0
        return 0;
1164
0
      }
1165
0
    }
1166
0
    if (_warn_if_op_needed(warn_if_udev_failed))
1167
0
      log_warn("%s not set up by udev: Falling back to direct "
1168
0
         "node creation.", path);
1169
0
  }
1170
1171
  /*
1172
   * Test environment optimization: If using alternative dev dir (e.g., /tmp/LVMTEST/dev)
1173
   * and the real /dev node already exists, create a symlink instead of a duplicate node.
1174
   * This ensures operations trigger udev events which only monitors /dev.
1175
   * Requires cookie support (DM >= 4.15) for udev sync; on older kernels
1176
   * udev may transiently delete /dev/dm-N nodes, breaking the symlinks.
1177
   */
1178
0
  if (dm_cookie_supported() && strcmp(_dm_dir, DEV_DIR) != 0) {
1179
0
    char real_path[PATH_MAX];
1180
0
    struct stat real_stat;
1181
1182
    /* Build path to real /dev node (kernel always creates /dev/dm-N) */
1183
0
    if (dm_snprintf(real_path, sizeof(real_path), DEV_DIR "dm-%u", minor) >= 0) {
1184
      /* Check if real node exists with matching dev */
1185
0
      if (stat(real_path, &real_stat) >= 0 &&
1186
0
          S_ISBLK(real_stat.st_mode) &&
1187
0
          real_stat.st_rdev == dev) {
1188
        /*
1189
         * Real /dev/dm-N exists. Create symlink from alternative location.
1190
         * This allows operations to work through the symlink and trigger
1191
         * udev events on the real device.
1192
         */
1193
0
        log_debug_activation("Creating symlink %s -> %s", path, real_path);
1194
0
        (void) dm_prepare_selinux_context(path, S_IFLNK);
1195
0
        if (symlink(real_path, path) < 0) {
1196
0
          log_sys_error("symlink", path);
1197
0
          (void) dm_prepare_selinux_context(NULL, 0);
1198
0
          return 0;
1199
0
        }
1200
0
        (void) dm_prepare_selinux_context(NULL, 0);
1201
0
        log_debug_activation("Created symlink %s -> %s", path, real_path);
1202
0
        return 1;
1203
0
      }
1204
0
    }
1205
0
  }
1206
1207
0
  (void) dm_prepare_selinux_context(path, S_IFBLK);
1208
0
  old_mask = umask(0);
1209
1210
  /* The node may already have been created by udev. So ignore EEXIST. */
1211
  /* coverity[toctou] previous checks are for cleanup/optimization; EEXIST is handled */
1212
0
  if (mknod(path, S_IFBLK | mode, dev) < 0 && errno != EEXIST) {
1213
0
    log_error("%s: mknod for %s failed: %s", path, dev_name, strerror(errno));
1214
0
    umask(old_mask);
1215
0
    (void) dm_prepare_selinux_context(NULL, 0);
1216
0
    return 0;
1217
0
  }
1218
0
  umask(old_mask);
1219
0
  (void) dm_prepare_selinux_context(NULL, 0);
1220
1221
0
  if (chown(path, uid, gid) < 0) {
1222
0
    log_sys_error("chown", path);
1223
0
    return 0;
1224
0
  }
1225
1226
0
  log_debug_activation("Created %s", path);
1227
1228
0
  return 1;
1229
0
}
1230
1231
static int _rm_dev_node(const char *dev_name, int warn_if_udev_failed)
1232
0
{
1233
0
  char path[PATH_MAX];
1234
0
  struct stat info;
1235
1236
0
  if (!_build_dev_path(path, sizeof(path), dev_name))
1237
0
    return_0;
1238
0
  if (lstat(path, &info) < 0)
1239
0
    return 1;
1240
0
  else if (_warn_if_op_needed(warn_if_udev_failed))
1241
0
    log_warn("Node %s was not removed by udev. "
1242
0
       "Falling back to direct node removal.", path);
1243
1244
  /* udev may already have deleted the node. Ignore ENOENT. */
1245
  /* coverity[toctou] lstat is only for the warning; ENOENT is handled */
1246
0
  if (unlink(path) && (errno != ENOENT)) {
1247
0
    log_sys_error("unlink", path);
1248
0
    return 0;
1249
0
  }
1250
1251
0
  log_debug_activation("Removed %s", path);
1252
1253
0
  return 1;
1254
0
}
1255
1256
static int _rename_dev_node(const char *old_name, const char *new_name,
1257
          int warn_if_udev_failed)
1258
0
{
1259
0
  char oldpath[PATH_MAX];
1260
0
  char newpath[PATH_MAX];
1261
0
  struct stat info, info2;
1262
0
  struct stat *info_block_dev;
1263
1264
0
  if (!_build_dev_path(oldpath, sizeof(oldpath), old_name) ||
1265
0
      !_build_dev_path(newpath, sizeof(newpath), new_name))
1266
0
    return_0;
1267
1268
0
  if (lstat(newpath, &info) == 0) {
1269
0
    if (S_ISLNK(info.st_mode)) {
1270
0
      if (stat(newpath, &info2) == 0)
1271
0
        info_block_dev = &info2;
1272
0
      else {
1273
0
        log_sys_error("stat", newpath);
1274
0
        return 0;
1275
0
      }
1276
0
    } else
1277
0
      info_block_dev = &info;
1278
1279
0
    if (!S_ISBLK(info_block_dev->st_mode)) {
1280
0
      log_error("A non-block device file at '%s' "
1281
0
          "is already present", newpath);
1282
0
      return 0;
1283
0
    }
1284
0
    else if (_warn_if_op_needed(warn_if_udev_failed)) {
1285
0
      if (lstat(oldpath, &info) < 0 &&
1286
0
         errno == ENOENT)
1287
        /* assume udev already deleted this */
1288
0
        return 1;
1289
1290
0
      log_warn("The node %s should have been renamed to %s "
1291
0
         "by udev but old node is still present. "
1292
0
         "Falling back to direct old node removal.",
1293
0
         oldpath, newpath);
1294
0
      return _rm_dev_node(old_name, 0);
1295
0
    }
1296
1297
    /* Remove existing node at target path before rename */
1298
    /* coverity[toctou] stat/lstat checks are for validation; errors are handled */
1299
0
    if (unlink(newpath) < 0) {
1300
0
      if (errno == EPERM) {
1301
        /* devfs, entry has already been renamed */
1302
0
        return 1;
1303
0
      }
1304
0
      log_error("Unable to unlink device node for '%s'",
1305
0
          new_name);
1306
0
      return 0;
1307
0
    }
1308
0
  }
1309
0
  else if (_warn_if_op_needed(warn_if_udev_failed))
1310
0
    log_warn("The node %s should have been renamed to %s "
1311
0
       "by udev but new node is not present. "
1312
0
       "Falling back to direct node rename.",
1313
0
       oldpath, newpath);
1314
1315
  /* udev may already have renamed the node. Ignore ENOENT. */
1316
  /* FIXME: when renaming to target mangling mode "none" with udev
1317
   * while there are some blacklisted characters in the node name,
1318
   * udev will remove the old_node, but fails to properly rename
1319
   * to new_node. The libdevmapper code tries to call
1320
   * rename(old_node,new_node), but that won't do anything
1321
   * since the old node is already removed by udev.
1322
   * For example renaming 'a\x20b' to 'a b':
1323
   *   - udev removes 'a\x20b'
1324
   *   - udev creates 'a' and 'b' (since it considers the ' ' as a delimiter
1325
   *   - libdevmapper checks udev has done the rename properly
1326
   *   - libdevmapper calls stat(new_node) and it does not see it
1327
   *   - libdevmapper calls rename(old_node,new_node)
1328
   *   - the rename is a NOP since the old_node does not exist anymore
1329
   *
1330
   * However, this situation is very rare - why would anyone need
1331
   * to rename to an unsupported mode??? So a fix for this would be
1332
   * just for completeness.
1333
   */
1334
0
  if (rename(oldpath, newpath) < 0 && errno != ENOENT) {
1335
0
    log_error("Unable to rename device node from '%s' to '%s'",
1336
0
        old_name, new_name);
1337
0
    return 0;
1338
0
  }
1339
1340
0
  log_debug_activation("Renamed %s to %s", oldpath, newpath);
1341
1342
0
  return 1;
1343
0
}
1344
1345
#ifdef __linux__
1346
static int _open_dev_node(const char *dev_name)
1347
0
{
1348
0
  int fd = -1;
1349
0
  char path[PATH_MAX];
1350
1351
0
  if (!_build_dev_path(path, sizeof(path), dev_name))
1352
0
    return fd;
1353
1354
0
  if ((fd = open(path, O_RDONLY, 0)) < 0)
1355
0
    log_sys_error("open", path);
1356
1357
0
  return fd;
1358
0
}
1359
1360
int get_dev_node_read_ahead(const char *dev_name, uint32_t major, uint32_t minor,
1361
          uint32_t *read_ahead)
1362
0
{
1363
0
  char path0[PATH_MAX];
1364
0
  char buf[24];
1365
0
  int len;
1366
0
  int r = 1;
1367
0
  int fd;
1368
0
  long read_ahead_long = 0;
1369
1370
  /*
1371
   * If we know the device number, use sysfs if we can.
1372
   * Otherwise use BLKRAGET ioctl.
1373
   */
1374
0
  if (*_sysfs_dir && major != 0) {
1375
0
    if (dm_snprintf(path0, sizeof(path0), "%sdev/block/%" PRIu32
1376
0
        ":%" PRIu32 "/bdi/read_ahead_kb", _sysfs_dir,
1377
0
        major, minor) < 0) {
1378
0
      log_error("Failed to build sysfs_path.");
1379
0
      return 0;
1380
0
    }
1381
1382
0
    if ((fd = open(path0, O_RDONLY, 0)) != -1) {
1383
      /* Reading from sysfs, expecting number\n */
1384
0
      if ((len = read(fd, buf, sizeof(buf) - 1)) < 1) {
1385
0
        log_sys_error("read", path0);
1386
0
        r = 0;
1387
0
      } else {
1388
0
        buf[len] = 0; /* kill \n and ensure \0 */
1389
0
        *read_ahead = atoi(buf) * 2;
1390
0
        log_debug_activation("%s (%u:%u): read ahead is %u.",
1391
0
                 dev_name, major, minor, *read_ahead);
1392
0
      }
1393
1394
0
      if (close(fd))
1395
0
        log_sys_debug("close", path0);
1396
1397
0
      return r;
1398
0
    }
1399
1400
0
    log_sys_debug("open", path0);
1401
    /* Fall back to use dev_name */
1402
0
  }
1403
1404
  /*
1405
   * Open/close dev_name may block the process
1406
   * (i.e. overfilled thin pool volume)
1407
   */
1408
0
  if (!*dev_name) {
1409
0
    log_error("Empty device name passed to BLKRAGET");
1410
0
    return 0;
1411
0
  }
1412
1413
0
  if ((fd = _open_dev_node(dev_name)) < 0)
1414
0
    return_0;
1415
1416
0
  if (ioctl(fd, BLKRAGET, &read_ahead_long)) {
1417
0
    log_sys_error("BLKRAGET", dev_name);
1418
0
    *read_ahead = 0;
1419
0
    r = 0;
1420
0
  } else {
1421
0
    *read_ahead = (uint32_t) read_ahead_long;
1422
0
    log_debug_activation("%s: read ahead is %" PRIu32, dev_name, *read_ahead);
1423
0
  }
1424
1425
0
  if (close(fd))
1426
0
    log_sys_debug("close", dev_name);
1427
1428
0
  return r;
1429
0
}
1430
1431
static int _set_read_ahead(const char *dev_name, uint32_t major, uint32_t minor,
1432
         uint32_t read_ahead)
1433
0
{
1434
0
  char path0[PATH_MAX];
1435
0
  char buf[24];
1436
0
  int len;
1437
0
  int r = 1;
1438
0
  int fd;
1439
0
  long read_ahead_long = (long) read_ahead;
1440
1441
0
  log_debug_activation("%s (%u:%u): Setting read ahead to %u.",
1442
0
           dev_name, major, minor, read_ahead);
1443
1444
  /*
1445
   * If we know the device number, use sysfs if we can.
1446
   * Otherwise use BLKRASET ioctl. RA is set after resume.
1447
   */
1448
0
  if (*_sysfs_dir && major != 0) {
1449
0
    if (dm_snprintf(path0, sizeof(path0), "%sdev/block/%" PRIu32
1450
0
        ":%" PRIu32 "/bdi/read_ahead_kb",
1451
0
        _sysfs_dir, major, minor) < 0) {
1452
0
      log_error("Failed to build sysfs_path.");
1453
0
      return 0;
1454
0
    }
1455
1456
    /* Sysfs is kB based, round up to kB */
1457
0
    if ((len = dm_snprintf(buf, sizeof(buf), FMTu32,
1458
0
               (read_ahead + 1) / 2)) < 0) {
1459
0
      log_error("Failed to build size in kB.");
1460
0
      return 0;
1461
0
    }
1462
1463
0
    if ((fd = open(path0, O_WRONLY, 0)) != -1) {
1464
0
      if (write(fd, buf, len) < len) {
1465
0
        log_sys_error("write", path0);
1466
0
        r = 0;
1467
0
      }
1468
1469
0
      if (close(fd))
1470
0
        log_sys_debug("close", path0);
1471
1472
0
      return r;
1473
0
    }
1474
1475
0
    log_sys_debug("open", path0);
1476
    /* Fall back to use dev_name */
1477
0
  }
1478
1479
0
  if (!*dev_name) {
1480
0
    log_error("Empty device name passed to BLKRASET.");
1481
0
    return 0;
1482
0
  }
1483
1484
0
  if ((fd = _open_dev_node(dev_name)) < 0)
1485
0
    return_0;
1486
1487
0
  if (ioctl(fd, BLKRASET, read_ahead_long)) {
1488
0
    log_sys_error("BLKRASET", dev_name);
1489
0
    r = 0;
1490
0
  }
1491
1492
0
  if (close(fd))
1493
0
    log_sys_debug("close", dev_name);
1494
1495
0
  return r;
1496
0
}
1497
1498
static int _set_dev_node_read_ahead(const char *dev_name,
1499
            uint32_t major, uint32_t minor,
1500
            uint32_t read_ahead, uint32_t read_ahead_flags)
1501
0
{
1502
0
  uint32_t current_read_ahead;
1503
1504
0
  if (read_ahead == DM_READ_AHEAD_AUTO)
1505
0
    return 1;
1506
1507
0
  if (read_ahead == DM_READ_AHEAD_NONE)
1508
0
    read_ahead = 0;
1509
1510
0
  if (read_ahead_flags & DM_READ_AHEAD_MINIMUM_FLAG) {
1511
0
    if (!get_dev_node_read_ahead(dev_name, major, minor, &current_read_ahead))
1512
0
      return_0;
1513
1514
0
    if (current_read_ahead >= read_ahead) {
1515
0
      log_debug_activation("%s: retaining kernel read ahead of %" PRIu32
1516
0
          " (requested %" PRIu32 ")",
1517
0
          dev_name, current_read_ahead, read_ahead);
1518
0
      return 1;
1519
0
    }
1520
0
  }
1521
1522
0
  return _set_read_ahead(dev_name, major, minor, read_ahead);
1523
0
}
1524
1525
#else
1526
1527
int get_dev_node_read_ahead(const char *dev_name, uint32_t major, uint32_t minor,
1528
          uint32_t *read_ahead)
1529
{
1530
  *read_ahead = 0;
1531
1532
  return 1;
1533
}
1534
1535
static int _set_dev_node_read_ahead(const char *dev_name,
1536
            uint32_t major, uint32_t minor,
1537
            uint32_t read_ahead, uint32_t read_ahead_flags)
1538
{
1539
  return 1;
1540
}
1541
#endif
1542
1543
typedef enum {
1544
  NODE_ADD,
1545
  NODE_DEL,
1546
  NODE_RENAME,
1547
  NODE_READ_AHEAD,
1548
  NUM_NODES
1549
} node_op_t;
1550
1551
static int _do_node_op(node_op_t type, const char *dev_name, uint32_t major,
1552
           uint32_t minor, uid_t uid, gid_t gid, mode_t mode,
1553
           const char *old_name, uint32_t read_ahead,
1554
           uint32_t read_ahead_flags, int warn_if_udev_failed)
1555
0
{
1556
0
  switch (type) {
1557
0
  case NODE_ADD:
1558
0
    return _add_dev_node(dev_name, major, minor, uid, gid,
1559
0
             mode, warn_if_udev_failed);
1560
0
  case NODE_DEL:
1561
0
    return _rm_dev_node(dev_name, warn_if_udev_failed);
1562
0
  case NODE_RENAME:
1563
0
    return _rename_dev_node(old_name, dev_name, warn_if_udev_failed);
1564
0
  case NODE_READ_AHEAD:
1565
0
    return _set_dev_node_read_ahead(dev_name, major, minor,
1566
0
            read_ahead, read_ahead_flags);
1567
0
  default:
1568
0
    ; /* NOTREACHED */
1569
0
  }
1570
1571
0
  return 1;
1572
0
}
1573
1574
struct dm_thread_state {
1575
  struct dm_list node_ops;
1576
  int count_node_ops[NUM_NODES];
1577
  char uuid_prefix[DM_MAX_UUID_PREFIX_LEN + 1];
1578
  int uuid_prefix_set;
1579
#ifdef UDEV_SYNC_SUPPORT
1580
  int sync_with_udev;
1581
  int udev_checking;
1582
#endif
1583
};
1584
1585
static pthread_key_t _thread_state_key;
1586
static pthread_once_t _thread_state_once = PTHREAD_ONCE_INIT;
1587
1588
static void _pop_node_ops(void);
1589
1590
static void _destroy_thread_state(void *ptr)
1591
0
{
1592
0
  struct dm_thread_state *ts = ptr;
1593
1594
  /*
1595
   * Flush any pending node ops as a safety net in case the
1596
   * caller did not call update_devs() before thread exit.
1597
   * Re-associate so _pop_node_ops() finds the state via accessor.
1598
   */
1599
0
  pthread_setspecific(_thread_state_key, ts);
1600
0
  _pop_node_ops();
1601
0
  pthread_setspecific(_thread_state_key, NULL);
1602
0
  dm_free(ts);
1603
0
}
1604
1605
static void _init_thread_state_key(void)
1606
0
{
1607
  /* pthread_once prevents retry on failure -- nothing we can do */
1608
0
  if (pthread_key_create(&_thread_state_key, _destroy_thread_state))
1609
0
    log_error("Failed to create thread state key.");
1610
0
}
1611
1612
static struct dm_thread_state *_get_thread_state(void)
1613
0
{
1614
0
  struct dm_thread_state *ts;
1615
1616
0
  pthread_once(&_thread_state_once, _init_thread_state_key);
1617
1618
0
  ts = pthread_getspecific(_thread_state_key);
1619
0
  if (!ts) {
1620
0
    if (!(ts = dm_zalloc(sizeof(*ts)))) {
1621
0
      log_error("Failed to allocate thread state.");
1622
0
      return NULL;
1623
0
    }
1624
0
    dm_list_init(&ts->node_ops);
1625
#ifdef UDEV_SYNC_SUPPORT
1626
    ts->sync_with_udev = 1;
1627
    ts->udev_checking = 1;
1628
#endif
1629
0
    pthread_setspecific(_thread_state_key, ts);
1630
0
  }
1631
1632
0
  return ts;
1633
0
}
1634
1635
void dm_thread_state_exit(void)
1636
0
{
1637
0
  struct dm_thread_state *ts = _get_thread_state();
1638
1639
0
  if (ts)
1640
0
    _destroy_thread_state(ts);
1641
1642
0
  pthread_key_delete(_thread_state_key);
1643
0
}
1644
1645
static struct dm_list *_get_node_ops_list(void)
1646
0
{
1647
0
  struct dm_thread_state *ts = _get_thread_state();
1648
1649
0
  return ts ? &ts->node_ops : NULL;
1650
0
}
1651
1652
static int *_get_count_node_ops(void)
1653
0
{
1654
0
  struct dm_thread_state *ts = _get_thread_state();
1655
1656
0
  return ts ? ts->count_node_ops : NULL;
1657
0
}
1658
1659
struct node_op_parms {
1660
  struct dm_list list;
1661
  node_op_t type;
1662
  char *dev_name;
1663
  uint32_t major;
1664
  uint32_t minor;
1665
  uid_t uid;
1666
  gid_t gid;
1667
  mode_t mode;
1668
  uint32_t read_ahead;
1669
  uint32_t read_ahead_flags;
1670
  char *old_name;
1671
  int warn_if_udev_failed;
1672
  unsigned rely_on_udev;
1673
  char names[0];
1674
};
1675
1676
static void _store_str(char **pos, char **ptr, const char *str)
1677
0
{
1678
0
  size_t len = strlen(str) + 1;
1679
0
  memcpy(*pos, str, len);
1680
0
  *ptr = *pos;
1681
0
  *pos += len;
1682
0
}
1683
1684
static void _del_node_op(struct node_op_parms *nop)
1685
0
{
1686
0
  int *count = _get_count_node_ops();
1687
1688
0
  if (count)
1689
0
    count[nop->type]--;
1690
0
  dm_list_del(&nop->list);
1691
0
  dm_free(nop);
1692
0
}
1693
1694
/* Check if there is other the type of node operation stacked */
1695
static int _other_node_ops(node_op_t type)
1696
0
{
1697
0
  int *count = _get_count_node_ops();
1698
0
  unsigned i;
1699
1700
0
  if (!count)
1701
0
    return 0;
1702
1703
0
  for (i = 0; i < NUM_NODES; i++)
1704
0
    if (type != i && count[i])
1705
0
      return 1;
1706
0
  return 0;
1707
0
}
1708
1709
static void _log_node_op(const char *action_str, struct node_op_parms *nop)
1710
0
{
1711
0
  const char *rely = nop->rely_on_udev ? " [trust_udev]" : "" ;
1712
0
  const char *verify = nop->warn_if_udev_failed ? " [verify_udev]" : "";
1713
1714
0
  switch (nop->type) {
1715
0
  case NODE_ADD:
1716
0
    log_debug_activation("%s: %s NODE_ADD (%" PRIu32 ",%" PRIu32 ") %u:%u 0%o%s%s",
1717
0
             nop->dev_name, action_str, nop->major, nop->minor, nop->uid, nop->gid, nop->mode,
1718
0
             rely, verify);
1719
0
    break;
1720
0
  case NODE_DEL:
1721
0
    log_debug_activation("%s: %s NODE_DEL%s%s", nop->dev_name, action_str, rely, verify);
1722
0
    break;
1723
0
  case NODE_RENAME:
1724
0
    log_debug_activation("%s: %s NODE_RENAME to %s%s%s", nop->old_name, action_str, nop->dev_name, rely, verify);
1725
0
    break;
1726
0
  case NODE_READ_AHEAD:
1727
0
    log_debug_activation("%s: %s NODE_READ_AHEAD %" PRIu32 " (flags=%" PRIu32 ")%s%s",
1728
0
             nop->dev_name, action_str, nop->read_ahead, nop->read_ahead_flags, rely, verify);
1729
0
    break;
1730
0
  default:
1731
0
    ; /* NOTREACHED */
1732
0
  }
1733
0
}
1734
1735
static int _stack_node_op(node_op_t type, const char *dev_name, uint32_t major,
1736
        uint32_t minor, uid_t uid, gid_t gid, mode_t mode,
1737
        const char *old_name, uint32_t read_ahead,
1738
        uint32_t read_ahead_flags, int warn_if_udev_failed,
1739
        unsigned rely_on_udev)
1740
0
{
1741
0
  struct node_op_parms *nop;
1742
0
  struct dm_list *noph, *nopht;
1743
0
  struct dm_list *node_ops;
1744
0
  int *count;
1745
0
  size_t len = strlen(dev_name) + strlen(old_name) + 2;
1746
0
  char *pos;
1747
1748
0
  if (!(node_ops = _get_node_ops_list()))
1749
0
    return 0;
1750
1751
0
  if (!(count = _get_count_node_ops()))
1752
0
    return 0;
1753
1754
  /*
1755
   * Note: warn_if_udev_failed must have valid content
1756
   */
1757
0
  if ((type == NODE_DEL) && _other_node_ops(type))
1758
    /*
1759
     * Ignore any outstanding operations on the node if deleting it.
1760
     */
1761
0
    dm_list_iterate_safe(noph, nopht, node_ops) {
1762
0
      nop = dm_list_item(noph, struct node_op_parms);
1763
0
      if (!strcmp(dev_name, nop->dev_name)) {
1764
0
        _log_node_op("Unstacking", nop);
1765
0
        _del_node_op(nop);
1766
0
        if (!_other_node_ops(type))
1767
0
          break; /* no other non DEL ops */
1768
0
      }
1769
0
    }
1770
0
  else if ((type == NODE_ADD) && count[NODE_DEL])
1771
    /*
1772
     * Ignore previous DEL operation on added node.
1773
     * (No other operations for this device than DEL could be stacked here).
1774
     */
1775
0
    dm_list_iterate_safe(noph, nopht, node_ops) {
1776
0
      nop = dm_list_item(noph, struct node_op_parms);
1777
0
      if ((nop->type == NODE_DEL) &&
1778
0
          !strcmp(dev_name, nop->dev_name)) {
1779
0
        _log_node_op("Unstacking", nop);
1780
0
        _del_node_op(nop);
1781
0
        break; /* no other DEL ops */
1782
0
      }
1783
0
    }
1784
0
  else if (type == NODE_RENAME)
1785
    /*
1786
     * Ignore any outstanding operations if renaming it.
1787
     *
1788
     * Currently  RENAME operation happens through 'suspend -> resume'.
1789
     * On 'resume' device is added with read_ahead settings, so it is
1790
     * safe to remove any stacked ADD, RENAME, READ_AHEAD operation
1791
     * There cannot be any DEL operation on the renamed device.
1792
     */
1793
0
    dm_list_iterate_safe(noph, nopht, node_ops) {
1794
0
      nop = dm_list_item(noph, struct node_op_parms);
1795
0
      if (!strcmp(old_name, nop->dev_name)) {
1796
0
        _log_node_op("Unstacking", nop);
1797
0
        _del_node_op(nop);
1798
0
      }
1799
0
    }
1800
0
  else if (type == NODE_READ_AHEAD) {
1801
    /* udev doesn't process readahead */
1802
0
    rely_on_udev = 0;
1803
0
    warn_if_udev_failed = 0;
1804
0
  }
1805
1806
0
  if (!(nop = dm_malloc(sizeof(*nop) + len))) {
1807
0
    log_error("Insufficient memory to stack mknod operation");
1808
0
    return 0;
1809
0
  }
1810
1811
0
  pos = nop->names;
1812
0
  nop->type = type;
1813
0
  nop->major = major;
1814
0
  nop->minor = minor;
1815
0
  nop->uid = uid;
1816
0
  nop->gid = gid;
1817
0
  nop->mode = mode;
1818
0
  nop->read_ahead = read_ahead;
1819
0
  nop->read_ahead_flags = read_ahead_flags;
1820
0
  nop->rely_on_udev = rely_on_udev;
1821
1822
  /*
1823
   * Clear warn_if_udev_failed if rely_on_udev is set.  It doesn't get
1824
   * checked in this case - this just removes the flag from log messages.
1825
   */
1826
0
  nop->warn_if_udev_failed = rely_on_udev ? 0 : warn_if_udev_failed;
1827
1828
0
  _store_str(&pos, &nop->dev_name, dev_name);
1829
0
  _store_str(&pos, &nop->old_name, old_name);
1830
1831
0
  count[type]++;
1832
0
  dm_list_add(node_ops, &nop->list);
1833
1834
0
  _log_node_op("Stacking", nop);
1835
1836
0
  return 1;
1837
0
}
1838
1839
static void _pop_node_ops(void)
1840
0
{
1841
0
  struct dm_list *noph, *nopht, *node_ops;
1842
0
  struct node_op_parms *nop;
1843
1844
0
  if (!(node_ops = _get_node_ops_list()))
1845
0
    return;
1846
1847
0
  dm_list_iterate_safe(noph, nopht, node_ops) {
1848
0
    nop = dm_list_item(noph, struct node_op_parms);
1849
0
    if (!nop->rely_on_udev) {
1850
0
      _log_node_op("Processing", nop);
1851
0
      _do_node_op(nop->type, nop->dev_name, nop->major, nop->minor,
1852
0
            nop->uid, nop->gid, nop->mode, nop->old_name,
1853
0
            nop->read_ahead, nop->read_ahead_flags,
1854
0
            nop->warn_if_udev_failed);
1855
0
    } else
1856
0
      _log_node_op("Skipping", nop);
1857
0
    _del_node_op(nop);
1858
0
  }
1859
0
}
1860
1861
int add_dev_node(const char *dev_name, uint32_t major, uint32_t minor,
1862
     uid_t uid, gid_t gid, mode_t mode, int check_udev, unsigned rely_on_udev)
1863
0
{
1864
0
  return _stack_node_op(NODE_ADD, dev_name, major, minor, uid,
1865
0
            gid, mode, "", 0, 0, check_udev, rely_on_udev);
1866
0
}
1867
1868
int rename_dev_node(const char *old_name, const char *new_name, int check_udev, unsigned rely_on_udev)
1869
0
{
1870
0
  return _stack_node_op(NODE_RENAME, new_name, 0, 0, 0,
1871
0
            0, 0, old_name, 0, 0, check_udev, rely_on_udev);
1872
0
}
1873
1874
int rm_dev_node(const char *dev_name, int check_udev, unsigned rely_on_udev)
1875
0
{
1876
0
  return _stack_node_op(NODE_DEL, dev_name, 0, 0, 0,
1877
0
            0, 0, "", 0, 0, check_udev, rely_on_udev);
1878
0
}
1879
1880
int set_dev_node_read_ahead(const char *dev_name,
1881
                            uint32_t major, uint32_t minor,
1882
          uint32_t read_ahead, uint32_t read_ahead_flags)
1883
0
{
1884
0
  if (read_ahead == DM_READ_AHEAD_AUTO)
1885
0
    return 1;
1886
1887
0
  return _stack_node_op(NODE_READ_AHEAD, dev_name, major, minor, 0, 0,
1888
0
                              0, "", read_ahead, read_ahead_flags, 0, 0);
1889
0
}
1890
1891
void update_devs(void)
1892
0
{
1893
0
  _pop_node_ops();
1894
0
}
1895
1896
static int _canonicalize_and_set_dir(const char *src, const char *suffix, size_t max_len, char *dir)
1897
0
{
1898
0
  size_t len;
1899
0
  const char *slash;
1900
1901
0
  if (*src != '/') {
1902
0
    log_debug_activation("Invalid directory value, %s: "
1903
0
             "not an absolute name.", src);
1904
0
    return 0;
1905
0
  }
1906
1907
0
  len = strlen(src);
1908
0
  slash = src[len-1] == '/' ? "" : "/";
1909
1910
0
  if (dm_snprintf(dir, max_len, "%s%s%s", src, slash, suffix ? suffix : "") < 0) {
1911
0
    log_debug_activation("Invalid directory value, %s: name too long.", src);
1912
0
    return 0;
1913
0
  }
1914
1915
0
  return 1;
1916
0
}
1917
1918
int dm_set_dev_dir(const char *dev_dir)
1919
0
{
1920
0
  char new_dir[PATH_MAX];
1921
1922
0
  if (!_canonicalize_and_set_dir(dev_dir, DM_DIR, sizeof new_dir, new_dir))
1923
0
    return_0;
1924
1925
0
  if (!strcmp(new_dir, _dm_dir))
1926
0
    return 1;
1927
1928
0
  if (!_is_init_thread("change dev dir"))
1929
0
    return 1;
1930
1931
0
  return dm_strncpy(_dm_dir, new_dir, sizeof _dm_dir);
1932
0
}
1933
1934
const char *dm_dir(void)
1935
0
{
1936
0
  return _dm_dir;
1937
0
}
1938
1939
int dm_set_sysfs_dir(const char *sysfs_dir)
1940
0
{
1941
0
  char new_dir[PATH_MAX];
1942
1943
0
  if (!sysfs_dir || !*sysfs_dir)
1944
0
    new_dir[0] = '\0';
1945
0
  else if (!_canonicalize_and_set_dir(sysfs_dir, NULL, sizeof new_dir, new_dir))
1946
0
    return_0;
1947
1948
0
  if (!strcmp(new_dir, _sysfs_dir))
1949
0
    return 1;
1950
1951
0
  if (!_is_init_thread("change sysfs dir"))
1952
0
    return 1;
1953
1954
0
  return dm_strncpy(_sysfs_dir, new_dir, sizeof _sysfs_dir);
1955
0
}
1956
1957
const char *dm_sysfs_dir(void)
1958
0
{
1959
0
  return _sysfs_dir;
1960
0
}
1961
1962
/*
1963
 * Replace existing uuid_prefix provided it isn't too long.
1964
 */
1965
int dm_set_uuid_prefix(const char *uuid_prefix)
1966
0
{
1967
0
  struct dm_thread_state *ts;
1968
0
  size_t len;
1969
1970
0
  if (!uuid_prefix)
1971
0
    return_0;
1972
1973
0
  if ((len = strlen(uuid_prefix)) > DM_MAX_UUID_PREFIX_LEN) {
1974
0
    log_error("New uuid prefix %s too long.", uuid_prefix);
1975
0
    return 0;
1976
0
  }
1977
1978
0
  if (!(ts = _get_thread_state()))
1979
0
    return_0;
1980
1981
0
  memcpy(ts->uuid_prefix, uuid_prefix, len + 1);
1982
0
  ts->uuid_prefix_set = 1;
1983
1984
0
  return 1;
1985
0
}
1986
1987
const char *dm_uuid_prefix(void)
1988
0
{
1989
0
  struct dm_thread_state *ts = _get_thread_state();
1990
1991
0
  if (ts && ts->uuid_prefix_set)
1992
0
    return ts->uuid_prefix;
1993
1994
0
  return _default_uuid_prefix;
1995
0
}
1996
1997
static int _is_octal(int a)
1998
0
{
1999
0
  return (((a) & ~7) == '0');
2000
0
}
2001
2002
/* Convert mangled mountinfo into normal ASCII string */
2003
static void _unmangle_mountinfo_string(const char *src, char *buf)
2004
0
{
2005
0
  while (*src) {
2006
0
    if ((*src == '\\') &&
2007
0
        _is_octal(src[1]) && _is_octal(src[2]) && _is_octal(src[3])) {
2008
0
      *buf++ = 64 * (src[1] & 7) + 8 * (src[2] & 7) + (src[3] & 7);
2009
0
      src += 4;
2010
0
    } else
2011
0
      *buf++ = *src++;
2012
0
  }
2013
0
  *buf = '\0';
2014
0
}
2015
2016
/* coverity[+tainted_string_sanitize_content:arg-0] */
2017
0
static int _sanitize_line(const char *line) { return 1; }
2018
2019
/* Parse one line of mountinfo and unmangled target line */
2020
static int _mountinfo_parse_line(const char *line, unsigned *maj, unsigned *min, char *buf)
2021
0
{
2022
0
  char root[PATH_MAX + 1]; /* sscanf needs extra '\0' */
2023
0
  char target[PATH_MAX + 1];
2024
0
  const char *devmapper;
2025
0
  struct dm_task *dmt;
2026
0
  struct dm_info info;
2027
0
  unsigned i;
2028
2029
  /* TODO: maybe detect availability of  %ms  glib support ? */
2030
0
  if (sscanf(line, "%*u %*u %u:%u %" DM_TO_STRING(PATH_MAX)
2031
0
       "s %" DM_TO_STRING(PATH_MAX) "s",
2032
0
       maj, min, root, target) < 4) {
2033
0
    log_error("Failed to parse mountinfo line.");
2034
0
    return 0;
2035
0
  }
2036
2037
  /* btrfs fakes device numbers, but there is still /dev/mapper name
2038
   * placed in mountinfo, so try to detect proper major:minor via this */
2039
0
  if (*maj == 0 && (devmapper = strstr(line, "/dev/mapper/"))) {
2040
0
    if (!(dmt = dm_task_create(DM_DEVICE_INFO))) {
2041
0
      log_error("Mount info task creation failed.");
2042
0
      return 0;
2043
0
    }
2044
0
    devmapper += 12; /* skip fixed prefix */
2045
0
    for (i = 0; devmapper[i] && devmapper[i] != ' ' && i < sizeof(root)-1; ++i)
2046
0
      root[i] = devmapper[i];
2047
0
    root[i] = 0;
2048
0
    _unmangle_mountinfo_string(root, buf);
2049
0
    buf[DM_NAME_LEN] = 0; /* cut away */
2050
2051
0
    if (dm_task_set_name(dmt, buf) &&
2052
0
        dm_task_no_open_count(dmt) &&
2053
0
        dm_task_run(dmt) &&
2054
0
        dm_task_get_info(dmt, &info)) {
2055
0
      log_debug("Replacing mountinfo device (%u:%u) with matching DM device %s (%u:%u).",
2056
0
          *maj, *min, buf, info.major, info.minor);
2057
0
      *maj = info.major;
2058
0
      *min = info.minor;
2059
0
    }
2060
0
    dm_task_destroy(dmt);
2061
0
  }
2062
2063
0
  _unmangle_mountinfo_string(target, buf);
2064
2065
0
  return 1;
2066
0
}
2067
2068
/*
2069
 * Function to operate on individual mountinfo line,
2070
 * minor, major and mount target are parsed and unmangled
2071
 */
2072
int dm_mountinfo_read(dm_mountinfo_line_callback_fn read_fn, void *cb_data)
2073
0
{
2074
0
  FILE *minfo;
2075
0
  char buffer[2 * PATH_MAX];
2076
0
  char target[PATH_MAX];
2077
0
  unsigned maj, min;
2078
0
  int r = 1;
2079
2080
0
  if (!(minfo = fopen(_mountinfo, "r"))) {
2081
0
    if (errno != ENOENT)
2082
0
      log_sys_error("fopen", _mountinfo);
2083
0
    else
2084
0
      log_sys_debug("fopen", _mountinfo);
2085
0
    return 0;
2086
0
  }
2087
2088
0
  while (!feof(minfo) && fgets(buffer, sizeof(buffer), minfo))
2089
0
    if (!_sanitize_line(buffer) ||
2090
0
        !_mountinfo_parse_line(buffer, &maj, &min, target) ||
2091
0
        !read_fn(buffer, maj, min, target, cb_data)) {
2092
0
      stack;
2093
0
      r = 0;
2094
0
      break;
2095
0
    }
2096
2097
0
  if (fclose(minfo))
2098
0
    log_sys_error("fclose", _mountinfo);
2099
2100
0
  return r;
2101
0
}
2102
2103
static int _sysfs_get_dm_name(uint32_t major, uint32_t minor, char *buf, size_t buf_size)
2104
0
{
2105
0
  char sysfs_path[PATH_MAX], temp_buf[2 * DM_NAME_LEN];
2106
0
  FILE *fp = NULL;
2107
0
  int r = 0;
2108
0
  size_t len;
2109
2110
0
  if (dm_snprintf(sysfs_path, sizeof(sysfs_path),
2111
0
      "%sdev/block/%" PRIu32 ":%" PRIu32
2112
0
      "/dm/name", _sysfs_dir, major, minor) < 0) {
2113
0
    log_error("_sysfs_get_dm_name: dm_snprintf failed.");
2114
0
    goto bad;
2115
0
  }
2116
2117
0
  if (!(fp = fopen(sysfs_path, "r"))) {
2118
0
    if (errno == ENOENT)
2119
0
      log_sys_debug("fopen", sysfs_path);
2120
0
    else
2121
0
      log_sys_error("fopen", sysfs_path);
2122
0
    goto bad;
2123
0
  }
2124
2125
0
  if (!fgets(temp_buf, sizeof(temp_buf), fp)) {
2126
0
    log_sys_error("fgets", sysfs_path);
2127
0
    goto bad;
2128
0
  }
2129
2130
0
  len = strlen(temp_buf);
2131
2132
0
  if (len > buf_size) {
2133
0
    log_error("_sysfs_get_dm_name: supplied buffer too small.");
2134
0
    goto bad;
2135
0
  }
2136
2137
0
  if (len)
2138
0
    --len;  /* strip \n */
2139
2140
0
  memcpy(buf, temp_buf, len);
2141
0
  buf[len] = '\0';
2142
2143
0
  r = 1;
2144
0
bad:
2145
0
  if (fp && fclose(fp))
2146
0
    log_sys_error("fclose", sysfs_path);
2147
2148
0
  return r;
2149
0
}
2150
2151
static int _sysfs_get_dev_major_minor(const char *path, uint32_t major, uint32_t minor)
2152
0
{
2153
0
  FILE *fp;
2154
0
  uint32_t ma, mi;
2155
0
  int r;
2156
2157
0
  if (!(fp = fopen(path, "r")))
2158
0
    return 0;
2159
2160
0
  r = (fscanf(fp, "%" PRIu32 ":%" PRIu32 , &ma, &mi) == 2) &&
2161
0
    (ma == major) && (mi == minor);
2162
  // log_debug("Checking %s  %u:%u  -> %d", path, ma, mi, r);
2163
2164
0
  if (fclose(fp))
2165
0
    log_sys_error("fclose", path);
2166
2167
0
  return r;
2168
0
}
2169
2170
static int _sysfs_find_kernel_name(uint32_t major, uint32_t minor, char *buf, size_t buf_size)
2171
0
{
2172
  /* sorted alphabetically */
2173
0
  static const char _ignore_sysfs[][16] = {
2174
0
    ".",
2175
0
    "..",
2176
0
    "bdi",
2177
0
    "dev",
2178
0
    "device",
2179
0
    "holders",
2180
0
    "integrity",
2181
0
    "loop",
2182
0
    "md",
2183
0
    "mq",
2184
0
    "power",
2185
0
    "queue",
2186
0
    "removable",
2187
0
    "slave",
2188
0
    "slaves",
2189
0
    "subsystem",
2190
0
    "trace",
2191
0
    "uevent"
2192
0
  };
2193
0
  const char *name, *name_dev;
2194
0
  char path[PATH_MAX];
2195
0
  struct dirent *dirent, *dirent_dev;
2196
0
  DIR *d, *d_dev;
2197
0
  int r = 0, sz;
2198
2199
0
  if (!*_sysfs_dir ||
2200
0
      dm_snprintf(path, sizeof(path), "%sblock/", _sysfs_dir) < 0) {
2201
0
    log_error("Failed to build sysfs_path.");
2202
0
    return 0;
2203
0
  }
2204
2205
0
  if (!(d = opendir(path))) {
2206
0
    log_sys_error("opendir", path);
2207
0
    return 0;
2208
0
  }
2209
2210
0
  while (!r && (dirent = readdir(d))) {
2211
0
    name = dirent->d_name;
2212
2213
0
    if (!strcmp(name, ".") || !strcmp(name, ".."))
2214
0
      continue;
2215
2216
0
    if ((sz = dm_snprintf(path, sizeof(path), "%sblock/%s/dev",
2217
0
              _sysfs_dir, name)) < 5) {
2218
0
      log_warn("Couldn't create path for %s.", name);
2219
0
      continue;
2220
0
    }
2221
2222
0
    if (_sysfs_get_dev_major_minor(path, major, minor)) {
2223
0
      r = dm_strncpy(buf, name, buf_size);
2224
0
      break; /* found */
2225
0
    }
2226
2227
0
    path[sz - 4] = 0; /* strip /dev from end of path string */
2228
2229
    /* let's assume there is no tree-complex device in past systems */
2230
0
    if (!(d_dev = opendir(path))) {
2231
      /* Silently skip non-directories, log other errors */
2232
0
      if (errno != ENOTDIR)
2233
0
        log_sys_debug("opendir", path);
2234
0
      continue;
2235
0
    }
2236
2237
0
    while ((dirent_dev = readdir(d_dev))) {
2238
0
      name_dev = dirent_dev->d_name;
2239
2240
      /* skip known ignorable paths using binary search */
2241
0
      if (bsearch(name_dev, _ignore_sysfs, DM_ARRAY_SIZE(_ignore_sysfs),
2242
0
            sizeof(_ignore_sysfs[0]), (int (*)(const void *, const void *))strcmp))
2243
0
        continue;
2244
2245
0
      if (dm_snprintf(path, sizeof(path), "%sblock/%s/%s/dev",
2246
0
          _sysfs_dir, name, name_dev) == -1) {
2247
0
        log_warn("Couldn't create path for %s/%s.", name, name_dev);
2248
0
        continue;
2249
0
      }
2250
2251
0
      if (_sysfs_get_dev_major_minor(path, major, minor)) {
2252
0
        r = dm_strncpy(buf, name_dev, buf_size);
2253
0
        break; /* found */
2254
0
      }
2255
0
    }
2256
2257
0
    if (closedir(d_dev))
2258
0
      log_sys_debug("closedir", name);
2259
0
    }
2260
2261
0
  if (closedir(d))
2262
0
    log_sys_debug("closedir", path);
2263
2264
0
  return r;
2265
0
}
2266
2267
static int _sysfs_get_kernel_name(uint32_t major, uint32_t minor, char *buf, size_t buf_size)
2268
0
{
2269
0
  char *name, *sysfs_path, *temp_buf = NULL;
2270
0
  ssize_t size;
2271
0
  int r = 0;
2272
2273
0
  if (!(sysfs_path = malloc(PATH_MAX)) ||
2274
0
      !(temp_buf = malloc(PATH_MAX))) {
2275
0
    log_error("_sysfs_get_kernel_name: failed to allocate temporary buffers");
2276
0
    goto bad;
2277
0
  }
2278
2279
0
  if (dm_snprintf(sysfs_path, PATH_MAX, "%sdev/block/%" PRIu32 ":%" PRIu32,
2280
0
      _sysfs_dir, major, minor) < 0) {
2281
0
    log_error("_sysfs_get_kernel_name: dm_snprintf failed");
2282
0
    goto bad;
2283
0
  }
2284
2285
0
  if ((size = readlink(sysfs_path, temp_buf, PATH_MAX - 1)) < 0) {
2286
0
    if (errno != ENOENT)
2287
0
      log_sys_error("readlink", sysfs_path);
2288
0
    else {
2289
0
      log_sys_debug("readlink", sysfs_path);
2290
0
      r = _sysfs_find_kernel_name(major, minor, buf, buf_size);
2291
0
      goto out;
2292
0
    }
2293
0
    goto bad;
2294
0
  }
2295
0
  temp_buf[size] = '\0';
2296
2297
0
  if (!(name = strrchr(temp_buf, '/'))) {
2298
0
    log_error("Could not locate device kernel name in sysfs path %s", temp_buf);
2299
0
    goto bad;
2300
0
  }
2301
0
  name += 1;
2302
0
  if (!_dm_strncpy(buf, name, buf_size)) {
2303
0
    log_error("_sysfs_get_kernel_name: output buffer too small");
2304
0
    goto bad;
2305
0
  }
2306
0
  r = 1;
2307
0
bad:
2308
0
out:
2309
0
  free(temp_buf);
2310
0
  free(sysfs_path);
2311
2312
0
  return r;
2313
0
}
2314
2315
int dm_device_get_name(uint32_t major, uint32_t minor, int prefer_kernel_name,
2316
           char *buf, size_t buf_size)
2317
0
{
2318
0
  if (!*_sysfs_dir)
2319
0
    return 0;
2320
2321
  /*
2322
   * device-mapper devices and prefer_kernel_name = 0
2323
   * get dm name by reading /sys/dev/block/major:minor/dm/name,
2324
   * fallback to _sysfs_get_kernel_name if not successful
2325
   */
2326
0
  if (dm_is_dm_major(major) && !prefer_kernel_name) {
2327
0
    if (_sysfs_get_dm_name(major, minor, buf, buf_size))
2328
0
      return 1;
2329
0
    else
2330
0
      stack;
2331
0
  }
2332
2333
  /*
2334
   * non-device-mapper devices or prefer_kernel_name = 1
2335
   * get kernel name using readlink /sys/dev/block/major:minor -> .../dm-X
2336
   */
2337
0
  return _sysfs_get_kernel_name(major, minor, buf, buf_size);
2338
0
}
2339
2340
int dm_device_has_holders(uint32_t major, uint32_t minor)
2341
0
{
2342
0
  char sysfs_path[PATH_MAX];
2343
0
  struct stat st;
2344
2345
0
  if (!*_sysfs_dir)
2346
0
    return 0;
2347
2348
0
  if (dm_snprintf(sysfs_path, PATH_MAX, "%sdev/block/%" PRIu32
2349
0
      ":%" PRIu32 "/holders", _sysfs_dir, major, minor) < 0) {
2350
0
    log_warn("WARNING: sysfs_path dm_snprintf failed.");
2351
0
    return 0;
2352
0
  }
2353
2354
0
  if (stat(sysfs_path, &st)) {
2355
0
    if (errno != ENOENT)
2356
0
      log_sys_debug("stat", sysfs_path);
2357
0
    return 0;
2358
0
  }
2359
2360
0
  return !dm_is_empty_dir(sysfs_path);
2361
0
}
2362
2363
static int _mounted_fs_on_device(const char *kernel_dev_name)
2364
0
{
2365
0
  char sysfs_path[PATH_MAX];
2366
0
  struct dirent *dirent;
2367
0
  DIR *d;
2368
0
  struct stat st;
2369
0
  int r = 0;
2370
2371
0
  if (dm_snprintf(sysfs_path, PATH_MAX, "%sfs", _sysfs_dir) < 0) {
2372
0
    log_warn("WARNING: sysfs_path dm_snprintf failed.");
2373
0
    return 0;
2374
0
  }
2375
2376
0
  if (!(d = opendir(sysfs_path))) {
2377
0
    if (errno != ENOENT)
2378
0
      log_sys_debug("opendir", sysfs_path);
2379
0
    return 0;
2380
0
  }
2381
2382
0
  while ((dirent = readdir(d))) {
2383
0
    if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, ".."))
2384
0
      continue;
2385
2386
0
    if (dm_snprintf(sysfs_path, PATH_MAX, "%sfs/%s/%s",
2387
0
        _sysfs_dir, dirent->d_name, kernel_dev_name) < 0) {
2388
0
      log_warn("WARNING: sysfs_path dm_snprintf failed.");
2389
0
      break;
2390
0
    }
2391
2392
0
    if (!stat(sysfs_path, &st)) {
2393
      /* found! */
2394
0
      r = 1;
2395
0
      break;
2396
0
    }
2397
0
    else if (errno != ENOENT) {
2398
0
      log_sys_debug("stat", sysfs_path);
2399
0
      break;
2400
0
    }
2401
0
  }
2402
2403
0
  if (closedir(d))
2404
0
    log_sys_debug("closedir", kernel_dev_name);
2405
2406
0
  return r;
2407
0
}
2408
2409
struct mountinfo_s {
2410
  unsigned maj;
2411
  unsigned min;
2412
  int mounted;
2413
};
2414
2415
static int _device_has_mounted_fs(char *buffer, unsigned major, unsigned minor,
2416
          char *target, void *cb_data)
2417
0
{
2418
0
  struct mountinfo_s *data = cb_data;
2419
0
  char kernel_dev_name[PATH_MAX];
2420
2421
0
  if ((major == data->maj) && (minor == data->min)) {
2422
0
    if (!dm_device_get_name(major, minor, 1, kernel_dev_name,
2423
0
          sizeof(kernel_dev_name))) {
2424
0
      stack;
2425
0
      *kernel_dev_name = '\0';
2426
0
    }
2427
0
    log_verbose("Device %s (%u:%u) appears to be mounted on %s.",
2428
0
          kernel_dev_name, major, minor, target);
2429
0
    data->mounted = 1;
2430
0
  }
2431
2432
0
  return 1;
2433
0
}
2434
2435
int dm_device_has_mounted_fs(uint32_t major, uint32_t minor)
2436
0
{
2437
0
  char kernel_dev_name[PATH_MAX];
2438
0
  struct mountinfo_s data = {
2439
0
    .maj = major,
2440
0
    .min = minor,
2441
0
  };
2442
2443
0
  if (!dm_mountinfo_read(_device_has_mounted_fs, &data))
2444
0
    stack;
2445
2446
0
  if (data.mounted)
2447
0
    return 1;
2448
  /*
2449
   * TODO: Verify dm_mountinfo_read() is superset
2450
   * and remove sysfs check (namespaces)
2451
   */
2452
  /* Get kernel device name first */
2453
0
  if (!dm_device_get_name(major, minor, 1, kernel_dev_name, PATH_MAX))
2454
0
    return 0;
2455
2456
  /* Check /sys/fs/<fs_name>/<kernel_dev_name> presence */
2457
0
  return _mounted_fs_on_device(kernel_dev_name);
2458
0
}
2459
2460
int dm_mknodes(const char *name)
2461
0
{
2462
0
  struct dm_task *dmt;
2463
0
  int r = 0;
2464
2465
0
  if (!(dmt = dm_task_create(DM_DEVICE_MKNODES)))
2466
0
    return_0;
2467
2468
0
  if (name && !dm_task_set_name(dmt, name))
2469
0
    goto out;
2470
2471
0
  if (!dm_task_no_open_count(dmt))
2472
0
    goto out;
2473
2474
0
  r = dm_task_run(dmt);
2475
2476
0
out:
2477
0
  dm_task_destroy(dmt);
2478
0
  return r;
2479
0
}
2480
2481
int dm_driver_version(char *version, size_t size)
2482
0
{
2483
0
  struct dm_task *dmt;
2484
0
  int r = 0;
2485
2486
0
  if (!(dmt = dm_task_create(DM_DEVICE_VERSION)))
2487
0
    return_0;
2488
2489
0
  if (!dm_task_run(dmt)) {
2490
0
    log_error("Failed to get driver version.");
2491
0
    goto out;
2492
0
  }
2493
2494
0
  if (!dm_task_get_driver_version(dmt, version, size))
2495
0
    goto out;
2496
2497
0
  r = 1;
2498
2499
0
out:
2500
0
  dm_task_destroy(dmt);
2501
0
  return r;
2502
0
}
2503
2504
static void _set_cookie_flags(struct dm_task *dmt, uint16_t flags)
2505
0
{
2506
0
  if (!dm_cookie_supported())
2507
0
    return;
2508
2509
0
  if (_udev_disabled) {
2510
    /*
2511
     * If udev is disabled, hardcode this functionality:
2512
     *   - we want libdm to create the nodes
2513
     *   - we don't want the /dev/mapper and any subsystem
2514
     *     related content to be created by udev if udev
2515
     *     rules are installed
2516
     */
2517
0
    flags &= ~DM_UDEV_DISABLE_LIBRARY_FALLBACK;
2518
0
    flags |= DM_UDEV_DISABLE_DM_RULES_FLAG | DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG;
2519
0
  }
2520
2521
0
  dmt->event_nr = flags << DM_UDEV_FLAGS_SHIFT;
2522
0
}
2523
2524
#ifndef UDEV_SYNC_SUPPORT
2525
void dm_udev_set_sync_support(int sync_with_udev)
2526
0
{
2527
0
}
2528
2529
int dm_udev_get_sync_support(void)
2530
0
{
2531
0
  return 0;
2532
0
}
2533
2534
void dm_udev_set_checking(int checking)
2535
0
{
2536
0
}
2537
2538
int dm_udev_get_checking(void)
2539
0
{
2540
0
  return 0;
2541
0
}
2542
2543
int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags)
2544
0
{
2545
0
  _set_cookie_flags(dmt, flags);
2546
2547
0
  *cookie = 0;
2548
0
  dmt->cookie_set = 1;
2549
2550
0
  return 1;
2551
0
}
2552
2553
int dm_udev_create_cookie(uint32_t *cookie)
2554
0
{
2555
0
  *cookie = 0;
2556
2557
0
  return 1;
2558
0
}
2559
2560
int dm_udev_complete(uint32_t cookie)
2561
0
{
2562
0
  return 1;
2563
0
}
2564
2565
int dm_udev_wait(uint32_t cookie)
2566
0
{
2567
0
  update_devs();
2568
2569
0
  return 1;
2570
0
}
2571
2572
int dm_udev_wait_immediate(uint32_t cookie, int *ready)
2573
0
{
2574
0
  update_devs();
2575
0
  *ready = 1;
2576
2577
0
  return 1;
2578
0
}
2579
2580
#else   /* UDEV_SYNC_SUPPORT */
2581
2582
static int _check_semaphore_is_supported(void)
2583
{
2584
  int maxid;
2585
  union semun arg;
2586
  struct seminfo seminfo;
2587
2588
  arg.__buf = &seminfo;
2589
  maxid = semctl(0, 0, SEM_INFO, arg);
2590
2591
  if (maxid < 0) {
2592
    log_warn("Kernel not configured for semaphores (System V IPC). "
2593
       "Not using udev synchronization code.");
2594
    return 0;
2595
  }
2596
2597
  return 1;
2598
}
2599
2600
static int _check_udev_is_running(void)
2601
{
2602
  int r = (access(UDEV_CONTROL_PATH, F_OK) >= 0) ||
2603
    (access(UDEV_LEGACY_QUEUE_PATH, F_OK) >= 0);
2604
2605
  if (!r)
2606
    log_debug_activation("Udev is not running. "
2607
             "Not using udev synchronization code.");
2608
2609
  return r;
2610
}
2611
2612
static pthread_once_t _udev_sync_once = PTHREAD_ONCE_INIT;
2613
2614
static void _init_udev_sync_requirements(void)
2615
{
2616
  _semaphore_supported = _check_semaphore_is_supported();
2617
  _udev_running = _check_udev_is_running();
2618
2619
  if (_udev_disabled && _udev_running)
2620
    log_warn("Udev is running and DM_DISABLE_UDEV environment variable is set. "
2621
       "Bypassing udev, device-mapper library will manage device "
2622
       "nodes in device directory.");
2623
}
2624
2625
void dm_udev_set_sync_support(int sync_with_udev)
2626
{
2627
  struct dm_thread_state *ts;
2628
2629
  pthread_once(&_udev_sync_once, _init_udev_sync_requirements);
2630
2631
  if ((ts = _get_thread_state()))
2632
    ts->sync_with_udev = sync_with_udev;
2633
}
2634
2635
int dm_udev_get_sync_support(void)
2636
{
2637
  struct dm_thread_state *ts;
2638
2639
  pthread_once(&_udev_sync_once, _init_udev_sync_requirements);
2640
2641
  ts = _get_thread_state();
2642
2643
  return !_udev_disabled && _semaphore_supported &&
2644
    dm_cookie_supported() && _udev_running &&
2645
    (ts ? ts->sync_with_udev : 1);
2646
}
2647
2648
void dm_udev_set_checking(int checking)
2649
{
2650
  struct dm_thread_state *ts;
2651
2652
  if ((ts = _get_thread_state()))
2653
    ts->udev_checking = checking;
2654
2655
  if (checking)
2656
    log_debug_activation("DM udev checking enabled");
2657
  else
2658
    log_debug_activation("DM udev checking disabled");
2659
}
2660
2661
int dm_udev_get_checking(void)
2662
{
2663
  struct dm_thread_state *ts = _get_thread_state();
2664
2665
  return ts ? ts->udev_checking : 1;
2666
}
2667
2668
static int _get_cookie_sem(uint32_t cookie, int *semid)
2669
{
2670
  if (cookie >> 16 != DM_COOKIE_MAGIC) {
2671
    log_error("Could not continue to access notification "
2672
        "semaphore identified by cookie value %"
2673
        PRIu32 " (0x%x). Incorrect cookie prefix.",
2674
        cookie, cookie);
2675
    return 0;
2676
  }
2677
2678
  if ((*semid = semget((key_t) cookie, 1, 0)) >= 0)
2679
    return 1;
2680
2681
  switch (errno) {
2682
    case ENOENT:
2683
      log_error("Could not find notification "
2684
          "semaphore identified by cookie "
2685
          "value %" PRIu32 " (0x%x)",
2686
          cookie, cookie);
2687
      break;
2688
    case EACCES:
2689
      log_error("No permission to access "
2690
          "notification semaphore identified "
2691
          "by cookie value %" PRIu32 " (0x%x)",
2692
          cookie, cookie);
2693
      break;
2694
    default:
2695
      log_error("Failed to access notification "
2696
           "semaphore identified by cookie "
2697
           "value %" PRIu32 " (0x%x): %s",
2698
          cookie, cookie, strerror(errno));
2699
      break;
2700
  }
2701
2702
  return 0;
2703
}
2704
2705
static int _udev_notify_sem_inc(uint32_t cookie, int semid)
2706
{
2707
  struct sembuf sb = {0, 1, 0};
2708
  int val;
2709
2710
  if (semop(semid, &sb, 1) < 0) {
2711
    log_error("cookie inc: semid %d: semop failed for cookie 0x%" PRIx32 ": %s",
2712
        semid, cookie, strerror(errno));
2713
    return 0;
2714
  }
2715
2716
  if ((val = semctl(semid, 0, GETVAL)) < 0) {
2717
    log_warn("cookie inc: semid %d: semctl GETVAL failed for "
2718
        "cookie 0x%" PRIx32 ": %s",
2719
        semid, cookie, strerror(errno));
2720
    log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) incremented.",
2721
              cookie, semid);
2722
  } else
2723
    log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) incremented to %d",
2724
             cookie, semid, val);
2725
2726
  return 1;
2727
}
2728
2729
static int _udev_notify_sem_dec(uint32_t cookie, int semid)
2730
{
2731
  struct sembuf sb = {0, -1, IPC_NOWAIT};
2732
  int val;
2733
2734
  if ((val = semctl(semid, 0, GETVAL)) < 0)
2735
    log_warn("cookie dec: semid %d: semctl GETVAL failed for "
2736
       "cookie 0x%" PRIx32 ": %s",
2737
       semid, cookie, strerror(errno));
2738
2739
  if (semop(semid, &sb, 1) < 0) {
2740
    switch (errno) {
2741
      case EAGAIN:
2742
        log_error("cookie dec: semid %d: semop failed for cookie "
2743
            "0x%" PRIx32 ": "
2744
            "incorrect semaphore state",
2745
            semid, cookie);
2746
        break;
2747
      default:
2748
        log_error("cookie dec: semid %d: semop failed for cookie "
2749
            "0x%" PRIx32 ": %s",
2750
            semid, cookie, strerror(errno));
2751
        break;
2752
    }
2753
    return 0;
2754
  }
2755
2756
  if (val < 0)
2757
    log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) decremented.",
2758
             cookie, semid);
2759
  else
2760
    log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) decremented to %d",
2761
             cookie, semid, val - 1);
2762
  return 1;
2763
}
2764
2765
static int _udev_notify_sem_destroy(uint32_t cookie, int semid)
2766
{
2767
  if (semctl(semid, 0, IPC_RMID, 0) < 0) {
2768
    log_error("Could not cleanup notification semaphore "
2769
        "identified by cookie value %" PRIu32 " (0x%x): %s",
2770
        cookie, cookie, strerror(errno));
2771
    return 0;
2772
  }
2773
2774
  log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) destroyed", cookie,
2775
           semid);
2776
2777
  return 1;
2778
}
2779
2780
static int _udev_notify_sem_create(uint32_t *cookie, int *semid)
2781
{
2782
  int fd;
2783
  int gen_semid;
2784
  int val;
2785
  uint16_t base_cookie;
2786
  uint32_t gen_cookie;
2787
  union semun sem_arg;
2788
2789
  if ((fd = open("/dev/urandom", O_RDONLY)) < 0) {
2790
    log_error("Failed to open /dev/urandom "
2791
        "to create random cookie value");
2792
    *cookie = 0;
2793
    return 0;
2794
  }
2795
2796
  /* Generate random cookie value. Be sure it is unique and non-zero. */
2797
  do {
2798
    /* FIXME Handle non-error returns from read(). Move _io() into libdm? */
2799
    if (read(fd, &base_cookie, sizeof(base_cookie)) != sizeof(base_cookie)) {
2800
      log_error("Failed to initialize notification cookie");
2801
      goto bad;
2802
    }
2803
2804
    gen_cookie = DM_COOKIE_MAGIC << 16 | base_cookie;
2805
2806
    if (base_cookie && (gen_semid = semget((key_t) gen_cookie,
2807
            1, 0600 | IPC_CREAT | IPC_EXCL)) < 0) {
2808
      switch (errno) {
2809
        case EEXIST:
2810
          /* if the semaphore key exists, we
2811
           * simply generate another random one */
2812
          base_cookie = 0;
2813
          break;
2814
        case ENOMEM:
2815
          log_error("Not enough memory to create "
2816
              "notification semaphore");
2817
          goto bad;
2818
        case ENOSPC:
2819
          log_error("Limit for the maximum number "
2820
              "of semaphores reached. You can "
2821
              "check and set the limits in "
2822
              "/proc/sys/kernel/sem.");
2823
          goto bad;
2824
        default:
2825
          log_error("Failed to create notification "
2826
              "semaphore: %s", strerror(errno));
2827
          goto bad;
2828
      }
2829
    }
2830
  } while (!base_cookie);
2831
2832
  log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) created",
2833
           gen_cookie, gen_semid);
2834
2835
  sem_arg.val = 1;
2836
2837
  if (semctl(gen_semid, 0, SETVAL, sem_arg) < 0) {
2838
    log_error("cookie create: semid %d: semctl failed: %s", gen_semid, strerror(errno));
2839
    /* We have to destroy just created semaphore
2840
     * so it won't stay in the system. */
2841
    (void) _udev_notify_sem_destroy(gen_cookie, gen_semid);
2842
    goto bad;
2843
  }
2844
2845
  if ((val = semctl(gen_semid, 0, GETVAL)) < 0) {
2846
    log_error("cookie create: semid %d: semctl GETVAL failed for "
2847
        "cookie 0x%" PRIx32 ": %s",
2848
        gen_semid, gen_cookie, strerror(errno));
2849
    (void) _udev_notify_sem_destroy(gen_cookie, gen_semid);
2850
    goto bad;
2851
  }
2852
2853
  log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) incremented to %d",
2854
           gen_cookie, gen_semid, val);
2855
2856
  if (close(fd))
2857
    stack;
2858
2859
  *semid = gen_semid;
2860
  *cookie = gen_cookie;
2861
2862
  return 1;
2863
2864
bad:
2865
  if (close(fd))
2866
    stack;
2867
2868
  *cookie = 0;
2869
2870
  return 0;
2871
}
2872
2873
int dm_udev_create_cookie(uint32_t *cookie)
2874
{
2875
  int semid;
2876
2877
  if (!dm_udev_get_sync_support()) {
2878
    *cookie = 0;
2879
    return 1;
2880
  }
2881
2882
  return _udev_notify_sem_create(cookie, &semid);
2883
}
2884
2885
static const char *_task_type_disp(int type)
2886
{
2887
  switch(type) {
2888
  case DM_DEVICE_CREATE:
2889
    return "CREATE";
2890
  case DM_DEVICE_RELOAD:
2891
    return "RELOAD";
2892
  case DM_DEVICE_REMOVE:
2893
    return "REMOVE";
2894
  case DM_DEVICE_REMOVE_ALL:
2895
    return "REMOVE_ALL";
2896
  case DM_DEVICE_SUSPEND:
2897
    return "SUSPEND";
2898
  case DM_DEVICE_RESUME:
2899
    return "RESUME";
2900
  case DM_DEVICE_INFO:
2901
    return "INFO";
2902
  case DM_DEVICE_DEPS:
2903
    return "DEPS";
2904
  case DM_DEVICE_RENAME:
2905
    return "RENAME";
2906
  case DM_DEVICE_VERSION:
2907
    return "VERSION";
2908
  case DM_DEVICE_STATUS:
2909
    return "STATUS";
2910
  case DM_DEVICE_TABLE:
2911
    return "TABLE";
2912
  case DM_DEVICE_WAITEVENT:
2913
    return "WAITEVENT";
2914
  case DM_DEVICE_LIST:
2915
    return "LIST";
2916
  case DM_DEVICE_CLEAR:
2917
    return "CLEAR";
2918
  case DM_DEVICE_MKNODES:
2919
    return "MKNODES";
2920
  case DM_DEVICE_LIST_VERSIONS:
2921
    return "LIST_VERSIONS";
2922
  case DM_DEVICE_TARGET_MSG:
2923
    return "TARGET_MSG";
2924
  case DM_DEVICE_SET_GEOMETRY:
2925
    return "SET_GEOMETRY";
2926
  }
2927
  return "unknown";
2928
}
2929
2930
int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags)
2931
{
2932
  int semid;
2933
2934
  _set_cookie_flags(dmt, flags);
2935
2936
  if (!dm_udev_get_sync_support()) {
2937
    *cookie = 0;
2938
    dmt->cookie_set = 1;
2939
    return 1;
2940
  }
2941
2942
  if (*cookie) {
2943
    if (!_get_cookie_sem(*cookie, &semid))
2944
      goto_bad;
2945
  } else if (!_udev_notify_sem_create(cookie, &semid))
2946
    goto_bad;
2947
2948
  if (!_udev_notify_sem_inc(*cookie, semid)) {
2949
    log_error("Could not set notification semaphore "
2950
        "identified by cookie value %" PRIu32 " (0x%x)",
2951
        *cookie, *cookie);
2952
    goto bad;
2953
  }
2954
2955
  dmt->event_nr |= ~DM_UDEV_FLAGS_MASK & *cookie;
2956
  dmt->cookie_set = 1;
2957
2958
  log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) assigned to "
2959
           "%s task(%d) with flags%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s (0x%" PRIx16 ")",
2960
           *cookie, semid, _task_type_disp(dmt->type), dmt->type,
2961
           (flags & DM_UDEV_DISABLE_DM_RULES_FLAG) ? " DISABLE_DM_RULES" : "",
2962
           (flags & DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG) ? " DISABLE_SUBSYSTEM_RULES" : "",
2963
           (flags & DM_UDEV_DISABLE_DISK_RULES_FLAG) ? " DISABLE_DISK_RULES" : "",
2964
           (flags & DM_UDEV_DISABLE_OTHER_RULES_FLAG) ? " DISABLE_OTHER_RULES" : "",
2965
           (flags & DM_UDEV_LOW_PRIORITY_FLAG) ? " LOW_PRIORITY" : "",
2966
           (flags & DM_UDEV_DISABLE_LIBRARY_FALLBACK) ? " DISABLE_LIBRARY_FALLBACK" : "",
2967
           (flags & DM_UDEV_PRIMARY_SOURCE_FLAG) ? " PRIMARY_SOURCE" : "",
2968
           (flags & DM_SUBSYSTEM_UDEV_FLAG0) ? " SUBSYSTEM_0" : "",
2969
           (flags & DM_SUBSYSTEM_UDEV_FLAG1) ? " SUBSYSTEM_1" : "",
2970
           (flags & DM_SUBSYSTEM_UDEV_FLAG2) ? " SUBSYSTEM_2" : "",
2971
           (flags & DM_SUBSYSTEM_UDEV_FLAG3) ? " SUBSYSTEM_3" : "",
2972
           (flags & DM_SUBSYSTEM_UDEV_FLAG4) ? " SUBSYSTEM_4" : "",
2973
           (flags & DM_SUBSYSTEM_UDEV_FLAG5) ? " SUBSYSTEM_5" : "",
2974
           (flags & DM_SUBSYSTEM_UDEV_FLAG6) ? " SUBSYSTEM_6" : "",
2975
           (flags & DM_SUBSYSTEM_UDEV_FLAG7) ? " SUBSYSTEM_7" : "",
2976
           flags);
2977
2978
  return 1;
2979
2980
bad:
2981
  dmt->event_nr = 0;
2982
  return 0;
2983
}
2984
2985
int dm_udev_complete(uint32_t cookie)
2986
{
2987
  int semid;
2988
2989
  if (!cookie || !dm_udev_get_sync_support())
2990
    return 1;
2991
2992
  if (!_get_cookie_sem(cookie, &semid))
2993
    return_0;
2994
2995
  if (!_udev_notify_sem_dec(cookie, semid)) {
2996
    log_error("Could not signal waiting process using notification "
2997
        "semaphore identified by cookie value %" PRIu32 " (0x%x)",
2998
        cookie, cookie);
2999
    return 0;
3000
  }
3001
3002
  return 1;
3003
}
3004
3005
/*
3006
 * If *nowait is set, return immediately leaving it set if the semaphore
3007
 * is not ready to be decremented to 0.  *nowait is cleared if the wait
3008
 * succeeds.
3009
 */
3010
static int _udev_wait(uint32_t cookie, int *nowait)
3011
{
3012
  int semid;
3013
  struct sembuf sb = {0, 0, 0};
3014
  int val;
3015
3016
  if (!cookie || !dm_udev_get_sync_support())
3017
    return 1;
3018
3019
  if (!_get_cookie_sem(cookie, &semid))
3020
    return_0;
3021
3022
  /* Return immediately if the semaphore value exceeds 1? */
3023
  if (*nowait) {
3024
    if ((val = semctl(semid, 0, GETVAL)) < 0) {
3025
      log_error("semid %d: semctl GETVAL failed for "
3026
          "cookie 0x%" PRIx32 ": %s",
3027
          semid, cookie, strerror(errno));
3028
      return 0;
3029
    }
3030
3031
    if (val > 1)
3032
      return 1;
3033
3034
    *nowait = 0;
3035
  }
3036
3037
  if (!_udev_notify_sem_dec(cookie, semid)) {
3038
    log_error("Failed to set a proper state for notification "
3039
        "semaphore identified by cookie value %" PRIu32 " (0x%x) "
3040
        "to initialize waiting for incoming notifications.",
3041
        cookie, cookie);
3042
    (void) _udev_notify_sem_destroy(cookie, semid);
3043
    return 0;
3044
  }
3045
3046
  log_debug_activation("Udev cookie 0x%" PRIx32 " (semid %d) waiting for zero",
3047
           cookie, semid);
3048
3049
repeat_wait:
3050
  if (semop(semid, &sb, 1) < 0) {
3051
    if (errno == EINTR)
3052
      goto repeat_wait;
3053
    else if (errno == EIDRM)
3054
      return 1;
3055
3056
    log_error("Could not set wait state for notification semaphore "
3057
        "identified by cookie value %" PRIu32 " (0x%x): %s",
3058
        cookie, cookie, strerror(errno));
3059
    (void) _udev_notify_sem_destroy(cookie, semid);
3060
    return 0;
3061
  }
3062
3063
  return _udev_notify_sem_destroy(cookie, semid);
3064
}
3065
3066
int dm_udev_wait(uint32_t cookie)
3067
{
3068
  int nowait = 0;
3069
  int r = _udev_wait(cookie, &nowait);
3070
3071
  update_devs();
3072
3073
  return r;
3074
}
3075
3076
int dm_udev_wait_immediate(uint32_t cookie, int *ready)
3077
{
3078
  int nowait = 1;
3079
  int r = _udev_wait(cookie, &nowait);
3080
3081
  if (r && nowait) {
3082
    *ready = 0;
3083
    return 1;
3084
  }
3085
3086
  update_devs();
3087
  *ready = 1;
3088
3089
  return r;
3090
}
3091
#endif    /* UDEV_SYNC_SUPPORT */