* Implement --use-random and --use-urandom for luksFormat to allow setting of RNG...
[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                         goto out;
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, struct device_infos *infos, struct crypt_device *cd)
274 {
275         uint64_t size;
276         unsigned long size_small;
277         int readonly = 0;
278         int ret = -1;
279         int fd;
280
281         /* Try to open read-write to check whether it is a read-only device */
282         fd = open(device, O_RDWR);
283         if (fd < 0) {
284                 if (errno == EROFS) {
285                         readonly = 1;
286                         fd = open(device, O_RDONLY);
287                 }
288         } else {
289                 close(fd);
290                 fd = open(device, O_RDONLY);
291         }
292         if (fd < 0) {
293                 log_err(cd, _("Cannot open device: %s\n"), device);
294                 return -1;
295         }
296
297 #ifdef BLKROGET
298         /* If the device can be opened read-write, i.e. readonly is still 0, then
299          * check whether BKROGET says that it is read-only. E.g. read-only loop
300          * devices may be openend read-write but are read-only according to BLKROGET
301          */
302         if (readonly == 0 && ioctl(fd, BLKROGET, &readonly) < 0) {
303                 log_err(cd, _("BLKROGET failed on device %s.\n"), device);
304                 goto out;
305         }
306 #else
307 #error BLKROGET not available
308 #endif
309
310 #ifdef BLKGETSIZE64
311         if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
312                 size >>= SECTOR_SHIFT;
313                 ret = 0;
314                 goto out;
315         }
316 #endif
317
318 #ifdef BLKGETSIZE
319         if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
320                 size = (uint64_t)size_small;
321                 ret = 0;
322                 goto out;
323         }
324 #else
325 #       error Need at least the BLKGETSIZE ioctl!
326 #endif
327
328         log_err(cd, _("BLKGETSIZE failed on device %s.\n"), device);
329 out:
330         if (ret == 0) {
331                 infos->size = size;
332                 infos->readonly = readonly;
333         }
334         close(fd);
335         return ret;
336 }
337
338 int wipe_device_header(const char *device, int sectors)
339 {
340         char *buffer;
341         int size = sectors * SECTOR_SIZE;
342         int r = -1;
343         int devfd;
344
345         devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
346         if(devfd == -1)
347                 return -EINVAL;
348
349         buffer = malloc(size);
350         if (!buffer) {
351                 close(devfd);
352                 return -ENOMEM;
353         }
354         memset(buffer, 0, size);
355
356         r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
357
358         free(buffer);
359         close(devfd);
360
361         return r;
362 }
363
364 /* MEMLOCK */
365 #define DEFAULT_PROCESS_PRIORITY -18
366
367 static int _priority;
368 static int _memlock_count = 0;
369
370 // return 1 if memory is locked
371 int crypt_memlock_inc(struct crypt_device *ctx)
372 {
373         if (!_memlock_count++) {
374                 log_dbg("Locking memory.");
375                 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
376                         log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
377                         _memlock_count--;
378                         return 0;
379                 }
380                 errno = 0;
381                 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
382                         log_err(ctx, _("Cannot get process priority.\n"));
383                 else
384                         if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
385                                 log_err(ctx, _("setpriority %u failed: %s"),
386                                         DEFAULT_PROCESS_PRIORITY, strerror(errno));
387         }
388         return _memlock_count ? 1 : 0;
389 }
390
391 int crypt_memlock_dec(struct crypt_device *ctx)
392 {
393         if (_memlock_count && (!--_memlock_count)) {
394                 log_dbg("Unlocking memory.");
395                 if (munlockall())
396                         log_err(ctx, _("Cannot unlock memory."));
397                 if (setpriority(PRIO_PROCESS, 0, _priority))
398                         log_err(ctx, _("setpriority %u failed: %s"), _priority, strerror(errno));
399         }
400         return _memlock_count ? 1 : 0;
401 }
402
403 /* DEVICE TOPOLOGY */
404
405 /* block device topology ioctls, introduced in 2.6.32 */
406 #ifndef BLKIOMIN
407 #define BLKIOMIN    _IO(0x12,120)
408 #define BLKIOOPT    _IO(0x12,121)
409 #define BLKALIGNOFF _IO(0x12,122)
410 #endif
411
412 void get_topology_alignment(const char *device,
413                             unsigned long *required_alignment, /* bytes */
414                             unsigned long *alignment_offset,   /* bytes */
415                             unsigned long default_alignment)
416 {
417         int dev_alignment_offset = 0;
418         unsigned int min_io_size = 0, opt_io_size = 0;
419         unsigned long temp_alignment = 0;
420         int fd;
421
422         *required_alignment = default_alignment;
423         *alignment_offset = 0;
424
425         fd = open(device, O_RDONLY);
426         if (fd == -1)
427                 return;
428
429         /* minimum io size */
430         if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
431                 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
432                         device, default_alignment);
433                 goto out;
434         }
435
436         /* optimal io size */
437         if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
438                 opt_io_size = min_io_size;
439
440         /* alignment offset, bogus -1 means misaligned/unknown */
441         if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
442                 dev_alignment_offset = 0;
443         *alignment_offset = (unsigned long)dev_alignment_offset;
444
445         temp_alignment = (unsigned long)min_io_size;
446
447         if (temp_alignment < (unsigned long)opt_io_size)
448                 temp_alignment = (unsigned long)opt_io_size;
449
450         /* If calculated alignment is multiple of default, keep default */
451         if (temp_alignment && (default_alignment % temp_alignment))
452                 *required_alignment = temp_alignment;
453
454         log_dbg("Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
455                 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
456 out:
457         (void)close(fd);
458 }