~gl-az/percona-xtrabackup/2.1-io-block-size

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/******************************************************
Copyright (c) 2011 Percona Ireland Ltd.

The xbcrypt utility: decrypt files in the XBCRYPT format.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

*******************************************************/

#include <my_base.h>
#include <my_getopt.h>
#include "common.h"
#include "xbcrypt.h"
#include <gcrypt.h>

GCRY_THREAD_OPTION_PTHREAD_IMPL;

#define XBCRYPT_VERSION "1.0"

typedef enum {
	RUN_MODE_NONE,
	RUN_MODE_ENCRYPT,
	RUN_MODE_DECRYPT
} run_mode_t;

const char *xbcrypt_encrypt_algo_names[] =
{ "NONE", "AES128", "AES192", "AES256", NullS};
TYPELIB xbcrypt_encrypt_algo_typelib=
{array_elements(xbcrypt_encrypt_algo_names)-1,"",
	xbcrypt_encrypt_algo_names, NULL};

static run_mode_t	opt_run_mode = RUN_MODE_ENCRYPT;
static char 		*opt_input_file = NULL;
static char 		*opt_output_file = NULL;
static ulong 		opt_encrypt_algo;
static char 		*opt_encrypt_key_file = NULL;
static void 		*opt_encrypt_key = NULL;
static ulonglong	opt_encrypt_chunk_size = 0;
static my_bool		opt_verbose = FALSE;

static uint 		encrypt_algos[] = { GCRY_CIPHER_NONE,
					    GCRY_CIPHER_AES128,
					    GCRY_CIPHER_AES192,
					    GCRY_CIPHER_AES256 };
static int		encrypt_algo = 0;
static int		encrypt_mode = GCRY_CIPHER_MODE_CTR;
static uint 		encrypt_key_len = 0;
static const unsigned char encrypt_iv[] =
			    "Percona Xtrabackup is Awesome!!!";
static size_t 		encrypt_iv_len = 0;

static struct my_option my_long_options[] =
{
	{"help", '?', "Display this help and exit.",
	 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},

	{"decrypt", 'd', "Decrypt data input to output.",
	 0, 0, 0,
	 GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},

	{"input", 'i', "Optional input file. If not specified, input"
	 " will be read from standard input.",
	 &opt_input_file, &opt_input_file, 0,
	 GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},

	{"output", 'o', "Optional output file. If not specified, output"
	 " will be written to standard output.",
	 &opt_output_file, &opt_output_file, 0,
	 GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},

	{"encrypt-algo", 'a', "Encryption algorithm.",
	 &opt_encrypt_algo, &opt_encrypt_algo, &xbcrypt_encrypt_algo_typelib,
	 GET_ENUM, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},

	{"encrypt-key", 'k', "Encryption key.",
	 &opt_encrypt_key, &opt_encrypt_key, 0,
	 GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},

	{"encrypt-key-file", 'f', "File which contains encryption key.",
	 &opt_encrypt_key_file, &opt_encrypt_key_file, 0,
	 GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},

	{"encrypt-chunk-size", 's', "Size of working buffer for encryption in"
	 " bytes. The default value is 64K.",
	 &opt_encrypt_chunk_size, &opt_encrypt_chunk_size, 0,
	GET_ULL, REQUIRED_ARG, (1 << 16), 1024, ULONGLONG_MAX, 0, 0, 0},

	{"verbose", 'v', "Display verbose status output.",
	 &opt_verbose, &opt_verbose,
	  0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
	{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};

static
int
get_options(int *argc, char ***argv);

static
my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument __attribute__((unused)));

static
void
print_version(void);

static
void
usage(void);

static
int
mode_decrypt(File filein, File fileout);

static
int
mode_encrypt(File filein, File fileout);

int
main(int argc, char **argv)
{
	gcry_error_t 		gcry_error;
	File filein = 0;
	File fileout = 0;

	MY_INIT(argv[0]);

	if (get_options(&argc, &argv)) {
		goto err;
	}

	/* Acording to gcrypt docs (and my testing), setting up the threading
	   callbacks must be done first, so, lets give it a shot */
	gcry_error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
	if (gcry_error) {
		msg("%s: unable to set libgcrypt thread cbs - "
		    "%s : %s\n", my_progname,
		    gcry_strsource(gcry_error),
		    gcry_strerror(gcry_error));
		return 1;
	}

	/* Version check should be the very first call because it
	makes sure that important subsystems are intialized. */
	if (!gcry_control(GCRYCTL_ANY_INITIALIZATION_P)) {
		const char	*gcrypt_version;
		gcrypt_version = gcry_check_version(NULL);
		/* No other library has already initialized libgcrypt. */
		if (!gcrypt_version) {
			msg("%s: failed to initialize libgcrypt\n",
			    my_progname);
			return 1;
		} else if (opt_verbose) {
			msg("%s: using gcrypt %s\n", my_progname,
			    gcrypt_version);
		}
	}
	gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

	/* Determine the algorithm */
	encrypt_algo = encrypt_algos[opt_encrypt_algo];

	/* Set up the iv length */
	encrypt_iv_len = gcry_cipher_get_algo_blklen(encrypt_algo);

	/* Now set up the key */
	if (opt_encrypt_key == NULL && opt_encrypt_key_file == NULL) {
		msg("%s: no encryption key or key file specified.\n",
		    my_progname);
		return 1;
	} else if (opt_encrypt_key && opt_encrypt_key_file) {
		msg("%s: both encryption key and key file specified.\n",
		    my_progname);
		return 1;
	} else if (opt_encrypt_key_file) {
		if (!xb_crypt_read_key_file(opt_encrypt_key_file,
					    &opt_encrypt_key,
					    &encrypt_key_len)) {
			msg("%s: unable to read encryption key file \"%s\".\n",
			    opt_encrypt_key_file, my_progname);
			return 1;
		}
	} else {
		encrypt_key_len = strlen(opt_encrypt_key);
	}

	if (opt_input_file) {
		MY_STAT 	mystat;

		if (opt_verbose)
			msg("%s: input file \"%s\".\n", my_progname,
			    opt_input_file);

		if (my_stat(opt_input_file, &mystat, MYF(MY_WME)) == NULL) {
			goto err;
		}
		if (!MY_S_ISREG(mystat.st_mode)) {
			msg("%s: \"%s\" is not a regular file, exiting.\n",
			    my_progname, opt_input_file);
			goto err;
		}
		if ((filein = my_open(opt_input_file, O_RDONLY, MYF(MY_WME)))
		     < 0) {
			msg("%s: failed to open \"%s\".\n", my_progname,
			     opt_input_file);
			goto err;
		}
	} else {
		if (opt_verbose)
			msg("%s: input from standard input.\n", my_progname);
		filein = fileno(stdin);
	}

	if (opt_output_file) {
		if (opt_verbose)
			msg("%s: output file \"%s\".\n", my_progname,
			    opt_output_file);

		if ((fileout = my_create(opt_output_file, 0,
					 O_WRONLY|O_BINARY|O_EXCL|O_NOFOLLOW,
					 MYF(MY_WME))) < 0) {
			msg("%s: failed to create output file \"%s\".\n",
			    my_progname, opt_output_file);
			goto err;
		}
	} else {
		if (opt_verbose)
			msg("%s: output to standard output.\n", my_progname);
		fileout = fileno(stdout);
	}

	if (opt_run_mode == RUN_MODE_DECRYPT
	    && mode_decrypt(filein, fileout)) {
		goto err;
	} else if (opt_run_mode == RUN_MODE_ENCRYPT
		   && mode_encrypt(filein, fileout)) {
		goto err;
	}

	if (opt_input_file && filein) {
		my_close(filein, MYF(MY_WME));
	}
	if (opt_output_file && fileout) {
		my_close(fileout, MYF(MY_WME));
	}

	my_cleanup_options(my_long_options);

	my_end(0);

	return EXIT_SUCCESS;
err:
	if (opt_input_file && filein) {
		my_close(filein, MYF(MY_WME));
	}
	if (opt_output_file && fileout) {
		my_close(fileout, MYF(MY_WME));
	}

	my_cleanup_options(my_long_options);

	my_end(0);

	exit(EXIT_FAILURE);

}


static
ssize_t
my_xb_crypt_read_callback(void *userdata, void *buf, size_t len)
{
	File* file = (File *) userdata;
	return my_read(*file, buf, len, MYF(MY_WME));
}

static
int
mode_decrypt(File filein, File fileout)
{
	xb_rcrypt_t		*xbcrypt_file = NULL;
	void			*chunkbuf = NULL;
	size_t			chunksize;
	size_t			originalsize;
	void			*decryptbuf = NULL;
	size_t			decryptbufsize = 0;
	ulonglong		ttlchunksread = 0;
	ulonglong		ttlbytesread = 0;
	xb_rcrypt_result_t	result;
	gcry_cipher_hd_t	cipher_handle;
	gcry_error_t		gcry_error;

	if (encrypt_algo != GCRY_CIPHER_NONE) {
		gcry_error = gcry_cipher_open(&cipher_handle,
					      encrypt_algo,
					      encrypt_mode, 0);
		if (gcry_error) {
			msg("%s:decrypt: unable to open libgcrypt"
			    " cipher - %s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			return 1;
		}

		gcry_error = gcry_cipher_setkey(cipher_handle,
						opt_encrypt_key,
						encrypt_key_len);
		if (gcry_error) {
			msg("%s:decrypt: unable to set libgcrypt cipher"
			    "key - %s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			goto err;
		}
	}

	/* Initialize the xb_crypt format reader */
	xbcrypt_file = xb_crypt_read_open(&filein, my_xb_crypt_read_callback);
	if (xbcrypt_file == NULL) {
		msg("%s:decrypt: xb_crypt_read_open() failed.\n", my_progname);
		goto err;
	}

	/* Walk the encrypted chunks, decrypting them and writing out */
	while ((result = xb_crypt_read_chunk(xbcrypt_file, &chunkbuf,
					     &originalsize, &chunksize))
		== XB_CRYPT_READ_CHUNK) {

		if (encrypt_algo != GCRY_CIPHER_NONE) {
			gcry_error = gcry_cipher_reset(cipher_handle);
			if (gcry_error) {
				msg("%s:decrypt: unable to reset libgcrypt"
				    " cipher - %s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				goto err;
			}

			gcry_error = gcry_cipher_setiv(cipher_handle,
							encrypt_iv,
							encrypt_iv_len);
			if (gcry_error) {
				msg("%s:decrypt: unable to set cipher iv - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				continue;
			}

			if (decryptbufsize < originalsize) {
				if (decryptbufsize) {
					decryptbuf = my_realloc(decryptbuf,
								originalsize,
								MYF(MY_WME));
					decryptbufsize = originalsize;
				} else {
					decryptbuf = my_malloc(originalsize,
							       MYF(MY_WME));
					decryptbufsize = originalsize;
				}
			}

			/* Try to decrypt it */
			gcry_error = gcry_cipher_decrypt(cipher_handle,
							 decryptbuf,
							 originalsize,
							 chunkbuf,
							 chunksize);
			if (gcry_error) {
				msg("%s:decrypt: unable to decrypt chunk - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				gcry_cipher_close(cipher_handle);
					goto err;
			}

		} else {
			decryptbuf = chunkbuf;
		}

		/* Write it out */
		if (my_write(fileout, decryptbuf, originalsize,
			     MYF(MY_WME | MY_NABP))) {
			msg("%s:decrypt: unable to write output chunk.\n",
			    my_progname);
			goto err;
		}
		ttlchunksread++;
		ttlbytesread += chunksize;
		if (opt_verbose)
			msg("%s:decrypt: %llu chunks read, %llu bytes read\n.",
		    	    my_progname, ttlchunksread, ttlbytesread);
	}

	xb_crypt_read_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (decryptbuf && decryptbufsize)
		MY_FREE(decryptbuf);

	if (opt_verbose)
		msg("\n%s:decrypt: done\n", my_progname);

	return 0;
err:
	if (xbcrypt_file)
		xb_crypt_read_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (decryptbuf && decryptbufsize)
		MY_FREE(decryptbuf);

	return 1;
}

static
ssize_t
my_xb_crypt_write_callback(void *userdata, const void *buf, size_t len)
{
	File* file = (File *) userdata;

	ssize_t ret = my_write(*file, buf, len, MYF(MY_WME));
	posix_fadvise(*file, 0, 0, POSIX_FADV_DONTNEED);
	return ret;
}

static
int
mode_encrypt(File filein, File fileout)
{
	size_t			bytesread;
	size_t			chunkbuflen;
	void			*chunkbuf = NULL;
	size_t			encryptbuflen = 0;
	size_t			encryptedlen = 0;
	void			*encryptbuf = NULL;
	ulonglong		ttlchunkswritten = 0;
	ulonglong		ttlbyteswritten = 0;
	xb_wcrypt_t		*xbcrypt_file = NULL;
	gcry_cipher_hd_t	cipher_handle;
	gcry_error_t		gcry_error;

	if (encrypt_algo != GCRY_CIPHER_NONE) {
		gcry_error = gcry_cipher_open(&cipher_handle,
					      encrypt_algo,
					      encrypt_mode, 0);
		if (gcry_error) {
			msg("%s:encrypt: unable to open libgcrypt cipher - "
			    "%s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			return 1;
		}

		gcry_error = gcry_cipher_setkey(cipher_handle,
						opt_encrypt_key,
						encrypt_key_len);
		if (gcry_error) {
			msg("%s:encrypt: unable to set libgcrypt cipher key - "
			    "%s : %s\n", my_progname,
			    gcry_strsource(gcry_error),
			    gcry_strerror(gcry_error));
			goto err;
		}
	}

	posix_fadvise(filein, 0, 0, POSIX_FADV_SEQUENTIAL);

	xbcrypt_file = xb_crypt_write_open(&fileout,
					   my_xb_crypt_write_callback);
	if (xbcrypt_file == NULL) {
		msg("%s:encrypt: xb_crypt_write_open() failed.\n",
		    my_progname);
		goto err;
	}

	/* now read in data in chunk size, encryptand write out */
	chunkbuflen = opt_encrypt_chunk_size;
	chunkbuf = my_malloc(chunkbuflen, MYF(MY_FAE));
	while ((bytesread = my_read(filein, chunkbuf, chunkbuflen,
				    MYF(MY_WME))) > 0) {

		if (encrypt_algo != GCRY_CIPHER_NONE) {
			gcry_error = gcry_cipher_reset(cipher_handle);

			if (gcry_error) {
				msg("%s:encrypt: unable to reset cipher - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				goto err;
			}
			gcry_error = gcry_cipher_setiv(cipher_handle,
							encrypt_iv,
							encrypt_iv_len);

			if (gcry_error) {
				msg("%s:encrypt: unable to set cipher iv - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				continue;
			}

			if (encryptbuflen < bytesread) {
				if (encryptbuflen) {
					encryptbuf = my_realloc(encryptbuf,
								bytesread,
								MYF(MY_WME));
					encryptbuflen = bytesread;
				} else {
					encryptbuf = my_malloc(bytesread,
							       MYF(MY_WME));
					encryptbuflen = bytesread;
				}
			}

			gcry_error = gcry_cipher_encrypt(cipher_handle,
							 encryptbuf,
							 encryptbuflen,
							 chunkbuf,
							 bytesread);

			encryptedlen = bytesread;

			if (gcry_error) {
				msg("%s:encrypt: unable to encrypt chunk - "
				    "%s : %s\n", my_progname,
				    gcry_strsource(gcry_error),
				    gcry_strerror(gcry_error));
				gcry_cipher_close(cipher_handle);
				goto err;
			}
		} else {
			encryptedlen = bytesread;
			encryptbuf = chunkbuf;
		}

		if (xb_crypt_write_chunk(xbcrypt_file, encryptbuf, bytesread, encryptedlen)) {
			msg("%s:encrypt: abcrypt_write_chunk() failed.\n",
			    my_progname);
			goto err;
		}

		ttlchunkswritten++;
		ttlbyteswritten += encryptedlen;

		if (opt_verbose)
			msg("%s:encrypt: %llu chunks written, %llu bytes "
			    "written\n.", my_progname, ttlchunkswritten,
			    ttlbyteswritten);
	}

	MY_FREE(chunkbuf);

	if (encryptbuf && encryptbuflen)
		MY_FREE(encryptbuf);

	xb_crypt_write_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	if (opt_verbose)
		msg("\n%s:encrypt: done\n", my_progname);

	return 0;
err:
	if (chunkbuf)
		MY_FREE(chunkbuf);

	if (encryptbuf && encryptbuflen)
		MY_FREE(encryptbuf);

	if (xbcrypt_file)
		xb_crypt_write_close(xbcrypt_file);

	if (encrypt_algo != GCRY_CIPHER_NONE)
		gcry_cipher_close(cipher_handle);

	return 1;
}

static
int
get_options(int *argc, char ***argv)
{
	int ho_error;

	if ((ho_error= handle_options(argc, argv, my_long_options,
				      get_one_option))) {
		exit(EXIT_FAILURE);
	}

	return 0;
}

static
my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument __attribute__((unused)))
{
	switch (optid) {
	case 'd':
		opt_run_mode = RUN_MODE_DECRYPT;
		break;
	case '?':
		usage();
		exit(0);
	}

	return FALSE;
}

static
void
print_version(void)
{
	printf("%s  Ver %s for %s (%s)\n", my_progname, XBCRYPT_VERSION,
	       SYSTEM_TYPE, MACHINE_TYPE);
}

static
void
usage(void)
{
	print_version();
	puts("Copyright (C) 2011 Percona Inc.");
	puts("This software comes with ABSOLUTELY NO WARRANTY. "
	     "This is free software,\nand you are welcome to modify and "
	     "redistribute it under the GPL license.\n");

	puts("Encrypt or decrypt files in the XBCRYPT format.\n");

	puts("Usage: ");
	printf("  %s [OPTIONS...]"
 	       " # read data from specified input, encrypting or decrypting "
	       " and writing the result to the specified output.\n",
	       my_progname);
	puts("\nOptions:");
	my_print_help(my_long_options);
}