Add support for automatic loop device use (image infile etc).
[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 = 0;
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 -EINVAL;
249         }
250
251         if (!S_ISBLK(st.st_mode))
252                 return -ENOTBLK;
253
254         log_dbg("Trying to open and read device %s.", device);
255         devfd = open(device, mode | O_DIRECT | O_SYNC);
256         if(devfd < 0) {
257                 log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
258                         (mode & O_EXCL) ? _("exclusive ") : "",
259                         (mode & O_RDWR) ? _("writable") : _("read-only"));
260                 return -EINVAL;
261         }
262
263          /* Try to read first sector */
264         s = read_blockwise(devfd, buf, sizeof(buf));
265         if (s < 0 || s != sizeof(buf)) {
266                 log_verbose(cd, _("Cannot read device %s.\n"), device);
267                 r = -EIO;
268         }
269
270         memset(buf, 0, sizeof(buf));
271         close(devfd);
272
273         return r;
274 }
275
276 int get_device_infos(const char *device,
277                      int open_exclusive,
278                      int *readonly,
279                      uint64_t *size)
280 {
281         struct stat st;
282         unsigned long size_small;
283         int fd, r = -1;
284         int flags = 0;
285
286         *readonly = 0;
287         *size = 0;
288
289         if (stat(device, &st) < 0)
290                 return -EINVAL;
291
292         /* never wipe header on mounted device */
293         if (open_exclusive && S_ISBLK(st.st_mode))
294                 flags |= O_EXCL;
295
296         /* Try to open read-write to check whether it is a read-only device */
297         fd = open(device, O_RDWR | flags);
298         if (fd == -1 && errno == EROFS) {
299                 *readonly = 1;
300                 fd = open(device, O_RDONLY | flags);
301         }
302
303         if (fd == -1 && open_exclusive && errno == EBUSY)
304                 return -EBUSY;
305
306         if (fd == -1)
307                 return -EINVAL;
308
309 #ifdef BLKROGET
310         /* If the device can be opened read-write, i.e. readonly is still 0, then
311          * check whether BKROGET says that it is read-only. E.g. read-only loop
312          * devices may be openend read-write but are read-only according to BLKROGET
313          */
314         if (*readonly == 0 && (r = ioctl(fd, BLKROGET, readonly)) < 0)
315                 goto out;
316 #else
317 #error BLKROGET not available
318 #endif
319
320 #ifdef BLKGETSIZE64
321         if (ioctl(fd, BLKGETSIZE64, size) >= 0) {
322                 *size >>= SECTOR_SHIFT;
323                 r = 0;
324                 goto out;
325         }
326 #endif
327
328 #ifdef BLKGETSIZE
329         if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
330                 *size = (uint64_t)size_small;
331                 r = 0;
332                 goto out;
333         }
334
335 #else
336 #       error Need at least the BLKGETSIZE ioctl!
337 #endif
338         r = -EINVAL;
339 out:
340         close(fd);
341         return r;
342 }
343
344 int device_check_and_adjust(struct crypt_device *cd,
345                             const char *device,
346                             int open_exclusive,
347                             uint64_t *size,
348                             uint64_t *offset,
349                             int *read_only)
350 {
351         int r, real_readonly;
352         uint64_t real_size;
353
354         if (!device)
355                 return -ENOTBLK;
356
357         r = get_device_infos(device, open_exclusive, &real_readonly, &real_size);
358         if (r < 0) {
359                 if (r == -EBUSY)
360                         log_err(cd, _("Cannot use device %s which is in use "
361                                       "(already mapped or mounted).\n"),
362                                       device);
363                 else
364                         log_err(cd, _("Cannot get info about device %s.\n"),
365                                 device);
366                 return r;
367         }
368
369         if (!*size) {
370                 *size = real_size;
371                 if (!*size) {
372                         log_err(cd, _("Device %s has zero size.\n"), device);
373                         return -ENOTBLK;
374                 }
375                 if (*size < *offset) {
376                         log_err(cd, _("Device %s is too small.\n"), device);
377                         return -EINVAL;
378                 }
379                 *size -= *offset;
380         }
381
382         if (real_readonly)
383                 *read_only = 1;
384
385         log_dbg("Calculated device size is %" PRIu64 " sectors (%s), offset %" PRIu64 ".",
386                 *size, *read_only ? "RO" : "RW", *offset);
387         return 0;
388 }
389
390 int wipe_device_header(const char *device, int sectors)
391 {
392         struct stat st;
393         char *buffer;
394         int size = sectors * SECTOR_SIZE;
395         int r = -1;
396         int devfd;
397         int flags = O_RDWR | O_DIRECT | O_SYNC;
398
399         if (stat(device, &st) < 0)
400                 return -EINVAL;
401
402         /* never wipe header on mounted device */
403         if (S_ISBLK(st.st_mode))
404                 flags |= O_EXCL;
405
406         devfd = open(device, flags);
407         if(devfd == -1)
408                 return errno == EBUSY ? -EBUSY : -EINVAL;
409
410         buffer = malloc(size);
411         if (!buffer) {
412                 close(devfd);
413                 return -ENOMEM;
414         }
415         memset(buffer, 0, size);
416
417         r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
418
419         free(buffer);
420         close(devfd);
421
422         return r;
423 }
424
425 /* MEMLOCK */
426 #define DEFAULT_PROCESS_PRIORITY -18
427
428 static int _priority;
429 static int _memlock_count = 0;
430
431 // return 1 if memory is locked
432 int crypt_memlock_inc(struct crypt_device *ctx)
433 {
434         if (!_memlock_count++) {
435                 log_dbg("Locking memory.");
436                 if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
437                         log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
438                         _memlock_count--;
439                         return 0;
440                 }
441                 errno = 0;
442                 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
443                         log_err(ctx, _("Cannot get process priority.\n"));
444                 else
445                         if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
446                                 log_err(ctx, _("setpriority %d failed: %s\n"),
447                                         DEFAULT_PROCESS_PRIORITY, strerror(errno));
448         }
449         return _memlock_count ? 1 : 0;
450 }
451
452 int crypt_memlock_dec(struct crypt_device *ctx)
453 {
454         if (_memlock_count && (!--_memlock_count)) {
455                 log_dbg("Unlocking memory.");
456                 if (munlockall() == -1)
457                         log_err(ctx, _("Cannot unlock memory.\n"));
458                 if (setpriority(PRIO_PROCESS, 0, _priority))
459                         log_err(ctx, _("setpriority %d failed: %s\n"), _priority, strerror(errno));
460         }
461         return _memlock_count ? 1 : 0;
462 }
463
464 /* DEVICE TOPOLOGY */
465
466 /* block device topology ioctls, introduced in 2.6.32 */
467 #ifndef BLKIOMIN
468 #define BLKIOMIN    _IO(0x12,120)
469 #define BLKIOOPT    _IO(0x12,121)
470 #define BLKALIGNOFF _IO(0x12,122)
471 #endif
472
473 void get_topology_alignment(const char *device,
474                             unsigned long *required_alignment, /* bytes */
475                             unsigned long *alignment_offset,   /* bytes */
476                             unsigned long default_alignment)
477 {
478         int dev_alignment_offset = 0;
479         unsigned int min_io_size = 0, opt_io_size = 0;
480         unsigned long temp_alignment = 0;
481         int fd;
482
483         *required_alignment = default_alignment;
484         *alignment_offset = 0;
485
486         fd = open(device, O_RDONLY);
487         if (fd == -1)
488                 return;
489
490         /* minimum io size */
491         if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
492                 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
493                         device, default_alignment);
494                 goto out;
495         }
496
497         /* optimal io size */
498         if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
499                 opt_io_size = min_io_size;
500
501         /* alignment offset, bogus -1 means misaligned/unknown */
502         if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
503                 dev_alignment_offset = 0;
504         *alignment_offset = (unsigned long)dev_alignment_offset;
505
506         temp_alignment = (unsigned long)min_io_size;
507
508         if (temp_alignment < (unsigned long)opt_io_size)
509                 temp_alignment = (unsigned long)opt_io_size;
510
511         /* If calculated alignment is multiple of default, keep default */
512         if (temp_alignment && (default_alignment % temp_alignment))
513                 *required_alignment = temp_alignment;
514
515         log_dbg("Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
516                 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
517 out:
518         (void)close(fd);
519 }