Add dm flags for query for features.
[platform/upstream/cryptsetup.git] / lib / utils.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stddef.h>
5 #include <stdarg.h>
6 #include <errno.h>
7 #include <linux/fs.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <sys/ioctl.h>
13 #include <fcntl.h>
14 #include <sys/mman.h>
15 #include <sys/resource.h>
16
17 #include "libcryptsetup.h"
18 #include "internal.h"
19
20 static char *error=NULL;
21
22 void set_error_va(const char *fmt, va_list va)
23 {
24         int r;
25
26         if(error) {
27                 free(error);
28                 error = NULL;
29         }
30
31         if(!fmt) return;
32
33         r = vasprintf(&error, fmt, va);
34         if (r < 0) {
35                 free(error);
36                 error = NULL;
37                 return;
38         }
39
40         if (r && error[r - 1] == '\n')
41                 error[r - 1] = '\0';
42 }
43
44 void set_error(const char *fmt, ...)
45 {
46         va_list va;
47
48         va_start(va, fmt);
49         set_error_va(fmt, va);
50         va_end(va);
51 }
52
53 const char *get_error(void)
54 {
55         return error;
56 }
57
58 static int get_alignment(int fd)
59 {
60         int alignment = DEFAULT_MEM_ALIGNMENT;
61
62 #ifdef _PC_REC_XFER_ALIGN
63         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
64         if (alignment < 0)
65                 alignment = DEFAULT_MEM_ALIGNMENT;
66 #endif
67         return alignment;
68 }
69
70 static void *aligned_malloc(void **base, int size, int alignment)
71 {
72 #ifdef HAVE_POSIX_MEMALIGN
73         return posix_memalign(base, alignment, size) ? NULL : *base;
74 #else
75 /* Credits go to Michal's padlock patches for this alignment code */
76         char *ptr;
77
78         ptr  = malloc(size + alignment);
79         if(ptr == NULL) return NULL;
80
81         *base = ptr;
82         if(alignment > 1 && ((long)ptr & (alignment - 1))) {
83                 ptr += alignment - ((long)(ptr) & (alignment - 1));
84         }
85         return ptr;
86 #endif
87 }
88 static int sector_size(int fd) 
89 {
90         int bsize;
91         if (ioctl(fd,BLKSSZGET, &bsize) < 0)
92                 return -EINVAL;
93         else
94                 return bsize;
95 }
96
97 int sector_size_for_device(const char *device)
98 {
99         int fd = open(device, O_RDONLY);
100         int r;
101         if(fd < 0)
102                 return -EINVAL;
103         r = sector_size(fd);
104         close(fd);
105         return r;
106 }
107
108 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
109 {
110         void *hangover_buf, *hangover_buf_base = NULL;
111         void *buf, *buf_base = NULL;
112         int r, hangover, solid, bsize, alignment;
113         ssize_t ret = -1;
114
115         if ((bsize = sector_size(fd)) < 0)
116                 return bsize;
117
118         hangover = count % bsize;
119         solid = count - hangover;
120         alignment = get_alignment(fd);
121
122         if ((long)orig_buf & (alignment - 1)) {
123                 buf = aligned_malloc(&buf_base, count, alignment);
124                 if (!buf)
125                         goto out;
126                 memcpy(buf, orig_buf, count);
127         } else
128                 buf = (void *)orig_buf;
129
130         r = write(fd, buf, solid);
131         if (r < 0 || r != solid)
132                 goto out;
133
134         if (hangover) {
135                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
136                 if (!hangover_buf)
137                         goto out;
138
139                 r = read(fd, hangover_buf, bsize);
140                 if(r < 0 || r != bsize) goto out;
141
142                 r = lseek(fd, -bsize, SEEK_CUR);
143                 if (r < 0)
144                         goto out;
145                 memcpy(hangover_buf, buf + solid, hangover);
146
147                 r = write(fd, hangover_buf, bsize);
148                 if(r < 0 || r != bsize) goto out;
149                 free(hangover_buf_base);
150         }
151         ret = count;
152  out:
153         if (buf != orig_buf)
154                 free(buf_base);
155         return ret;
156 }
157
158 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
159         void *hangover_buf, *hangover_buf_base;
160         void *buf, *buf_base = NULL;
161         int r, hangover, solid, bsize, alignment;
162         ssize_t ret = -1;
163
164         if ((bsize = sector_size(fd)) < 0)
165                 return bsize;
166
167         hangover = count % bsize;
168         solid = count - hangover;
169         alignment = get_alignment(fd);
170
171         if ((long)orig_buf & (alignment - 1)) {
172                 buf = aligned_malloc(&buf_base, count, alignment);
173                 if (!buf)
174                         return -1;
175         } else
176                 buf = orig_buf;
177
178         r = read(fd, buf, solid);
179         if(r < 0 || r != solid)
180                 goto out;
181
182         if (hangover) {
183                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
184                 if (!hangover_buf)
185                         goto out;
186                 r = read(fd, hangover_buf, bsize);
187                 if (r <  0 || r != bsize)
188                         goto out;
189
190                 memcpy(buf + solid, hangover_buf, hangover);
191                 free(hangover_buf_base);
192         }
193         ret = count;
194  out:
195         if (buf != orig_buf) {
196                 memcpy(orig_buf, buf, count);
197                 free(buf_base);
198         }
199         return ret;
200 }
201
202 /* 
203  * Combines llseek with blockwise write. write_blockwise can already deal with short writes
204  * but we also need a function to deal with short writes at the start. But this information
205  * is implicitly included in the read/write offset, which can not be set to non-aligned 
206  * boundaries. Hence, we combine llseek with write.
207  */
208
209 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
210         int bsize = sector_size(fd);
211         const char *orig_buf = buf;
212         char frontPadBuf[bsize];
213         int frontHang = offset % bsize;
214         int r;
215         int innerCount = count < bsize ? count : bsize;
216
217         if (bsize < 0)
218                 return bsize;
219
220         lseek(fd, offset - frontHang, SEEK_SET);
221         if(offset % bsize) {
222                 r = read(fd,frontPadBuf,bsize);
223                 if(r < 0) return -1;
224
225                 memcpy(frontPadBuf+frontHang, buf, innerCount);
226
227                 lseek(fd, offset - frontHang, SEEK_SET);
228                 r = write(fd,frontPadBuf,bsize);
229                 if(r < 0) return -1;
230
231                 buf += innerCount;
232                 count -= innerCount;
233         }
234         if(count <= 0) return buf - orig_buf;
235
236         return write_blockwise(fd, buf, count) + innerCount;
237 }
238
239 int device_ready(struct crypt_device *cd, const char *device, int mode)
240 {
241         int devfd, r = 1;
242         ssize_t s;
243         struct stat st;
244         char buf[512];
245
246         if(stat(device, &st) < 0) {
247                 log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
248                 return 0;
249         }
250
251         log_dbg("Trying to open and read device %s.", device);
252         devfd = open(device, mode | O_DIRECT | O_SYNC);
253         if(devfd < 0) {
254                 log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
255                         (mode & O_EXCL) ? _("exclusive ") : "",
256                         (mode & O_RDWR) ? _("writable") : _("read-only"));
257                 return 0;
258         }
259
260          /* Try to read first sector */
261         s = read_blockwise(devfd, buf, sizeof(buf));
262         if (s < 0 || s != sizeof(buf)) {
263                 log_err(cd, _("Cannot read device %s.\n"), device);
264                 r = 0;
265         }
266
267         memset(buf, 0, sizeof(buf));
268         close(devfd);
269
270         return r;
271 }
272
273 int get_device_infos(const char *device,
274                      int open_exclusive,
275                      int *readonly,
276                      uint64_t *size)
277 {
278         struct stat st;
279         unsigned long size_small;
280         int fd, r = -1;
281         int flags = 0;
282
283         *readonly = 0;
284         *size = 0;
285
286         if (stat(device, &st) < 0)
287                 return -EINVAL;
288
289         /* never wipe header on mounted device */
290         if (open_exclusive && S_ISBLK(st.st_mode))
291                 flags |= O_EXCL;
292
293         /* Try to open read-write to check whether it is a read-only device */
294         fd = open(device, O_RDWR | flags);
295         if (fd == -1 && errno == EROFS) {
296                 *readonly = 1;
297                 fd = open(device, O_RDONLY | flags);
298         }
299
300         if (fd == -1 && open_exclusive && errno == EBUSY)
301                 return -EBUSY;
302
303         if (fd == -1)
304                 return -EINVAL;
305
306 #ifdef BLKROGET
307         /* If the device can be opened read-write, i.e. readonly is still 0, then
308          * check whether BKROGET says that it is read-only. E.g. read-only loop
309          * devices may be openend read-write but are read-only according to BLKROGET
310          */
311         if (*readonly == 0 && (r = ioctl(fd, BLKROGET, readonly)) < 0)
312                 goto out;
313 #else
314 #error BLKROGET not available
315 #endif
316
317 #ifdef BLKGETSIZE64
318         if (ioctl(fd, BLKGETSIZE64, size) >= 0) {
319                 *size >>= SECTOR_SHIFT;
320                 r = 0;
321                 goto out;
322         }
323 #endif
324
325 #ifdef BLKGETSIZE
326         if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
327                 *size = (uint64_t)size_small;
328                 r = 0;
329                 goto out;
330         }
331
332 #else
333 #       error Need at least the BLKGETSIZE ioctl!
334 #endif
335         r = -EINVAL;
336 out:
337         close(fd);
338         return r;
339 }
340
341 int device_check_and_adjust(struct crypt_device *cd,
342                             const char *device,
343                             int open_exclusive,
344                             uint64_t *size,
345                             uint64_t *offset,
346                             int *read_only)
347 {
348         int r, real_readonly;
349         uint64_t real_size;
350
351         if (!device)
352                 return -ENOTBLK;
353
354         r = get_device_infos(device, open_exclusive, &real_readonly, &real_size);
355         if (r < 0) {
356                 if (r == -EBUSY)
357                         log_err(cd, _("Cannot use device %s which is in use "
358                                       "(already mapped or mounted).\n"),
359                                       device);
360                 else
361                         log_err(cd, _("Cannot get info about device %s.\n"),
362                                 device);
363                 return r;
364         }
365
366         if (!*size) {
367                 *size = real_size;
368                 if (!*size) {
369                         log_err(cd, _("Device %s has zero size.\n"), device);
370                         return -ENOTBLK;
371                 }
372                 if (*size < *offset) {
373                         log_err(cd, _("Device %s is too small.\n"), device);
374                         return -EINVAL;
375                 }
376                 *size -= *offset;
377         }
378
379         if (real_readonly)
380                 *read_only = 1;
381
382         log_dbg("Calculated device size is %" PRIu64 " sectors (%s), offset %" PRIu64 ".",
383                 *size, *read_only ? "RO" : "RW", *offset);
384         return 0;
385 }
386
387 int wipe_device_header(const char *device, int sectors)
388 {
389         struct stat st;
390         char *buffer;
391         int size = sectors * SECTOR_SIZE;
392         int r = -1;
393         int devfd;
394         int flags = O_RDWR | O_DIRECT | O_SYNC;
395
396         if (stat(device, &st) < 0)
397                 return -EINVAL;
398
399         /* never wipe header on mounted device */
400         if (S_ISBLK(st.st_mode))
401                 flags |= O_EXCL;
402
403         devfd = open(device, flags);
404         if(devfd == -1)
405                 return errno == EBUSY ? -EBUSY : -EINVAL;
406
407         buffer = malloc(size);
408         if (!buffer) {
409                 close(devfd);
410                 return -ENOMEM;
411         }
412         memset(buffer, 0, size);
413
414         r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
415
416         free(buffer);
417         close(devfd);
418
419         return r;
420 }
421
422 /* MEMLOCK */
423 #define DEFAULT_PROCESS_PRIORITY -18
424
425 static int _priority;
426 static int _memlock_count = 0;
427
428 // return 1 if memory is locked
429 int crypt_memlock_inc(struct crypt_device *ctx)
430 {
431         if (!_memlock_count++) {
432                 log_dbg("Locking memory.");
433                 if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
434                         log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
435                         _memlock_count--;
436                         return 0;
437                 }
438                 errno = 0;
439                 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
440                         log_err(ctx, _("Cannot get process priority.\n"));
441                 else
442                         if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
443                                 log_err(ctx, _("setpriority %d failed: %s\n"),
444                                         DEFAULT_PROCESS_PRIORITY, strerror(errno));
445         }
446         return _memlock_count ? 1 : 0;
447 }
448
449 int crypt_memlock_dec(struct crypt_device *ctx)
450 {
451         if (_memlock_count && (!--_memlock_count)) {
452                 log_dbg("Unlocking memory.");
453                 if (munlockall() == -1)
454                         log_err(ctx, _("Cannot unlock memory.\n"));
455                 if (setpriority(PRIO_PROCESS, 0, _priority))
456                         log_err(ctx, _("setpriority %d failed: %s\n"), _priority, strerror(errno));
457         }
458         return _memlock_count ? 1 : 0;
459 }
460
461 /* DEVICE TOPOLOGY */
462
463 /* block device topology ioctls, introduced in 2.6.32 */
464 #ifndef BLKIOMIN
465 #define BLKIOMIN    _IO(0x12,120)
466 #define BLKIOOPT    _IO(0x12,121)
467 #define BLKALIGNOFF _IO(0x12,122)
468 #endif
469
470 void get_topology_alignment(const char *device,
471                             unsigned long *required_alignment, /* bytes */
472                             unsigned long *alignment_offset,   /* bytes */
473                             unsigned long default_alignment)
474 {
475         int dev_alignment_offset = 0;
476         unsigned int min_io_size = 0, opt_io_size = 0;
477         unsigned long temp_alignment = 0;
478         int fd;
479
480         *required_alignment = default_alignment;
481         *alignment_offset = 0;
482
483         fd = open(device, O_RDONLY);
484         if (fd == -1)
485                 return;
486
487         /* minimum io size */
488         if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
489                 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
490                         device, default_alignment);
491                 goto out;
492         }
493
494         /* optimal io size */
495         if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
496                 opt_io_size = min_io_size;
497
498         /* alignment offset, bogus -1 means misaligned/unknown */
499         if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
500                 dev_alignment_offset = 0;
501         *alignment_offset = (unsigned long)dev_alignment_offset;
502
503         temp_alignment = (unsigned long)min_io_size;
504
505         if (temp_alignment < (unsigned long)opt_io_size)
506                 temp_alignment = (unsigned long)opt_io_size;
507
508         /* If calculated alignment is multiple of default, keep default */
509         if (temp_alignment && (default_alignment % temp_alignment))
510                 *required_alignment = temp_alignment;
511
512         log_dbg("Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
513                 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
514 out:
515         (void)close(fd);
516 }