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