Coverage Report

Created: 2026-08-12 06:13

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