Fix includes for libdevmapper internals.
[platform/upstream/cryptsetup.git] / lib / libdevmapper.c
1 #include <sys/ioctl.h>
2 #include <sys/stat.h>
3 #include <stdio.h>
4 #include <dirent.h>
5 #include <errno.h>
6 #include <libdevmapper.h>
7 #include <fcntl.h>
8 #include <linux/fs.h>
9 #include <uuid/uuid.h>
10
11 #include "internal.h"
12 #include "luks.h"
13
14 #define DEVICE_DIR              "/dev"
15 #define DM_UUID_LEN             129
16 #define DM_UUID_PREFIX          "CRYPT-"
17 #define DM_UUID_PREFIX_LEN      6
18 #define DM_CRYPT_TARGET         "crypt"
19 #define RETRY_COUNT             5
20
21 static int _dm_use_count = 0;
22 static struct crypt_device *_context = NULL;
23
24 /* Compatibility for old device-mapper without udev support */
25 #ifndef HAVE_DM_TASK_SET_COOKIE
26 #define CRYPT_TEMP_UDEV_FLAGS   0
27 static int dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags) { return 0; }
28 static int dm_udev_wait(uint32_t cookie) { return 0; };
29 #else
30 #define CRYPT_TEMP_UDEV_FLAGS   DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG | \
31                                 DM_UDEV_DISABLE_DISK_RULES_FLAG | \
32                                 DM_UDEV_DISABLE_OTHER_RULES_FLAG
33 #endif
34
35 static int _dm_use_udev()
36 {
37 #ifdef USE_UDEV /* cannot be enabled if devmapper is too old */
38         return dm_udev_get_sync_support();
39 #else
40         return 0;
41 #endif
42 }
43
44 static void set_dm_error(int level, const char *file, int line,
45                          const char *f, ...)
46 {
47         char *msg = NULL;
48         va_list va;
49
50         va_start(va, f);
51         if (vasprintf(&msg, f, va) > 0) {
52                 if (level < 4) {
53                         log_err(_context, msg);
54                         log_err(_context, "\n");
55                 } else
56                         log_dbg(msg);
57         }
58         free(msg);
59         va_end(va);
60 }
61
62 static int _dm_simple(int task, const char *name, int udev_wait);
63
64 int dm_init(struct crypt_device *context, int check_kernel)
65 {
66         if (!_dm_use_count++) {
67                 log_dbg("Initialising device-mapper backend%s, UDEV is %sabled.",
68                         check_kernel ? "" : " (NO kernel check requested)",
69                         _dm_use_udev() ? "en" : "dis");
70                 if (check_kernel && !_dm_simple(DM_DEVICE_LIST_VERSIONS, NULL, 0)) {
71                         log_err(context, _("Cannot initialize device-mapper. Is dm_mod kernel module loaded?\n"));
72                         return -1;
73                 }
74                 if (getuid() || geteuid())
75                         log_dbg(("WARNING: Running as a non-root user. Functionality may be unavailable."));
76                 dm_log_init(set_dm_error);
77                 dm_log_init_verbose(10);
78         }
79
80         // FIXME: global context is not safe
81         if (context)
82                 _context = context;
83
84         return 1;       /* unsafe memory */
85 }
86
87 void dm_exit(void)
88 {
89         if (_dm_use_count && (!--_dm_use_count)) {
90                 log_dbg("Releasing device-mapper backend.");
91                 dm_log_init_verbose(0);
92                 dm_log_init(NULL);
93                 dm_lib_release();
94                 _context = NULL;
95         }
96 }
97
98 static char *__lookup_dev(char *path, dev_t dev, int dir_level, const int max_level)
99 {
100         struct dirent *entry;
101         struct stat st;
102         char *ptr;
103         char *result = NULL;
104         DIR *dir;
105         int space;
106
107         /* Ignore strange nested directories */
108         if (dir_level > max_level)
109                 return NULL;
110
111         path[PATH_MAX - 1] = '\0';
112         ptr = path + strlen(path);
113         *ptr++ = '/';
114         *ptr = '\0';
115         space = PATH_MAX - (ptr - path);
116
117         dir = opendir(path);
118         if (!dir)
119                 return NULL;
120
121         while((entry = readdir(dir))) {
122                 if (entry->d_name[0] == '.' ||
123                     !strncmp(entry->d_name, "..", 2))
124                         continue;
125
126                 strncpy(ptr, entry->d_name, space);
127                 if (lstat(path, &st) < 0)
128                         continue;
129
130                 if (S_ISDIR(st.st_mode)) {
131                         result = __lookup_dev(path, dev, dir_level + 1, max_level);
132                         if (result)
133                                 break;
134                 } else if (S_ISBLK(st.st_mode)) {
135                         /* workaround: ignore dm-X devices, these are internal kernel names */
136                         if (dir_level == 0 && !strncmp(entry->d_name, "dm-", 3))
137                                 continue;
138                         if (st.st_rdev == dev) {
139                                 result = strdup(path);
140                                 break;
141                         }
142                 }
143         }
144
145         closedir(dir);
146         return result;
147 }
148
149 static char *lookup_dev(const char *dev_id)
150 {
151         uint32_t major, minor;
152         dev_t dev;
153         char *result, buf[PATH_MAX + 1];
154
155         if (sscanf(dev_id, "%" PRIu32 ":%" PRIu32, &major, &minor) != 2)
156                 return NULL;
157
158         dev = makedev(major, minor);
159         strncpy(buf, DEVICE_DIR, PATH_MAX);
160         buf[PATH_MAX] = '\0';
161
162         /* First try low level device */
163         if ((result = __lookup_dev(buf, dev, 0, 0)))
164                 return result;
165
166         /* If it is dm, try DM dir  */
167         if (dm_is_dm_major(major)) {
168                 strncpy(buf, dm_dir(), PATH_MAX);
169                 if ((result = __lookup_dev(buf, dev, 0, 0)))
170                         return result;
171         }
172
173         strncpy(buf, DEVICE_DIR, PATH_MAX);
174         result = __lookup_dev(buf, dev, 0, 4);
175
176         /* If not found, return major:minor */
177         return result ?: strdup(dev_id);
178 }
179
180 static int _dev_read_ahead(const char *dev, uint32_t *read_ahead)
181 {
182         int fd, r = 0;
183         long read_ahead_long;
184
185         if ((fd = open(dev, O_RDONLY)) < 0)
186                 return 0;
187
188         r = ioctl(fd, BLKRAGET, &read_ahead_long) ? 0 : 1;
189         close(fd);
190
191         if (r)
192                 *read_ahead = (uint32_t) read_ahead_long;
193
194         return r;
195 }
196
197 static void hex_key(char *hexkey, size_t key_size, const char *key)
198 {
199         int i;
200
201         for(i = 0; i < key_size; i++)
202                 sprintf(&hexkey[i * 2], "%02x", (unsigned char)key[i]);
203 }
204
205 static char *get_params(const char *device, uint64_t skip, uint64_t offset,
206                         const char *cipher, size_t key_size, const char *key)
207 {
208         char *params;
209         char *hexkey;
210
211         hexkey = safe_alloc(key_size * 2 + 1);
212         if (!hexkey)
213                 return NULL;
214
215         hex_key(hexkey, key_size, key);
216
217         params = safe_alloc(strlen(hexkey) + strlen(cipher) + strlen(device) + 64);
218         if (!params)
219                 goto out;
220
221         sprintf(params, "%s %s %" PRIu64 " %s %" PRIu64,
222                 cipher, hexkey, skip, device, offset);
223
224 out:
225         safe_free(hexkey);
226         return params;
227 }
228
229 /* DM helpers */
230 static int _dm_simple(int task, const char *name, int udev_wait)
231 {
232         int r = 0;
233         struct dm_task *dmt;
234         uint32_t cookie = 0;
235
236         if (!_dm_use_udev())
237                 udev_wait = 0;
238
239         if (!(dmt = dm_task_create(task)))
240                 return 0;
241
242         if (name && !dm_task_set_name(dmt, name))
243                 goto out;
244
245         if (udev_wait && !dm_task_set_cookie(dmt, &cookie, 0))
246                 goto out;
247
248         r = dm_task_run(dmt);
249
250         if (udev_wait)
251                 (void)dm_udev_wait(cookie);
252
253       out:
254         dm_task_destroy(dmt);
255         return r;
256 }
257
258 static int _error_device(const char *name, size_t size)
259 {
260         struct dm_task *dmt;
261         int r = 0;
262
263         if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
264                 return 0;
265
266         if (!dm_task_set_name(dmt, name))
267                 goto error;
268
269         if (!dm_task_add_target(dmt, UINT64_C(0), size, "error", ""))
270                 goto error;
271
272         if (!dm_task_set_ro(dmt))
273                 goto error;
274
275         if (!dm_task_no_open_count(dmt))
276                 goto error;
277
278         if (!dm_task_run(dmt))
279                 goto error;
280
281         if (!_dm_simple(DM_DEVICE_RESUME, name, 1)) {
282                 _dm_simple(DM_DEVICE_CLEAR, name, 0);
283                 goto error;
284         }
285
286         r = 1;
287
288 error:
289         dm_task_destroy(dmt);
290         return r;
291 }
292
293 int dm_remove_device(const char *name, int force, uint64_t size)
294 {
295         int r = -EINVAL;
296         int retries = force ? RETRY_COUNT : 1;
297         int error_target = 0;
298
299         if (!name || (force && !size))
300                 return -EINVAL;
301
302         do {
303                 r = _dm_simple(DM_DEVICE_REMOVE, name, 1) ? 0 : -EINVAL;
304                 if (--retries && r) {
305                         log_dbg("WARNING: other process locked internal device %s, %s.",
306                                 name, retries ? "retrying remove" : "giving up");
307                         if (force && (crypt_get_debug_level() == CRYPT_LOG_DEBUG))
308                                 debug_processes_using_device(name);
309                         sleep(1);
310                         if (force && !error_target) {
311                                 /* If force flag is set, replace device with error, read-only target.
312                                  * it should stop processes from reading it and also removed underlying
313                                  * device from mapping, so it is usable again.
314                                  * Force flag should be used only for temporary devices, which are
315                                  * intended to work inside cryptsetup only!
316                                  * Anyway, if some process try to read temporary cryptsetup device,
317                                  * it is bug - no other process should try touch it (e.g. udev).
318                                  */
319                                 _error_device(name, size);
320                                 error_target = 1;
321                         }
322                 }
323         } while (r == -EINVAL && retries);
324
325         dm_task_update_nodes();
326
327         return r;
328 }
329
330 #define UUID_LEN 37 /* 36 + \0, libuuid ... */
331 /*
332  * UUID has format: CRYPT-<devicetype>-[<uuid>-]<device name>
333  * CRYPT-PLAIN-name
334  * CRYPT-LUKS1-00000000000000000000000000000000-name
335  * CRYPT-TEMP-name
336  */
337 static void dm_prepare_uuid(const char *name, const char *type, const char *uuid, char *buf, size_t buflen)
338 {
339         char *ptr, uuid2[UUID_LEN] = {0};
340         uuid_t uu;
341         int i = 0;
342
343         /* Remove '-' chars */
344         if (uuid && !uuid_parse(uuid, uu)) {
345                 for (ptr = uuid2, i = 0; i < UUID_LEN; i++)
346                         if (uuid[i] != '-') {
347                                 *ptr = uuid[i];
348                                 ptr++;
349                         }
350         }
351
352         i = snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s%s",
353                 type ?: "", type ? "-" : "",
354                 uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "",
355                 name);
356
357         log_dbg("DM-UUID is %s", buf);
358         if (i >= buflen)
359                 log_err(NULL, _("DM-UUID for device %s was truncated.\n"), name);
360 }
361
362 int dm_create_device(const char *name,
363                      const char *device,
364                      const char *cipher,
365                      const char *type,
366                      const char *uuid,
367                      uint64_t size,
368                      uint64_t skip,
369                      uint64_t offset,
370                      size_t key_size,
371                      const char *key,
372                      int read_only,
373                      int reload)
374 {
375         struct dm_task *dmt = NULL;
376         struct dm_info dmi;
377         char *params = NULL;
378         char *error = NULL;
379         char dev_uuid[DM_UUID_LEN] = {0};
380         int r = -EINVAL;
381         uint32_t read_ahead = 0;
382         uint32_t cookie = 0;
383         uint16_t udev_flags = 0;
384
385         params = get_params(device, skip, offset, cipher, key_size, key);
386         if (!params)
387                 goto out_no_removal;
388
389         if (type && !strncmp(type, "TEMP", 4))
390                 udev_flags = CRYPT_TEMP_UDEV_FLAGS;
391
392         /* All devices must have DM_UUID, only resize on old device is exception */
393         if (reload) {
394                 if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
395                         goto out_no_removal;
396
397                 if (!dm_task_set_name(dmt, name))
398                         goto out_no_removal;
399         } else {
400                 dm_prepare_uuid(name, type, uuid, dev_uuid, sizeof(dev_uuid));
401
402                 if (!(dmt = dm_task_create(DM_DEVICE_CREATE)))
403                         goto out_no_removal;
404
405                 if (!dm_task_set_name(dmt, name))
406                         goto out_no_removal;
407
408                 if (!dm_task_set_uuid(dmt, dev_uuid))
409                         goto out_no_removal;
410
411                 if (_dm_use_udev() && !dm_task_set_cookie(dmt, &cookie, udev_flags))
412                         goto out_no_removal;
413         }
414
415         if (read_only && !dm_task_set_ro(dmt))
416                 goto out_no_removal;
417         if (!dm_task_add_target(dmt, 0, size, DM_CRYPT_TARGET, params))
418                 goto out_no_removal;
419
420 #ifdef DM_READ_AHEAD_MINIMUM_FLAG
421         if (_dev_read_ahead(device, &read_ahead) &&
422             !dm_task_set_read_ahead(dmt, read_ahead, DM_READ_AHEAD_MINIMUM_FLAG))
423                 goto out_no_removal;
424 #endif
425
426         if (!dm_task_run(dmt))
427                 goto out_no_removal;
428
429         if (reload) {
430                 dm_task_destroy(dmt);
431                 if (!(dmt = dm_task_create(DM_DEVICE_RESUME)))
432                         goto out;
433                 if (!dm_task_set_name(dmt, name))
434                         goto out;
435                 if (uuid && !dm_task_set_uuid(dmt, dev_uuid))
436                         goto out;
437                 if (_dm_use_udev() && !dm_task_set_cookie(dmt, &cookie, udev_flags))
438                         goto out;
439                 if (!dm_task_run(dmt))
440                         goto out;
441         }
442
443         if (!dm_task_get_info(dmt, &dmi))
444                 goto out;
445
446         r = 0;
447 out:
448         if (_dm_use_udev()) {
449                 (void)dm_udev_wait(cookie);
450                 cookie = 0;
451         }
452
453         if (r < 0 && !reload) {
454                 if (get_error())
455                         error = strdup(get_error());
456
457                 dm_remove_device(name, 0, 0);
458
459                 if (error) {
460                         set_error(error);
461                         free(error);
462                 }
463         }
464
465 out_no_removal:
466         if (cookie && _dm_use_udev())
467                 (void)dm_udev_wait(cookie);
468
469         if (params)
470                 safe_free(params);
471         if (dmt)
472                 dm_task_destroy(dmt);
473
474         dm_task_update_nodes();
475         return r;
476 }
477
478 int dm_status_device(const char *name)
479 {
480         struct dm_task *dmt;
481         struct dm_info dmi;
482         uint64_t start, length;
483         char *target_type, *params;
484         void *next = NULL;
485         int r = -EINVAL;
486
487         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
488                 return -EINVAL;
489
490         if (!dm_task_set_name(dmt, name)) {
491                 r = -EINVAL;
492                 goto out;
493         }
494
495         if (!dm_task_run(dmt)) {
496                 r = -EINVAL;
497                 goto out;
498         }
499
500         if (!dm_task_get_info(dmt, &dmi)) {
501                 r = -EINVAL;
502                 goto out;
503         }
504
505         if (!dmi.exists) {
506                 r = -ENODEV;
507                 goto out;
508         }
509
510         next = dm_get_next_target(dmt, next, &start, &length,
511                                   &target_type, &params);
512         if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
513             start != 0 || next)
514                 r = -EINVAL;
515         else
516                 r = (dmi.open_count > 0);
517 out:
518         if (dmt)
519                 dm_task_destroy(dmt);
520
521         return r;
522 }
523
524 int dm_query_device(const char *name,
525                     char **device,
526                     uint64_t *size,
527                     uint64_t *skip,
528                     uint64_t *offset,
529                     char **cipher,
530                     int *key_size,
531                     char **key,
532                     int *read_only,
533                     int *suspended,
534                     char **uuid)
535 {
536         struct dm_task *dmt;
537         struct dm_info dmi;
538         uint64_t start, length, val64;
539         char *target_type, *params, *rcipher, *key_, *rdevice, *endp, buffer[3], *tmp_uuid;
540         void *next = NULL;
541         int i, r = -EINVAL;
542
543         if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
544                 goto out;
545         if (!dm_task_set_name(dmt, name))
546                 goto out;
547         r = -ENODEV;
548         if (!dm_task_run(dmt))
549                 goto out;
550
551         r = -EINVAL;
552         if (!dm_task_get_info(dmt, &dmi))
553                 goto out;
554
555         if (!dmi.exists) {
556                 r = -ENODEV;
557                 goto out;
558         }
559
560         next = dm_get_next_target(dmt, next, &start, &length,
561                                   &target_type, &params);
562         if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
563             start != 0 || next)
564                 goto out;
565
566         if (size)
567                 *size = length;
568
569         rcipher = strsep(&params, " ");
570         /* cipher */
571         if (cipher)
572                 *cipher = strdup(rcipher);
573
574         /* skip */
575         key_ = strsep(&params, " ");
576         if (!params)
577                 goto out;
578         val64 = strtoull(params, &params, 10);
579         if (*params != ' ')
580                 goto out;
581         params++;
582         if (skip)
583                 *skip = val64;
584
585         /* device */
586         rdevice = strsep(&params, " ");
587         if (device)
588                 *device = lookup_dev(rdevice);
589
590         /*offset */
591         if (!params)
592                 goto out;
593         val64 = strtoull(params, &params, 10);
594         if (*params)
595                 goto out;
596         if (offset)
597                 *offset = val64;
598
599         /* key_size */
600         if (key_size)
601                 *key_size = strlen(key_) / 2;
602
603         /* key */
604         if (key_size && key) {
605                 *key = safe_alloc(*key_size);
606                 if (!*key) {
607                         r = -ENOMEM;
608                         goto out;
609                 }
610
611                 buffer[2] = '\0';
612                 for(i = 0; i < *key_size; i++) {
613                         memcpy(buffer, &key_[i * 2], 2);
614                         (*key)[i] = strtoul(buffer, &endp, 16);
615                         if (endp != &buffer[2]) {
616                                 safe_free(key);
617                                 *key = NULL;
618                                 goto out;
619                         }
620                 }
621         }
622         memset(key_, 0, strlen(key_));
623
624         if (read_only)
625                 *read_only = dmi.read_only;
626
627         if (suspended)
628                 *suspended = dmi.suspended;
629
630         if (uuid && (tmp_uuid = (char*)dm_task_get_uuid(dmt)) &&
631             !strncmp(tmp_uuid, DM_UUID_PREFIX, DM_UUID_PREFIX_LEN))
632                 *uuid = strdup(tmp_uuid + DM_UUID_PREFIX_LEN);
633
634         r = (dmi.open_count > 0);
635 out:
636         if (dmt)
637                 dm_task_destroy(dmt);
638
639         return r;
640 }
641
642 static int _dm_message(const char *name, const char *msg)
643 {
644         int r = 0;
645         struct dm_task *dmt;
646
647         if (!(dmt = dm_task_create(DM_DEVICE_TARGET_MSG)))
648                 return 0;
649
650         if (name && !dm_task_set_name(dmt, name))
651                 goto out;
652
653         if (!dm_task_set_sector(dmt, (uint64_t) 0))
654                 goto out;
655
656         if (!dm_task_set_message(dmt, msg))
657                 goto out;
658
659         r = dm_task_run(dmt);
660
661       out:
662         dm_task_destroy(dmt);
663         return r;
664 }
665
666 int dm_suspend_and_wipe_key(const char *name)
667 {
668         if (!_dm_simple(DM_DEVICE_SUSPEND, name, 0))
669                 return -EINVAL;
670
671         if (!_dm_message(name, "key wipe")) {
672                 _dm_simple(DM_DEVICE_RESUME, name, 1);
673                 return -EINVAL;
674         }
675
676         return 0;
677 }
678
679 int dm_resume_and_reinstate_key(const char *name,
680                                 size_t key_size,
681                                 const char *key)
682 {
683         int msg_size = key_size * 2 + 10; // key set <key>
684         char *msg;
685         int r = 0;
686
687         msg = safe_alloc(msg_size);
688         if (!msg)
689                 return -ENOMEM;
690
691         memset(msg, 0, msg_size);
692         strcpy(msg, "key set ");
693         hex_key(&msg[8], key_size, key);
694
695         if (!_dm_message(name, msg) ||
696             !_dm_simple(DM_DEVICE_RESUME, name, 1))
697                 r = -EINVAL;
698
699         safe_free(msg);
700         return r;
701 }
702
703 const char *dm_get_dir(void)
704 {
705         return dm_dir();
706 }