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