mqascan.c 11.2 KB
Newer Older
Mans Rullgard's avatar
Mans Rullgard committed
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
/*
  Copyright (c) 2017, Mans Rullgard <mans@mansr.com>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <unistd.h>
#include <sndfile.h>
35
#include <gmp.h>
Mans Rullgard's avatar
Mans Rullgard committed
36 37

#include "bits.h"
38
#include "blake2.h"
Mans Rullgard's avatar
Mans Rullgard committed
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
#include "sfbits.h"
#include "mqa-common.h"

#define MQA_MAGIC	0x11319207d5

struct metadata {
	unsigned size;
	uint8_t data[256];
};

static struct bitreader br;

static struct metadata *metadata;
static int metadata_frags;
static int metadata_type = 1;

static jmp_buf eofjmp;

static unsigned bitnum;
static unsigned abspos;

static uint32_t csum;

static int verbosity = 1;
static int packet_type = -1;
Mans Rullgard's avatar
Mans Rullgard committed
64
static int single;
Mans Rullgard's avatar
Mans Rullgard committed
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

static uint32_t update_csum(uint64_t bits, int n)
{
	while (n--) {
		int x = csum & 1;
		csum = csum >> 1 | bits << 31;
		if (x)
			csum ^= 3;
		bits >>= 1;
	}

	return csum & 15;
}

static void get_bits_cb(uint64_t bits, int n)
{
	bitnum += n;
	update_csum(bits, n);
}

static void eof_cb(void)
{
	longjmp(eofjmp, 1);
}

static int handle_hole(struct bitreader *b, unsigned ptype)
{
	int size = print_field(b, 4, 0, "size", NULL);

	if (size == 15)
		size = print_field(b, 12, 0, "size", NULL);

	print_data(b, size, 0, "hole", NULL);

	return 0;
}

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
static const struct bitfield auth_fields[] = {
	{ 63,	BF_HEX,		"unknown" },
	{ 1,	0,		"check_lsb" },
	{ 24,	BF_HEX,		"unknown" },
	{ 4,	BF_HEX,		"auth_info", },
	{ 4,	0,		"auth_level" },
	{ 32,	BF_HEX,		"stage2_crc" },
	{ 256,	BF_DATA,	"stage1_hash" },
	{ 256,	BF_DATA,	"lsb_hash[0]" },
	{ 256,	BF_DATA,	"lsb_hash[1]" },
	{ 256,	BF_DATA,	"lsb_hash[2]" },
	{ 256,	BF_DATA,	"lsb_hash[3]" },
	{ 256,	BF_DATA,	"lsb_hash[4]" },
	{ 256,	BF_DATA,	"lsb_hash[5]" },
	{ 256,	BF_DATA,	"lsb_hash[6]" },
	{ 256,	BF_DATA,	"lsb_hash[7]" },
	{ 256,	BF_DATA,	"lsb_hash[8]" },
	{ 32,	BF_HEX,		"unknown" },
	{ 96,	BF_DATA,	"unknown" },
	{ 256,	BF_DATA,	"auth_hash" },
};

static int handle_auth(struct bitreader *b, unsigned ptype)
{
	struct bitreader br;
	blake2s_state b2s;
	uint8_t data[384];
	size_t size;
	mpz_t mod;
	mpz_t msg;
	int key;
	int i;

	key = print_field(b, 4, 0, "auth_level", NULL);
	print_data(b, 3072, 0, "auth_data", data);

	if (print_verbosity(-1) < 1)
		return 0;

	mpz_inits(mod, msg, NULL);

	mpz_import(mod, 384, 1, 1, 0, 0, mqa_auth_keys[key]);
	mpz_import(msg, 384, 1, 1, 0, 0, data);

	mpz_powm_ui(msg, msg, 3, mod);
	mpz_export(data, &size, 1, 1, 0, 0, msg);

	mpz_clears(mod, msg, NULL);

	memmove(data + 384 - size, data, size);

	blake2s_init(&b2s, 32);
	blake2s_update(&b2s, data + 352, 32);

	for (i = 0; i < 11; i++) {
		blake2s_state b2i = b2s;
		uint8_t il[4] = { i };
		uint8_t h[32];
		int j;

		blake2s_update(&b2i, &il, 4);
		blake2s_final(&b2i, h, 32);

		for (j = 0; j < 32; j++)
			data[32 * i + j] ^= h[j];
	}

	data[0] &= 0x7f;

	init_bits(&br);
	br.fill_bits = fill_bits_buf;
	br.data = data;

	print_verbose(1, "%10s[begin decrypted auth_data]\n", "");
	print_fields(&br, auth_fields, NULL);
	print_verbose(1, "%10s[end decrypted auth_data]\n", "");

	return 0;
}

Mans Rullgard's avatar
Mans Rullgard committed
182 183 184 185 186 187 188
static const struct bitfield datasync_fields[] = {
	{ 36,	BF_HEX,		"magic" },
	{ 1,	BF_RET,		"stream_pos_flag" },
	{ 1,	0,		"pad" },
	{ 5,	BF_HEX,		"orig_rate",	mqa_rates },
	{ 5,	BF_HEX,		"src_rate",	mqa_rates },
	{ 5,	0,		"render_filter" },
189 190
	{ 5,	BF_HEX,		"unknown_1" },
	{ 1,	0,		"unknown_2" },
Mans Rullgard's avatar
Mans Rullgard committed
191
	{ 2,	0,		"pad" },
192 193
	{ 4,	BF_HEX,		"auth_info" },
	{ 4,	BF_HEX,		"auth_level" },
194
	{ 7,	BF_RET,		"item_count" },
Mans Rullgard's avatar
Mans Rullgard committed
195 196 197 198 199 200 201
	{ 0 }
};

static int handle_datasync(struct bitreader *b, unsigned ptype)
{
	uint64_t val[2];
	int stream_pos_flag;
202 203
	unsigned pos = 0;
	int offs;
Mans Rullgard's avatar
Mans Rullgard committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
	int n;
	int size[128];
	int type[128];
	int i;

	print_fields(b, datasync_fields, val);
	stream_pos_flag = val[0];
	n = val[1];

	for (i = 0; i < n; i++)
		size[i] = print_field(b, 8, BF_HEX, "size", NULL);

	for (i = 0; i < n; i++)
		type[i] = print_field(b, 8, BF_HEX, "type", NULL);

	if (stream_pos_flag)
		abspos = print_field(b, 32, BF_HEX, "stream_position", NULL);

	for (i = 0; i < n; i++) {
		print_verbose(1, "%10s[type %d]\n", "", type[i]);
		switch (type[i]) {
		case 0:
226 227
			print_field(b, 2, 0, "stage2_dither", NULL);
			print_field(b, 4, 0, "gain_index", NULL);
228 229
			print_field(b, 7, 0, "unknown_5", NULL);
			print_field(b, 7, 0, "unknown_6", NULL);
Mans Rullgard's avatar
Mans Rullgard committed
230
			if (stream_pos_flag) {
231 232 233 234
				pos = print_field(b, 27, BF_HEX | BF_NONL,
						  "start_pos", NULL);
				pos <<= 5;
				print_verbose(1, " [0x%x]\n", pos);
Mans Rullgard's avatar
Mans Rullgard committed
235 236 237 238 239
				print_field(b, 1, 0, "pad", NULL);
				print_data(b, size[i] - 48, BF_HEX, "data",
					   NULL);
			}
			break;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
		case 1:
			print_field(b, 6, 0, "unknown_7", NULL);
			print_field(b, 2, 0, "unknown_8", NULL);
			print_field(b, 1, 0, "unknown_9", NULL);
			print_field(b, 2, 0, "unknown_10", NULL);
			if (stream_pos_flag) {
				print_field(b, 8, 0, "unknown_11", NULL);
				print_field(b, 1, 0, "unknown_12", NULL);
				offs = print_field(b, 12, BF_SIGNED | BF_NONL,
						   "unknown_13", NULL);
				print_verbose(1, " [0x%x]\n", pos + offs);
			}
			break;
		case 2:
			print_field(b, 6, 0, "unknown_7", NULL);
			print_field(b, 2, 0, "unknown_10", NULL);
			if (stream_pos_flag) {
				print_field(b, 3, 0, "unknown_11", NULL);
				print_field(b, 1, 0, "unknown_12", NULL);
				offs = print_field(b, 12, BF_SIGNED | BF_NONL,
						   "unknown_13", NULL);
				print_verbose(1, " [0x%x]\n", pos + offs);
			}
			break;
Mans Rullgard's avatar
Mans Rullgard committed
264 265 266 267 268 269 270
		case 3:
			print_field(b, 64, BF_HEX, "iv", NULL);
			print_field(b, 32, BF_HEX, "start_pos", NULL);
			break;
		default:
			print_field(b, size[i],
				    BF_HEX | (size[i] > 32 ? BF_DATA : 0),
271
				    "unknown_12", NULL);
Mans Rullgard's avatar
Mans Rullgard committed
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
			break;
		}
	}

	return 0;
}

static const struct bitfield metadata_fields[] = {
	{ 7,	BF_HEX | BF_RET,	"type" },
	{ 1,	0,			"is_last" },
	{ 12,	BF_RET,			"fragment" },
	{ 8,	BF_RET,			"size" },
	{ 0 }
};

static int handle_metadata(struct bitreader *b, unsigned ptype)
{
	uint64_t val[3];
	int type, frag, size;
	uint8_t *buf = NULL;

	print_fields(b, metadata_fields, val);

	type = val[0];
	frag = val[1];
	size = val[2] + 1;

	if (type == metadata_type) {
		if (frag >= metadata_frags) {
			int n = frag + 1;
			metadata = realloc(metadata, n * sizeof(*metadata));
			memset(&metadata[metadata_frags], 0,
			       (n - metadata_frags) * sizeof(*metadata));
			metadata_frags = n;
		}

		metadata[frag].size = size;
		buf = metadata[frag].data;
	}

	print_data(b, 8 * size, BF_CHAR, "data", buf);

	return 0;
}

static const struct bitfield recon_fields[] = {
	{ 12,	BF_HEX,			"size" },
	{ 0,	BF_DATA | BF_SIZE,	"data" },
	{ 0 }
};

static const struct bitfield terminate_fields[] = {
	{ 17,	BF_HEX,		"bits_to_end" },
	{ 0 }
};

static const struct frame packets[16] = {
	[0] = {
		.name		= "hole",
		.handler	= handle_hole,
	},
	[1] = {
		.name		= "reconstruction",
		.fields		= recon_fields,
	},
	[3] = {
		.name		= "terminate",
		.fields		= terminate_fields,
	},
	[4] = {
342 343
		.name		= "authentication",
		.handler	= handle_auth,
Mans Rullgard's avatar
Mans Rullgard committed
344 345 346 347 348 349 350 351 352 353 354 355 356
	},
	[5] = {
		.name		= "datasync",
		.handler	= handle_datasync,
	},
	[7] = {
		.name		= "metadata",
		.handler	= handle_metadata,
	},
};

static int find_mqa_sync(struct bitreader *b)
{
Mans Rullgard's avatar
Mans Rullgard committed
357 358 359 360
	int err = find_sync(b, MQA_MAGIC, 40, 65536);

	if (err)
		return err;
Mans Rullgard's avatar
Mans Rullgard committed
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

	if (peek_bits(b, 1, 40)) {
		int n = peek_bits(b, 7, 73);
		abspos = peek_bits(b, 32, 80 + 16 * n);
	}

	csum = abspos & 15;

	return 0;
}

static void scan_mqa(struct bitreader *b)
{
	for (;;) {
		int startbit = bitnum;
		int type = get_ubits(b, 4);
		const struct frame *p = &packets[type];
		int pcs;
		int cs;

		if (!p->name) {
			printf("%08x: unknown packet type %d, abort\n",
			       startbit, type);
			return;
		}

		if (packet_type >= 0 && type != packet_type)
			print_verbosity(0);

		print_frame(b, p, type, startbit);

		cs = update_csum(0, -(bitnum - startbit) & 31);

		pcs = print_field(b, 4, BF_HEX, "checksum", NULL);

		print_verbosity(verbosity);

		if (cs != pcs) {
			printf("%08x: checksum error, resynchronising\n",
				bitnum);
			find_mqa_sync(b);
			continue;
		}

Mans Rullgard's avatar
Mans Rullgard committed
405 406 407
		if (single && (packet_type < 0 || type == packet_type))
			break;

Mans Rullgard's avatar
Mans Rullgard committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		abspos += bitnum - startbit;
		csum = abspos & 15;
	}
}

static void write_metadata(const char *file)
{
	FILE *md = fopen(file, "w");
	int i;

	if (!md) {
		perror(file);
		return;
	}

	for (i = 0; i < metadata_frags; i++) {
		if (!metadata[i].size)
			fprintf(stderr, "%s: fragment %d missing\n", file, i);
		fwrite(metadata[i].data, 1, metadata[i].size, md);
	}

	fclose(md);
430 431 432 433

	free(metadata);
	metadata = NULL;
	metadata_frags = 0;
Mans Rullgard's avatar
Mans Rullgard committed
434 435
}

436
static int scan_file(const char *name, int start, int mqabit)
Mans Rullgard's avatar
Mans Rullgard committed
437 438 439
{
	SNDFILE *file;
	SF_INFO fmt;
440
	int i;
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

	abspos = 0;

	memset(&fmt, 0, sizeof(fmt));
	file = sf_open(name, SFM_READ, &fmt);
	if (!file) {
		fprintf(stderr, "%s: %s\n", name, sf_strerror(NULL));
		return -1;
	}

	if (fmt.channels != 2) {
		fprintf(stderr, "%s: %d channels not allowed\n",
			name, fmt.channels);
		return -1;
	}

	print_verbosity(verbosity);

	if (!setjmp(eofjmp)) {
460 461 462 463 464 465 466 467 468 469 470 471 472 473
		for (i = mqabit; i < 16; i++) {
			sf_seek(file, start, SEEK_SET);
			init_bits_sf(&br, file, i);
			br.msb = 0;
			br.get_bits_cb = get_bits_cb;
			br.eof_cb = eof_cb;
			bitnum = 0;

			if (!find_mqa_sync(&br))
				break;
		}

		if (i < 16) {
			printf("%08x: MQA signature at bit %d\n", bitnum, i);
Mans Rullgard's avatar
Mans Rullgard committed
474
			scan_mqa(&br);
475
		}
476 477 478 479 480 481 482 483 484 485 486
	}

	print_end();

	sf_close(file);

	return 0;
}

int main(int argc, char **argv)
{
Mans Rullgard's avatar
Mans Rullgard committed
487
	const char *mdfile = NULL;
488
	int mqabit = 8;
Mans Rullgard's avatar
Mans Rullgard committed
489 490
	int start = 0;
	int opt;
491
	int i;
Mans Rullgard's avatar
Mans Rullgard committed
492

493
	while ((opt = getopt(argc, argv, "1b:m:M:p:s:v")) != -1) {
Mans Rullgard's avatar
Mans Rullgard committed
494
		switch (opt) {
Mans Rullgard's avatar
Mans Rullgard committed
495 496 497
		case '1':
			single = 1;
			break;
498 499 500
		case 'b':
			mqabit = strtol(optarg, NULL, 0);
			break;
Mans Rullgard's avatar
Mans Rullgard committed
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
		case 'm':
			mdfile = optarg;
			verbosity = 0;
			break;
		case 'M':
			metadata_type = strtol(optarg, NULL, 0);
			break;
		case 'p':
			packet_type = strtol(optarg, NULL, 0);
			break;
		case 's':
			start = strtol(optarg, NULL, 0);
			break;
		case 'v':
			verbosity++;
			break;
		default:
			return 1;
		}
	}

	argc -= optind;
	argv += optind;

	if (argc < 1)
		return 1;

528 529 530
	for (i = 0; i < argc; i++) {
		if (argc > 1)
			printf("%s\n", argv[i]);
Mans Rullgard's avatar
Mans Rullgard committed
531

532
		scan_file(argv[i], start, mqabit);
Mans Rullgard's avatar
Mans Rullgard committed
533

534 535
		if (metadata && mdfile)
			write_metadata(mdfile);
Mans Rullgard's avatar
Mans Rullgard committed
536 537 538 539
	}

	return 0;
}