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