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