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