Optimize o_direct read/writes.
[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 <termios.h>
15
16 #include "libcryptsetup.h"
17 #include "internal.h"
18
19
20 struct safe_allocation {
21         size_t  size;
22         char    data[1];
23 };
24
25 static char *error=NULL;
26
27 void set_error_va(const char *fmt, va_list va)
28 {
29
30         if(error) {
31             free(error);
32             error=NULL;
33         }
34
35         if(!fmt) return;
36
37         if (vasprintf(&error, fmt, va) < 0) {
38                 free(error);
39                 error = NULL;
40         }
41 }
42
43 void set_error(const char *fmt, ...)
44 {
45         va_list va;
46
47         va_start(va, fmt);
48         set_error_va(fmt, va);
49         va_end(va);
50 }
51
52 const char *get_error(void)
53 {
54         return error;
55 }
56
57 void *safe_alloc(size_t size)
58 {
59         struct safe_allocation *alloc;
60
61         if (!size)
62                 return NULL;
63
64         alloc = malloc(size + offsetof(struct safe_allocation, data));
65         if (!alloc)
66                 return NULL;
67
68         alloc->size = size;
69
70         return &alloc->data;
71 }
72
73 void safe_free(void *data)
74 {
75         struct safe_allocation *alloc;
76
77         if (!data)
78                 return;
79
80         alloc = data - offsetof(struct safe_allocation, data);
81
82         memset(data, 0, alloc->size);
83
84         alloc->size = 0x55aa55aa;
85         free(alloc);
86 }
87
88 void *safe_realloc(void *data, size_t size)
89 {
90         void *new_data;
91
92         new_data = safe_alloc(size);
93
94         if (new_data && data) {
95                 struct safe_allocation *alloc;
96
97                 alloc = data - offsetof(struct safe_allocation, data);
98
99                 if (size > alloc->size)
100                         size = alloc->size;
101
102                 memcpy(new_data, data, size);
103         }
104
105         safe_free(data);
106         return new_data;
107 }
108
109 char *safe_strdup(const char *s)
110 {
111         char *s2 = safe_alloc(strlen(s) + 1);
112
113         if (!s2)
114                 return NULL;
115
116         return strcpy(s2, s);
117 }
118
119 static int get_alignment(int fd)
120 {
121         int alignment = DEFAULT_ALIGNMENT;
122
123 #ifdef _PC_REC_XFER_ALIGN
124         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
125         if (alignment < 0)
126                 alignment = DEFAULT_ALIGNMENT;
127 #endif
128         return alignment;
129 }
130
131 static void *aligned_malloc(void **base, int size, int alignment)
132 {
133 #ifdef HAVE_POSIX_MEMALIGN
134         return posix_memalign(base, alignment, size) ? NULL : *base;
135 #else
136 /* Credits go to Michal's padlock patches for this alignment code */
137         char *ptr;
138
139         ptr  = malloc(size + alignment);
140         if(ptr == NULL) return NULL;
141
142         *base = ptr;
143         if(alignment > 1 && ((long)ptr & (alignment - 1))) {
144                 ptr += alignment - ((long)(ptr) & (alignment - 1));
145         }
146         return ptr;
147 #endif
148 }
149 static int sector_size(int fd) 
150 {
151         int bsize;
152         if (ioctl(fd,BLKSSZGET, &bsize) < 0)
153                 return -EINVAL;
154         else
155                 return bsize;
156 }
157
158 int sector_size_for_device(const char *device)
159 {
160         int fd = open(device, O_RDONLY);
161         int r;
162         if(fd < 0)
163                 return -EINVAL;
164         r = sector_size(fd);
165         close(fd);
166         return r;
167 }
168
169 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
170 {
171         void *hangover_buf, *hangover_buf_base = NULL;
172         void *buf, *buf_base = NULL;
173         int r, hangover, solid, bsize, alignment;
174         ssize_t ret = -1;
175
176         if ((bsize = sector_size(fd)) < 0)
177                 return bsize;
178
179         hangover = count % bsize;
180         solid = count - hangover;
181         alignment = get_alignment(fd);
182
183         if ((long)orig_buf & (alignment - 1)) {
184                 buf = aligned_malloc(&buf_base, count, alignment);
185                 if (!buf)
186                         goto out;
187                 memcpy(buf, orig_buf, count);
188         } else
189                 buf = (void *)orig_buf;
190
191         r = write(fd, buf, solid);
192         if (r < 0 || r != solid)
193                 goto out;
194
195         if (hangover) {
196                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
197                 if (!hangover_buf)
198                         goto out;
199
200                 r = read(fd, hangover_buf, bsize);
201                 if(r < 0 || r != bsize) goto out;
202
203                 r = lseek(fd, -bsize, SEEK_CUR);
204                 if (r < 0)
205                         goto out;
206                 memcpy(hangover_buf, buf + solid, hangover);
207
208                 r = write(fd, hangover_buf, bsize);
209                 if(r < 0 || r != bsize) goto out;
210                 free(hangover_buf_base);
211         }
212         ret = count;
213  out:
214         if (buf != orig_buf)
215                 free(buf_base);
216         return ret;
217 }
218
219 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
220         void *hangover_buf, *hangover_buf_base;
221         void *buf, *buf_base = NULL;
222         int r, hangover, solid, bsize, alignment;
223         ssize_t ret = -1;
224
225         if ((bsize = sector_size(fd)) < 0)
226                 return bsize;
227
228         hangover = count % bsize;
229         solid = count - hangover;
230         alignment = get_alignment(fd);
231
232         if ((long)orig_buf & (alignment - 1)) {
233                 buf = aligned_malloc(&buf_base, count, alignment);
234                 if (!buf)
235                         goto out;
236         } else
237                 buf = orig_buf;
238
239         r = read(fd, buf, solid);
240         if(r < 0 || r != solid) {
241                 set_error("read failed in read_blockwise.\n");
242                 goto out;
243         }
244
245         if (hangover) {
246                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
247                 if (!hangover_buf)
248                         goto out;
249                 r = read(fd, hangover_buf, bsize);
250                 if (r <  0 || r != bsize)
251                         goto out;
252
253                 memcpy(buf + solid, hangover_buf, hangover);
254                 free(hangover_buf_base);
255         }
256         ret = count;
257  out:
258         if (buf != orig_buf) {
259                 memcpy(orig_buf, buf, count);
260                 free(buf_base);
261         }
262         return ret;
263 }
264
265 /* 
266  * Combines llseek with blockwise write. write_blockwise can already deal with short writes
267  * but we also need a function to deal with short writes at the start. But this information
268  * is implicitly included in the read/write offset, which can not be set to non-aligned 
269  * boundaries. Hence, we combine llseek with write.
270  */
271
272 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
273         int bsize = sector_size(fd);
274         const char *orig_buf = buf;
275         char frontPadBuf[bsize];
276         int frontHang = offset % bsize;
277         int r;
278         int innerCount = count < bsize ? count : bsize;
279
280         if (bsize < 0)
281                 return bsize;
282
283         lseek(fd, offset - frontHang, SEEK_SET);
284         if(offset % bsize) {
285                 r = read(fd,frontPadBuf,bsize);
286                 if(r < 0) return -1;
287
288                 memcpy(frontPadBuf+frontHang, buf, innerCount);
289
290                 lseek(fd, offset - frontHang, SEEK_SET);
291                 r = write(fd,frontPadBuf,bsize);
292                 if(r < 0) return -1;
293
294                 buf += innerCount;
295                 count -= innerCount;
296         }
297         if(count <= 0) return buf - orig_buf;
298
299         return write_blockwise(fd, buf, count) + innerCount;
300 }
301
302 /* Password reading helpers */
303
304 static int untimed_read(int fd, char *pass, size_t maxlen)
305 {
306         ssize_t i;
307
308         i = read(fd, pass, maxlen);
309         if (i > 0) {
310                 pass[i-1] = '\0';
311                 i = 0;
312         } else if (i == 0) { /* EOF */
313                 *pass = 0;
314                 i = -1;
315         }
316         return i;
317 }
318
319 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
320 {
321         struct timeval t;
322         fd_set fds;
323         int failed = -1;
324
325         FD_ZERO(&fds);
326         FD_SET(fd, &fds);
327         t.tv_sec = timeout;
328         t.tv_usec = 0;
329
330         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
331                 failed = untimed_read(fd, pass, maxlen);
332         else
333                 set_error("Operation timed out");
334         return failed;
335 }
336
337 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
338                 long timeout)
339 {
340         struct termios orig, tmp;
341         int failed = -1;
342         int infd = STDIN_FILENO, outfd;
343
344         if (maxlen < 1)
345                 goto out_err;
346
347         /* Read and write to /dev/tty if available */
348         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
349                 infd = STDIN_FILENO;
350                 outfd = STDERR_FILENO;
351         }
352
353         if (tcgetattr(infd, &orig)) {
354                 set_error("Unable to get terminal");
355                 goto out_err;
356         }
357         memcpy(&tmp, &orig, sizeof(tmp));
358         tmp.c_lflag &= ~ECHO;
359
360         if (write(outfd, prompt, strlen(prompt)) < 0)
361                 goto out_err;
362
363         tcsetattr(infd, TCSAFLUSH, &tmp);
364         if (timeout)
365                 failed = timed_read(infd, pass, maxlen, timeout);
366         else
367                 failed = untimed_read(infd, pass, maxlen);
368         tcsetattr(infd, TCSAFLUSH, &orig);
369
370 out_err:
371         if (!failed)
372                 (void)write(outfd, "\n", 1);
373         if (infd != STDIN_FILENO)
374                 close(infd);
375         return failed;
376 }
377
378 /*
379  * Password reading behaviour matrix of get_key
380  * 
381  *                    p   v   n   h
382  * -----------------+---+---+---+---
383  * interactive      | Y | Y | Y | Inf
384  * from fd          | N | N | Y | Inf
385  * from binary file | N | N | N | Inf or options->key_size
386  *
387  * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
388  *
389  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
390  *
391  * Returns true when more keys are available (that is when password
392  * reading can be retried as for interactive terminals).
393  */
394
395 int get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
396             const char *key_file, int passphrase_fd, int timeout, int how2verify)
397 {
398         int fd;
399         const int verify = how2verify & CRYPT_FLAG_VERIFY;
400         const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
401         char *pass = NULL;
402         int newline_stop;
403         int read_horizon;
404
405         if(key_file && !strcmp(key_file, "-")) {
406                 /* Allow binary reading from stdin */
407                 fd = passphrase_fd;
408                 newline_stop = 0;
409                 read_horizon = 0;
410         } else if (key_file) {
411                 fd = open(key_file, O_RDONLY);
412                 if (fd < 0) {
413                         char buf[128];
414                         set_error("Error opening key file: %s",
415                                   strerror_r(errno, buf, 128));
416                         goto out_err;
417                 }
418                 newline_stop = 0;
419
420                 /* This can either be 0 (LUKS) or the actually number
421                  * of key bytes (default or passed by -s) */
422                 read_horizon = key_size;
423         } else {
424                 fd = passphrase_fd;
425                 newline_stop = 1;
426                 read_horizon = 0;   /* Infinite, if read from terminal or fd */
427         }
428
429         /* Interactive case */
430         if(isatty(fd)) {
431                 int i;
432
433                 pass = safe_alloc(512);
434                 if (!pass || (i = interactive_pass(prompt, pass, 512, timeout))) {
435                         set_error("Error reading passphrase");
436                         goto out_err;
437                 }
438                 if (verify || verify_if_possible) {
439                         char pass_verify[512];
440                         i = interactive_pass("Verify passphrase: ", pass_verify, sizeof(pass_verify), timeout);
441                         if (i || strcmp(pass, pass_verify) != 0) {
442                                 set_error("Passphrases do not match");
443                                 goto out_err;
444                         }
445                         memset(pass_verify, 0, sizeof(pass_verify));
446                 }
447                 *passLen = strlen(pass);
448                 *key = pass;
449         } else {
450                 /* 
451                  * This is either a fd-input or a file, in neither case we can verify the input,
452                  * however we don't stop on new lines if it's a binary file.
453                  */
454                 int buflen, i;
455
456                 if(verify) {
457                         set_error("Can't do passphrase verification on non-tty inputs");
458                         goto out_err;
459                 }
460                 /* The following for control loop does an exhausting
461                  * read on the key material file, if requested with
462                  * key_size == 0, as it's done by LUKS. However, we
463                  * should warn the user, if it's a non-regular file,
464                  * such as /dev/random, because in this case, the loop
465                  * will read forever.
466                  */ 
467                 if(key_file && strcmp(key_file, "-") && read_horizon == 0) {
468                         struct stat st;
469                         if(stat(key_file, &st) < 0) {
470                                 set_error("Can't stat key file");
471                                 goto out_err;
472                         }
473                         if(!S_ISREG(st.st_mode)) {
474                                 //                              set_error("Can't do exhausting read on non regular files");
475                                 // goto out_err;
476                                 fprintf(stderr,"Warning: exhausting read requested, but key file is not a regular file, function might never return.\n");
477                         }
478                 }
479                 buflen = 0;
480                 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
481                         if(i >= buflen - 1) {
482                                 buflen += 128;
483                                 pass = safe_realloc(pass, buflen);
484                                 if (!pass) {
485                                         set_error("Not enough memory while "
486                                                   "reading passphrase");
487                                         goto out_err;
488                                 }
489                         }
490                         if(read(fd, pass + i, 1) != 1 || (newline_stop && pass[i] == '\n'))
491                                 break;
492                 }
493                 if(key_file)
494                         close(fd);
495                 pass[i] = 0;
496                 *key = pass;
497                 *passLen = i;
498         }
499
500         return isatty(fd); /* Return true, when password reading can be tried on interactive fds */
501
502 out_err:
503         if(pass)
504                 safe_free(pass);
505         *key = NULL;
506         *passLen = 0;
507         return 0;
508 }
509