emsh.c 58.3 KB
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 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#ifndef WIN32
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#else
#include <getopt.h>
#include <sys/timeb.h>
#include <winsock2.h>
#include <io.h>
#include <sys/stat.h>
#endif
#include <fcntl.h>

#include "ultrahost.h"
#include "PR/bbfs.h"
#include "PR/R4300.h"
#include "PR/bcp.h"
#include <bbcard.h>

#include "sha1.h"
#undef NULL
#include "algorithms.h"
#include "PR/bbskapi.h"
#include "PR/bbcert.h"

#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif

#include "mon.h"

#define DUMP_RAW_BLOCKS 1

#define BBC_UNKNOWN -1000

#define VERSION_MAJOR 1
#define VERSION_MINOR 2

/*
 * Private BBC interfaces only for emsh
 */
#ifndef WIN32
extern int BBCOpenMux(const char *devname, int flags);
#else
extern char* BBCGetDevName(BBCHandle h, int type);
#endif
extern int __BBC_ObjectSize(BBCHandle h, const char *name);
extern int __BBC_GetObject(BBCHandle h, const char *name, void *buf, int len);
extern int __BBC_StoreObject(BBCHandle h, const char *name, const char *tmpname, const void *buf, int len);
extern int __BBC_RenameObject(BBCHandle h, const char *old, const char *new);
extern int __BBC_RemoveObject(BBCHandle h, const char *name);
extern int __BBC_ListObjects(BBCHandle h);

#define TEMPFILE "temp.tmp"

extern int BBCGetFd(BBCHandle h, int input);
extern int osBbFDump(BBCHandle h, int blkno);

extern int bbc_log_level;
extern char* bbc_log_file;
extern int bbc_diag_mode;

int run_file(char* p);

/*
 * send commands to remote monitor and receive responses
 * basic flow is:
 *     send 2-word request <command, length of data>
 *     send data
 *     receive 2-word response <response is 255-cmd, length of data>
 *     receive data if any
 */

static int ifd = -1;
static int ofd = -1;

static int bbc_only = 0; /* Only support libbbc calls */
static int diag_mode = 0;

#define BBC_CLOSED   -1
#define BBC_OPEN_O    0
#define BBC_OPEN_B    1
static int bbc_mode = BBC_CLOSED;

static unsigned char version[256];
static unsigned char block[BB_FL_BLOCK_SIZE];
static unsigned char blist[BB_FL_BLOCK_SIZE];
static BbFat16 fat[2];	/* maximum 128MB flash */
static int blocks;

#define SK_BLOCKS	4
#define SL_BLOCKS	1
#define SA_BLOCKS	(BB_FL_BYTE_TO_BLOCK(BB_SYSTEM_AREA_SIZE)-2*SL_BLOCKS-SK_BLOCKS)
#define SYS_BLOCKS	(SK_BLOCKS + 2*SL_BLOCKS + SA_BLOCKS)

#define SK_OFF	0			/* first sk block */
#define SL0_OFF	SK_BLOCKS		/* sys license0 block */
#define SL1_OFF (SL0_OFF+SL_BLOCKS)	/* sys license1 block */
#define SA0_OFF (SL1_OFF+SL_BLOCKS)	/* first sys app0 block */

/*XXXblythe round up transfers to a multiple of 4 for irix */
#define RND(x)		(((x)+3)&~3)

static int sblocks[SYS_BLOCKS];

#ifndef BBC_IQAHC_DIAG
static char* progname = "emsh";
#else
static char* progname = "ique_diag";
#endif

#ifdef WIN32
#define TIME(t) _ftime(t)

struct _timeb t1, t2;

static int deltat(struct _timeb t1, struct _timeb t2)
{
	return (t2.time - t1.time)*1000 + (t2.millitm - t1.millitm);
}

#else
#define TIME(t) gettimeofday(t, NULL)

struct timeval t1, t2;

static int deltat(struct timeval tv1, struct timeval tv2)
{
    return (tv2.tv_sec-tv1.tv_sec)*1000 + (tv2.tv_usec-tv1.tv_usec)/1000;
}
#endif

static float getKBs(int bytes, int ms)
{
	if (ms == 0) ms = 1;  // Make sure we are dividing by 1 msec at least
	return bytes/1024.f/(ms/1000.f);
}

static const char*
basename(const char* s) {
    char* p;
    if ((p = strrchr(s, '/')) && p[1]) return p+1;
    return s;; 
}

void
sum(const unsigned char* p, int n) {
    int i;
    unsigned short s = 0;
    for(i = 0; i < n; i++)
	s += p[i];
    printf("sum %04x\n", s);
}

static int
send_cmd(const void* buf, int len) {
    int rv, i;

    for(i = 0; i < len/4; i++)
	*((unsigned int*)buf+i) = htonl(*((unsigned int*)buf+i));
    if ((rv = uhWriteGame(ofd, (void*)buf, len)) == -1) {
        perror("uhWriteGame");
	exit(1);
    }
    return rv;
}

static int
read_rsp(void* buf, int len) {
    int rv, i;
    if ((rv = uhReadGame(ifd, buf, len)) == -1) {
        perror("uhReadGame");
	exit(1);
    }
    for(i = 0; i < len/4; i++)
	*((unsigned int*)buf+i) = ntohl(*((unsigned int*)buf+i));
    return rv;
}

static int
send_data(const void* buf, int len) {
    int rv;
    if ((rv = uhWriteGame(ofd, (void*)buf, len)) == -1) {
        perror("uhWriteGame");
	exit(1);
    }
    return rv;
}

static int
read_data(void* buf, int len) {
    int rv;
    if ((rv = uhReadGame(ifd, buf, len)) == -1) {
        perror("uhReadGame");
	exit(1);
    }
    return rv;
}

static int blist_good;

static int
read_blist(int first_only) {
    unsigned int hbuf[2];
    int rv;
    if (blist_good && first_only) return 0;
    printf("scanning blocks\n");

    hbuf[0] = REQ_SCAN_BLOCKS;
    hbuf[1] = 0;
    send_cmd(hbuf, 8);
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_SCAN_BLOCKS || (hbuf[1]&0x80000000)) {
	fprintf(stderr, "scan blocks failed %d\n", hbuf[1]);
	return -1;
    }
    rv = read_data(blist, blocks = hbuf[1]);
    if (rv > 0) {
	/* compute addresses for sk, sal, and sa */
	int i, j;
        blist_good = 1;
	for(j = i = 0; i < blocks; i++) {
	    if (blist[i] == 0) {
		sblocks[j++] = i;
		if (j >= SYS_BLOCKS) break;
	    }
	}
	printf("found %d sys blocks\n", j);
    }
    return rv;
}

static int
write_block(const void* block, const void*spare,  int off) {
    unsigned int hbuf[2], r;
    /* write a block on the BBCard */
    hbuf[0] = spare ? REQ_WRITE_BLOCK_SP : REQ_WRITE_BLOCK;
    r = 255-hbuf[0];
    hbuf[1] = off;
    send_cmd(hbuf, 8);
    send_data(block, BB_FL_BLOCK_SIZE);
    if (spare) send_data(spare, BB_FL_SPARE_SIZE);
    read_rsp(hbuf, 8);
    if (hbuf[0] != r || hbuf[1] != 0) {
	fprintf(stderr, "write block %d failed\n", off);
	return -1;
    }
    return 0;
}

static int
read_block(void* block, void* spare, int off) {
    unsigned int hbuf[2], r;
    /* read a block on the BBCard */
    hbuf[0] = spare ? REQ_READ_BLOCK_SP : REQ_READ_BLOCK;
    r = 255-hbuf[0];
    hbuf[1] = off;
    send_cmd(hbuf, 8);
    read_rsp(hbuf, 8);
    read_data(block, BB_FL_BLOCK_SIZE);
    if (spare) read_data(spare, BB_FL_SPARE_SIZE);
    if (hbuf[0] != r || hbuf[1] != 0) {
	fprintf(stderr, "read block %d failed\n", off);
	return -1;
    }
    return 0;
}

static int
read_blocks(const char* file, int start, int n) {
    FILE* fp;
    int i;
    if ((fp = fopen(file, "wb")) == NULL) {
	perror(file);
	return -1;
    }
    for(i = 0; i < n; i++) {
	memset(block, 0, sizeof block);
	if (read_block(block, 0, sblocks[start+i]) < 0) {
	    fclose(fp);
	    return -1;
	}
	fwrite(block, sizeof block, 1, fp);
    }
    fclose(fp);
    return 0;
}

static int
write_blocks(const char* file, int start, int n, int link_start) {
    FILE* fp;
    int link = link_start;
    u8 spare[BB_FL_SPARE_SIZE];
    if ((fp = fopen(file, "rb")) == NULL) {
	perror(file);
	return -1;
    }
    memset(block, 0, sizeof block);
    memset(spare, 0xff, sizeof spare);
    while(fread(block, 1, sizeof block, fp) > 0) {
	if (--n < 0) {
	    printf("%s too large, truncating :)\n", file);
	    break;
	}
	if (link)  {
	    int prev = sblocks[link_start++];
            if(prev>255) return -1;
	    spare[BB_FL_BLOCK_LINK_OFF] = prev;
	    spare[BB_FL_BLOCK_LINK_OFF+1] = prev;
	    spare[BB_FL_BLOCK_LINK_OFF+2] = prev;
	    if (link_start >= SYS_BLOCKS) link_start = 0;
	}
	if (write_block(block, link ? spare : 0, sblocks[start++]) < 0) {
	    fclose(fp);
	    return -1;
	}
	memset(block, 0, sizeof block);
    }
    fclose(fp);
    return 0;
}

static int
delete_file(const char* file, int report) {
    unsigned int hbuf[2];
    hbuf[0] = REQ_DELETE_FILE;
    hbuf[1] = strlen(file)+1;
    send_cmd(hbuf, 8);
    send_data(file, RND(strlen(file)+1));
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_DELETE_FILE || (report && hbuf[1] != 0)) {
	fprintf(stderr, "delete %s failed\n", file);
    }
    return 0;
}

static int
move_file(const char* old, const char* new) {
    unsigned int hbuf[2];
    hbuf[0] = REQ_RENAME_FILE;
    hbuf[1] = strlen(old)+1;
    send_cmd(hbuf, 8);
    send_data(old, RND(strlen(old)+1));
    hbuf[0] = htonl(strlen(new)+1);
    send_data(hbuf, 4);
    send_data(new, RND(strlen(new)+1));
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_RENAME_FILE || hbuf[1] != 0) {
	fprintf(stderr, "move %s %s failed %d\n", new, old, hbuf[1]);
    }
    return 0;
}

static int
write_file(const char* in, const char* out) {
    FILE* fp;
    unsigned char* b;
    unsigned int hbuf[2];
    struct stat sb;
    unsigned int x, n, i;
#ifndef WIN32
    struct timeval tv1, tv2;
    float t;
#endif
    if ((fp = fopen(in, "rb")) == NULL) {
	perror(in);
	return -1;
    }
    fstat(fileno(fp), &sb);
    n = RND(sb.st_size);
    b = malloc(n);
    fread(b, sb.st_size, 1, fp);
    fclose(fp);
#ifndef WIN32
    gettimeofday(&tv1, NULL);
#endif
    hbuf[0] = REQ_WRITE_FILE;
    hbuf[1] = sb.st_size;
    send_cmd(hbuf, 8);
    x = htonl(strlen(out)+1);
    send_data(&x, 4);
    send_data(out, RND(ntohl(x)));
    /* read first response */
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_WRITE_FILE || hbuf[1] != 0) {
	fprintf(stderr, "file write of %s failed\n", in);
	free(b);
	return -1;
    }
    for(i = 0; i < n; i += BB_FL_BLOCK_SIZE)
	send_data(b+i, n-i < BB_FL_BLOCK_SIZE ? n-i : BB_FL_BLOCK_SIZE);
    free(b);
    /* read second response */
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_WRITE_FILE || hbuf[1] != 0) {
	fprintf(stderr, "file write of %s failed\n", in);
	return -1;
    }
#ifndef WIN32
    gettimeofday(&tv2, NULL);
    t = (float)(tv2.tv_sec-tv1.tv_sec) + (tv2.tv_usec-tv1.tv_usec)/1000000.f;
    printf("%.1f KB %.1f sec %.1f KB/s\n", sb.st_size/1024.f, t, sb.st_size/1000.f/t);
#endif
    return 0;
}

static int
read_file(const char* in, const char* out) {
    FILE* fp;
    unsigned char* b;
    unsigned int hbuf[2];
    int len, n;
    if ((fp = fopen(out, "wb")) == NULL) {
	perror(out);
	return -1;
    }
    hbuf[0] = REQ_READ_FILE;
    hbuf[1] = strlen(in)+1;
    send_cmd(hbuf, 8);
    send_data(in, RND(strlen(in)+1));
    read_rsp(hbuf, 8);
    if (hbuf[0] != 255-REQ_READ_FILE || (hbuf[1]&0x80000000)) {
	fprintf(stderr, "file read of %s failed\n", in);
	fclose(fp);
	return -1;
    }
    b = malloc(n = RND(hbuf[1]));
    for(len = 0; len < n; len += BB_FL_BLOCK_SIZE) {
	read_data(b+len, n-len < BB_FL_BLOCK_SIZE ? n-len : BB_FL_BLOCK_SIZE);
    }
    fwrite(b, hbuf[1], 1, fp);
    fclose(fp);
    free(b);
    return 0;
}

static int
mkfat(unsigned char* blist, BbFat16* fat) {
    int i, k, l;
    u16 csum = 0, *p = (u16*)fat, link = 0;

    for(k = 0; k < blocks/BB_FAT16_ENTRIES; k++) {
	memcpy(fat[k].magic, k ? BB_FAT16_LINK_MAGIC : BB_FAT16_MAGIC, sizeof fat[k].magic);
	fat[k].seq = 1;
    }

    for(i = 0; i < blocks; i++)
	BB_FAT16_NEXT(fat,i) = blist[i] ? BB_FAT_BAD : BB_FAT_AVAIL;
    for(i = 0; i < BB_FAT16_BLOCKS; i++) {
	if (BB_FAT16_NEXT(fat,blocks-1-i) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat,blocks-1-i) = BB_FAT_RESERVED;
    }
    for(i = 0; i < BB_SYSTEM_AREA_SIZE/BB_FL_BLOCK_SIZE; i++) {
	if (BB_FAT16_NEXT(fat,i) != BB_FAT_BAD)
	    BB_FAT16_NEXT(fat,i) = BB_FAT_RESERVED;
    }

    /* fix endianness */
    for(i = 0; i < blocks; i++)
	BB_FAT16_NEXT(fat,i) = htons(BB_FAT16_NEXT(fat,i));
    for(i = 0; i < BB_INODE16_ENTRIES; i++) {
	fat->inode[i].block = htons(fat->inode[i].block);
	fat->inode[i].size = htonl(fat->inode[i].size);
    }
    l = blocks-1;
    for(k = blocks/BB_FAT16_ENTRIES; --k >= 0;) {
	fat[k].seq = htonl(fat[k].seq);
	fat[k].link = htons(link);
	/* update version stamp, checksum */
	for(csum = i = 0; i < BB_FL_BLOCK_SIZE/sizeof(u16)-1; i++)
	    csum += ntohs(p[k*BB_FL_BLOCK_SIZE/sizeof(u16)+i]);
	fat[k].cksum = htons(BB_FAT16_CKSUM - csum);
	while(blist[l]) l--;
	link = l;
    }
    return 0;
}

static int
store_identity(BBCHandle h, const char *file)
{
    int fd, rv = BBC_ERROR, len;
    u32 bbID;
    struct stat sb;
    char *buf;

    if ((fd = open(file, O_RDONLY)) < 0) {
	perror(file);
	return rv;
    }
    if (fstat(fd, &sb) < 0) {
	perror(file);
	goto err0;
    }
#ifndef WIN32
    if (!S_ISREG(sb.st_mode)) {
	fprintf(stderr, "%s: not a regular file\n", file);
	goto err0;
    }
#endif
    len = sb.st_size;
    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	goto err0;
    }
    if ((rv = read(fd, buf, len)) < 0) {
	perror(file);
	goto err1;
    }
    if (rv < sizeof(int)) {
	fprintf(stderr, "%s: not enough data\n", file);
        rv = BBC_ERROR;
	goto err1;
    }
    /*bbID = htonl(*(u32 *)buf); */
    bbID = *(u32 *)buf;
    len -= sizeof(bbID);
    TIME(&t1);
    rv = BBCStoreIdentity(h, bbID, buf + sizeof(bbID), len);
    TIME(&t2);
    printf("%s: StoreId returns %d (%dms)\n", file, rv, deltat(t1,t2));

err1:
    free(buf);
err0:
    close(fd);
    return rv;
}

struct objfunc_s {
    char cmd;
    char *name;
    int (*getsize)(BBCHandle);
    int (*getobj)(BBCHandle, void *, int);
    int (*storeobj)(BBCHandle, const void *, int);
} objfunc[] = {
    { 'C', "Cert", BBCCertSize, BBCGetCert, BBCStoreCert },
    { 'P', "PrivateData", BBCPrivateDataSize, BBCGetPrivateData, BBCStorePrivateData },
    { 'R', "Crls", BBCCrlsSize, BBCGetCrls, BBCStoreCrls },
    { 'T', "Tickets", BBCTicketsSize, BBCGetTickets, BBCStoreTickets },
    { 'U', "UserData", BBCUserDataSize, BBCGetUserData, BBCStoreUserData },
    { '\0', NULL, NULL, NULL, NULL }
};

#define RNDFILELEN(x)	(((x)+(BB_FL_BLOCK_SIZE-1)) & ~(BB_FL_BLOCK_SIZE-1))

int
get_object(BBCHandle bh, char *p)
{
    int rv = BBC_ERROR, i, len;
    char cmd = *p++;
    char file[256];
    char *buf;

    i = 0;
    while (1) {
	if (cmd == objfunc[i].cmd)
	    break;
        if (objfunc[i].name == NULL) {
	    printf("Invalid command\n");
	    return rv;
	}
        i++;
    }

    if ((rv = sscanf(p, "%s", file)) < 1)
	file[0] = '\0';

    rv = BBC_ERROR;

    if ((len = objfunc[i].getsize(bh)) < 0) {
	printf("BBC%sSize returns %d\n", objfunc[i].name, len);
	return rv;
    }
    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	return rv;
    }
    TIME(&t1);
    rv = objfunc[i].getobj(bh, buf, len);
    TIME(&t2);
    printf("BBCGet%s returns %d (%dms, %.1f KB/s)\n",
           objfunc[i].name, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );
    if (rv > 0 && strlen(file)) {
        FILE* fp;
        if ((fp = fopen(file, "wb")) == NULL) {
	    perror(file);
        } else {
    	    fwrite(buf, 1, rv, fp);
            fclose(fp);
	}
    }
    free(buf);
    return rv;
}

int
put_object(BBCHandle bh, char *p)
{
    int rv = BBC_ERROR, i, fd;
    int len, filelen;
    char cmd = *p++;
    char file[256];
    char *buf;
    struct stat sb;

    i = 0;
    while (1) {
	if (cmd == objfunc[i].cmd)
	    break;
        if (objfunc[i].name == NULL) {
	    printf("Invalid command\n");
	    return rv;
	}
        i++;
    }

    if ((rv = sscanf(p, "%s", file)) < 1) {
	printf("Local file name required\n");
	return BBC_ERROR;
    }
    rv = BBC_ERROR;
    if (stat(file, &sb) < 0) {
	printf("Stat %s failed\n", file);
	return rv;
    }
    filelen = sb.st_size;
    len = RNDFILELEN(filelen);
    if ((fd = open(file, O_RDONLY)) < 0) {
	printf("Open %s failed\n", file);
	return rv;
    }
    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	return rv;
    }
    memset(buf, 0, len);
    (void) read(fd, buf, filelen);
    TIME(&t1);
    rv = objfunc[i].storeobj(bh, buf, len);
    TIME(&t2);
    printf("BBCStore%s returns %d (%dms, %.1f KB/s)\n",
           objfunc[i].name, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );
    free(buf);
    close(fd);
    return rv;
}

static int
bbc_write_file(BBCHandle bh, const char* in, const char* out) {
    int fd, rv, filelen, len;
    char* buf;
    struct stat sb;
    char error[256];

    rv = BBC_ERROR;
    if (stat(in, &sb) < 0) {
        sprintf(error, "Failed to stat %s", in);
	perror(error);
	return rv;
    }
    filelen = sb.st_size;
    len = RNDFILELEN(filelen);
    if ((fd = open(in, O_RDONLY)) < 0) {
        sprintf(error, "Failed to open %s", in);
	perror(error);
	return rv;
    }
    if ((buf = malloc(len)) == NULL) {
        sprintf(error, "Cannot allocate %d bytes to read %s", len, in);
	perror(error);
        close(fd);
	return rv;
    }
    memset(buf, 0, len);
    (void) read(fd, buf, filelen);

    TIME(&t1);
    rv = __BBC_StoreObject(bh, out, TEMPFILE, buf, len);
    TIME(&t2);
    printf("__BBC_StoreObject %s returns %d (%dms, %.1f KB/s)\n",
           out, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );

    free(buf);
    close(fd);
    return rv;
}


static int
bbc_read_file(BBCHandle bh, const char* in, const char* out) {
    int rv, len;
    char* buf;
    char error[256];

    rv = BBC_ERROR;
    if ((len = __BBC_ObjectSize(bh, in)) < 0) {
	printf("__BBC_ObjectSize %s returns %d\n", in, len);
	return rv;
    }
    if ((buf = malloc(len)) == NULL) {
        sprintf(error, "Cannot allocate %d bytes to read %s", len, in);
	perror(error);
	return rv;
    }
    TIME(&t1);
    rv = __BBC_GetObject(bh, in, buf, len);
    TIME(&t2);
    printf("__BBC_GetObject %s returns %d (%dms, %.1f KB/s)\n",
           in, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );
    if (rv > 0 && strlen(out)) {
        FILE* fp;
        if ((fp = fopen(out, "wb")) == NULL) {
            sprintf(error, "Failed to open %s", out);
            perror(error);
        } else {
    	    fwrite(buf, 1, rv, fp);
            fclose(fp);
	}
    }
    free(buf);
    return rv;
}

static int
bbc_delete_file(BBCHandle bh, const char* file) {
    int rv;
    TIME(&t1);
    rv = __BBC_RemoveObject(bh, file);
    TIME(&t2);
    printf("__BBC_RemoveObject %s returns %d (%dms)\n",
           file, rv, deltat(t1,t2));
    return rv;
}

static int
bbc_move_file(BBCHandle bh, const char* old, const char* new) {
    int rv;
    TIME(&t1);
    rv = __BBC_RenameObject(bh, old, new);
    TIME(&t2);
    printf("__BBC_RenameObject %s to %s returns %d (%dms)\n",
           old, new, rv, deltat(t1,t2));
    return rv;
}


static int
bbc_list_files(BBCHandle bh) {
    int rv;
    TIME(&t1);
    rv = __BBC_ListObjects(bh);
    TIME(&t2);
    printf("__BBC_ListObjects returns %d (%dms)\n", rv, deltat(t1,t2));
    return rv;
}

int
remove_content(BBCHandle bh, char *p)
{
    int rv;
    char cids[256];
    unsigned int cid;

    if ((rv = sscanf(p, "%s", cids)) < 1) {
	printf("Content id required\n");
	return BBC_ERROR;
    }

    cid = strtoul(cids, NULL, 16);
    TIME(&t1);
    rv = BBCRemoveContent(bh, cid);
    TIME(&t2);
    printf("BBCRemoveContent cid %x returns %d (%dms)\n",
           cid, rv, deltat(t1,t2));
    return rv;
}

#ifndef BBC_IQAHC_DIAG
int BBCStoreArbFile(BBCHandle h, char* filename, const void *buf, int size);

int 
store_arb_file(BBCHandle bh, char *p)
{
    char file[256], *buf;
    struct stat sb;
    int len, fd, rv;

    if ((rv = sscanf(p, "%s", file)) < 1) {
        printf("Local file name and content id required\n");
        return BBC_BADARG;
    }

    if (stat(file, &sb) < 0) {
        printf("Stat %s failed\n", file);
        return BBC_NOFILE;
    }

    len = (sb.st_size +BB_FL_BLOCK_SIZE-1) & ~(BB_FL_BLOCK_SIZE-1);
    if ((fd = open(file, O_RDONLY)) < 0) {
        printf("Open %s failed\n", file);
        return BBC_ERROR;
    }
    if ((buf = malloc(len)) == NULL) {
        perror("malloc");
        return BBC_NOMEM;
    }
    memset(buf, 0, len);
    printf("reading file...\n");
    (void) read(fd, buf, sb.st_size);
    printf("BBC store file %s ...\n", file);
    TIME(&t1);
    rv = BBCStoreArbFile(bh, file, buf, len);
    TIME(&t2);
    printf("BBCStoreArbFile returns %d (%dms, %.1f KB/s)\n",
            rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );
    free(buf);
    close(fd);
    return rv;
}
#endif

int
store_content(BBCHandle bh, char *p)
{
    int rv, len, fd;
    char file[256];
    char cids[256];
    char *buf;
    struct stat sb;
    unsigned int cid;

    if ((rv = sscanf(p, "%s %s", file, cids)) < 2) {
	printf("Local file name and content id required\n");
	return BBC_BADARG;
    }
    cid = strtoul(cids, NULL, 16);
    if (stat(file, &sb) < 0) {
	printf("Stat %s failed\n", file);
	return BBC_NOFILE;
    }
    len = sb.st_size;
    if ((fd = open(file, O_RDONLY)) < 0) {
	printf("Open %s failed\n", file);
	return BBC_ERROR;
    }
    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	return BBC_NOMEM;
    }
    printf("reading content...\n");
    (void) read(fd, buf, len);
    printf("BBCStoreContent...\n");
    TIME(&t1);
    rv = BBCStoreContent(bh, cid, buf, len);
    TIME(&t2);
    printf("BBCStoreContent cid %x returns %d (%dms, %.1f KB/s)\n", 
           cid, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );
    free(buf);
    close(fd);
    return rv;
}

int
get_content(BBCHandle bh, char *p)
{
    int rv, len;
    char file[256];
    char cids[256];
    char *buf;
    unsigned int cid;
    int type;

    if ((rv = sscanf(p, "%s %s", file, cids)) < 2) {
	printf("Local file name and content id required\n");
	return BBC_BADARG;
    }
    cid = strtoul(cids, NULL, 16);
    TIME(&t1);
    len = BBCContentSize(bh, cid, &type);
    TIME(&t2);
    if (len < 0) {
        printf("Error getting size of content %x: %d (%dms)\n",
               cid, len, deltat(t1, t2));
        return len;
    }
    else printf("BBCContentSize for content %x: size=%d, type=%d (%dms)\n",
                cid, len, type, deltat(t1, t2));

    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	return BBC_NOMEM;
    }

    TIME(&t1);
    rv = BBCGetContent(bh, cid, buf, len, &type);
    TIME(&t2);
    printf("BBCGetContent cid %x returns %d (%dms, %.1f KB/s)\n",
           cid, rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)) );

    if (rv > 0 && strlen(file)) {
        FILE* fp;
        if ((fp = fopen(file, "wb")) == NULL) {
            perror(file);
        } else {
    	    fwrite(buf, 1, rv, fp);
            fclose(fp);
        }
    }
    free(buf);
    return rv;
}

#define MAX_DIR	410
ContentId cidlist[MAX_DIR];
int cidsize[MAX_DIR];

int
get_content_list(BBCHandle bh, char *p)
{
    int rv, i;

    TIME(&t1);
    rv = BBCContentListSize(bh);
    TIME(&t2);
    printf("BBCContentListSize returns %d (%dms)\n", rv, deltat(t1,t2));
    if (rv < 0)
        return rv;
    memset(cidlist, 0, sizeof(cidlist));
    memset(cidsize, 0, sizeof(cidsize));
    TIME(&t1);
    rv = BBCGetContentList(bh, cidlist, cidsize, rv);
    TIME(&t2);
    printf("BBCGetContentList returns %d (%dms)\n", rv, deltat(t1,t2));
    for (i = 0; i < rv; i++)
	printf("cid %x, size %d\n", cidlist[i], cidsize[i]);
    return rv;
}

int
get_state(BBCHandle bh, char *p)
{
    int rv, cid, len, dirty;
    char cids[256], out[256];
    EccSig sig;
    char *buf;

    if ((rv = sscanf(p, "%s", cids)) < 1) {
	printf("content id required\n");
	return BBC_BADARG;
    }
    cid = strtoul(cids, NULL, 16);
    TIME(&t1);
    len = BBCStateSize(bh, cid);
    TIME(&t2);
    printf("BBCStateSize returns %d (%dms)\n", len, deltat(t1,t2));
    if (len > 0) {
        buf = malloc(len);
        TIME(&t1);
        rv = BBCGetState(bh, cid, buf, len, sig, &dirty);
        TIME(&t2);
        printf("BBCGetState returns %d (%dms, %.1f KB/s)\n",
               rv, deltat(t1, t2), getKBs(len, deltat(t1,t2)));
        if (rv >= 0) {
            int fd;
            printf("  sig = %08x %08x ... %08x dirty%d\n", sig[0], sig[1], sig[15], dirty);
#ifndef WIN32
            snprintf(out, sizeof(out), "%08x.sta", cid);
#else
            _snprintf(out, sizeof(out), "%08x.sta", cid);
#endif
            if ((fd = open(out, O_CREAT|O_WRONLY)) >= 0) {
                write(fd, buf, len);
                close(fd);
            }
        }
        free(buf);
    }
    else rv = len;
    return rv;
}

int
get_state_list(BBCHandle bh, char *p)
{
    int rv, i;

    TIME(&t1);
    rv = BBCStateListSize(bh);
    TIME(&t2);
    printf("BBCStateListSize returns %d (%dms)\n", rv, deltat(t1,t2));
    memset(cidlist, 0, sizeof(cidlist));
    if (rv > 0) {
        TIME(&t1);
        rv = BBCGetStateList(bh, cidlist, rv);
        TIME(&t2);
        printf("BBCGetStateList returns %d (%dms)\n", rv, deltat(t1,t2));
        for (i = 0; i < rv; i++)
	    printf("cid %x\n", cidlist[i]);
    }
    return rv;
}

int
rename_state(BBCHandle bh, char *p)
{
    int rv;
    char ocids[256];
    char ncids[256];
    unsigned int ocid, ncid;

    if ((rv = sscanf(p, "%s %s", ocids, ncids)) < 2) {
	printf("Old and new content id required\n");
	return BBC_BADARG;
    }
    ocid = strtoul(ocids, NULL, 16);
    ncid = strtoul(ncids, NULL, 16);
    TIME(&t1);
    rv = BBCRenameState(bh, ocid, ncid);
    TIME(&t2);
    printf("BBCRenameState ocid %x ncid %x returns %d (%dms)\n",
           ocid, ncid, rv, deltat(t1,t2));
    return rv;
}

int
verify_sk(BBCHandle bh, char *p)
{
    int rv, len, fd, force;
    char file[256];
    char *buf;
    struct stat sb;

    if ((rv = sscanf(p, "%s %d", file, &force)) < 1) {
	printf("Local file name required\n");
	return BBC_BADARG;
    }
    if (stat(file, &sb) < 0) {
	printf("Stat %s failed\n", file);
	return BBC_NOFILE;
    }
    len = sb.st_size;
    if ((fd = open(file, O_RDONLY)) < 0) {
	printf("Open %s failed\n", file);
	return BBC_ERROR;
    }
    if ((buf = malloc(len)) == NULL) {
	perror("malloc");
	return BBC_NOMEM;
    }
    (void) read(fd, buf, len);
    TIME(&t1);
    if (rv < 2) {
        /* Force not specified */
        rv = BBCVerifySKSA(bh, buf, len);
    }
    else {
        rv = BBCVerifySKSA2(bh, buf, len, force);
    }
    TIME(&t2);
    printf("BBCVerifySKSA returns %d (%dms)\n", rv, deltat(t1,t2));
    free(buf);
    close(fd);
    return rv;
}

/*
 * Sample code to invoke BBCAuthChallenge
 */
int
authenticate_bb(BBCHandle h, u32 bbid, BbEccCert* bbcert)
{
    SHA1Context sha;
    BbShaHash hash_data;
    u32 hash_input[16];
    BbEccSig sig;
    BbEccPublicKey publickey;
    int i, rv;
    BSL_boolean res;
    
#ifndef WIN32
    struct timeval tv;
    
    gettimeofday(&tv, NULL);
    srand(bbid + tv.tv_sec + tv.tv_usec);
#else
    srand(bbid + time(NULL));
#endif
    hash_input[0] = bbid;
    for (i = 1; i < 16; i++)
        hash_input[i] = rand();
    
    /* compute hash */
    SHA1Reset(&sha);
    SHA1Input(&sha, (u8 *)hash_input, sizeof hash_input);
    SHA1Result(&sha, (u8*) hash_data);
    
    /* hash data passed in native endian format */
    TIME(&t1);
    rv = BBCAuthChallenge(h, hash_data, sizeof hash_data, sig, sizeof sig);
    TIME(&t2);
    if (rv < 0) {
        fprintf(stderr, "BBCAuthChallenge error %d (%dms)\n",
                rv, deltat(t1,t2));
        return rv;
    }
    fprintf(stderr, "BBCAuthChallenge returned (%dms)\n", deltat(t1,t2));
    
    /* get public key from cert */
    for (i = 0; i < sizeof(BbEccPublicKey)/4; i++) {
        publickey[i] = ntohl(bbcert->publicKey[i]);
    }
    
    /* signature is returned in native endianness */
    fprintf(stderr, "Verifying signature for %d\n", (int) bbid);
    bsl_verify_ecc_sig((u8 *)hash_data, sizeof(BbShaHash), publickey,
                       sig, &res, API_IDENTITY);
    if (res != BSL_TRUE) {
        fprintf(stderr, "BBCAuthChallenge signature mismatch\n");
        return BBC_ERROR;
    }
    
    return BBC_OK;
}

int
authenticate(BBCHandle bh, char *p)
{
    int len, fd, rv;
    char file[256];
    char *buf;
    struct stat sb;
    int bbid = 0;

    if (sscanf(p+1, "%d %s", &bbid, file) != 2) {
        fprintf(stderr, "usage: W bbid file\n");
        return BBC_BADARG;
    }
    if (stat(file, &sb) < 0) {
        printf("Stat %s failed\n", file);
        return BBC_NOFILE;
    }
    len = sb.st_size;
    if (len < sizeof (BbEccCert)) {
        printf("%s too small to hold a BbEccCert\n", file);
        return BBC_BADLENGTH;
    }
    if ((fd = open(file, O_RDONLY)) < 0) {
        printf("Open %s failed\n", file);
        return BBC_ERROR;
    }
    if ((buf = malloc(len)) == NULL) {
        perror("malloc");
        return BBC_NOMEM;
    }

    (void) read(fd, buf, len);

    if ((rv = authenticate_bb(bh, bbid, (BbEccCert*) buf)) == BBC_OK) {
        printf("BBCAuthChallenge passed\n");
    }
    else {
        printf("BBCAuthChallenge failed\n");
    }

	free(buf);
    close(fd);
    return rv;
}

#ifdef WIN32
#if TEST_THREAD
HANDLE hTestThread = NULL;
unsigned __stdcall do_test(LPVOID lpParameter)
{
	BBCHandle bh = (BBCHandle) lpParameter;
    int bbid = 0, rv = 0;
    char certbuf[512];
	while(rv >= 0) {
//	    rv = BBCGetIdentity(bh, &bbid, certbuf, sizeof certbuf);
		rv = store_content(bh, "testfile.408 408");
		printf("store_content returned %d\n", rv);
	}
	return 0;
}

void bb_test_thread_start(BBCHandle bh)
{
    unsigned int dwId;    
	printf("Starting test thread\n");
	hTestThread = (HANDLE) _beginthreadex(NULL, 0, &do_test, bh, 0, &dwId);
}

void bb_test_thread_end()
{
    if (hTestThread) {
        printf("Stopping test thread\n");
	    TerminateThread(hTestThread, -1);
        CloseHandle(hTestThread);
        hTestThread = NULL;
    }
}
#endif /* TEST_THREAD */
#endif /* WIN32 */

/*
 * Data for BBC card interface
 */
char udevname[256] = "/dev/usb/bbrdb0";
static BBCHandle bh = -1;

int proc_bbc_command(char* p) {
    char file[256];
#ifdef WIN32
    char *rname, *wname;
#endif
    int rv = 0;

    memset(file, 0, sizeof file);
    if (*p == 'B') { /* BBC Card Init */
        if (bh >= 0) {
            printf("BBCInit: handle already valid, close it first\n");
            return BBC_BADARG;
        }
        TIME(&t1);
#ifndef WIN32
        rv = BBCInit(udevname, BBC_SYNC);
#else
        rv = BBCInit(BBC_SYNC);
#endif
        TIME(&t2);
        bh = rv;
#ifndef WIN32
        printf("BBCInit(%s, SYNC) returns %d (%dms)\n",
               udevname, rv, deltat(t1, t2));
#endif
        if (bh >= 0) {
            ifd = BBCGetFd(bh, 1);
            ofd = BBCGetFd(bh, 0);
#ifdef WIN32
            rname = BBCGetDevName(bh, 0);
            wname = BBCGetDevName(bh, 1);
            printf("BBCInit(%s, %s) returns %d (%dms)\n",
                   rname, wname, rv, deltat(t1,t2));
#endif
            
        }
#ifdef WIN32
        else {
            printf("BBCInit(SYNC) returned %d (%dms)\n", rv, deltat(t1,t2));
        }
#endif
        bbc_mode = BBC_OPEN_B;
    }
    else if (*p == 'A') { /* BBC Card Present */
        TIME(&t1);
#ifndef BBC_IQAHC_DIAG /* Not used by diagnostics */
	if (*(p+1) == 'F') {
		rv = store_arb_file(bh, p+2);
	} else 
#endif
        	rv = BBCCardPresent(bh);
        TIME(&t2);
#ifndef BBC_IQAHC_DIAG /* Not used by diagnostics */
	if (*(p+1) == 'F') {
		printf("BBCStoreArbFile %s %d, (%dms)\n", p+2, rv, deltat(t1,t2)); 
	}  else
#endif	
	        printf("BBCCardPresent %d (%dms)\n", rv, deltat(t1,t2));
#ifndef BBC_IQAHC_DIAG /* Not used by diagnostics */
    } else if (*p == 'W') { /* BBC Authentication Challenge */
        rv = authenticate(bh, p+1);
#endif
    } else if (*p == 'C') { /* BBC Card Stats */
        int sysSize, contentSize, freeSize, badSize, cardsize;
        sysSize = contentSize = freeSize = cardsize = badSize = -1;
        TIME(&t1);
        if (*(p+1) == 'o') {
            /* old style */
            rv = BBCStats(bh, &cardsize, &sysSize, &freeSize, &badSize);
            TIME(&t2);
            printf("BBCStats(%s): size %d, freeSpace %d, rsvd %d, bad %d ret %d (%dms)\n",
               udevname, cardsize, freeSize, sysSize, badSize, rv, deltat(t1,t2));
	} else {
            rv = BBCStats2(bh, &cardsize, &sysSize, &contentSize, &freeSize);
            TIME(&t2);
            printf("BBCStats2(%s): size %d, sysSpace: %d, contentSpace: %d, freeSpace: %d ret %d (%dms)\n",
               udevname, cardsize, sysSize, contentSize, freeSize, rv, deltat(t1,t2));
	}
    } else if (*p == 'I') { /* BCC Get Player Identity */
        int bbid = 0;
        TIME(&t1);
        rv = BBCGetPlayerIdentity(bh, &bbid);
        TIME(&t2);
        printf("BBCGetPlayerIdentity(%s): bbid 0x%x, ret %d (%dms)\n",
               udevname, bbid, rv, deltat(t1,t2));
    } else if (*p == 'G' && *(p+1) == 'I') { /* BBC Get Identity */
        int bbid = 0;
        char certbuf[512];
        if ((rv = sscanf(p+2, "%s", file)) < 1) {
            file[0] = '\0';
        }
        TIME(&t1);
        rv = BBCGetIdentity(bh, &bbid, certbuf, sizeof certbuf);
        TIME(&t2);
        printf("BBCGetIdentity(%s): bbid 0x%x, ret %d (%dms)\n",
               udevname, bbid, rv, deltat(t1,t2));
        if (rv > 0 && strlen(file)) {
            FILE* fp;
            if ((fp = fopen(file, "wb")) == NULL) {
                perror(file);
            } else {
                fwrite(&bbid, sizeof(bbid), 1, fp);
                fwrite(certbuf, 1, rv, fp);
                fclose(fp);
            }
        }
#ifndef BBC_IQAHC_DIAG
    } else if (*p == 'P' && *(p+1) == 'I') { /* BBC Store Identity */
        if ((rv = sscanf(p+2, "%s", file)) < 1) {
            printf("PI: local file name required\n");
            rv = BBC_BADARG;
        }
        else
            rv = store_identity(bh, file);
    } else if (*p == 'F') { /* BBC Format Card */
        int clear_bad_blocks;
        if ((rv = sscanf(p+1, "%d", &clear_bad_blocks)) < 1) {
            clear_bad_blocks = 0;
        }
        TIME(&t1);
        rv = BBCFormatCard2(bh, clear_bad_blocks);
        TIME(&t2);
        printf("BBCFormatCard returns %d (%dms)\n", rv, deltat(t1,t2));
#endif /* BBC_IQAHC_DIAG */
    } else if (*p == 'G') { /* BBC Get Object */
        rv = get_object(bh, p+1);
    } else if (*p == 'H') { /* BBC Set LED */
        int ledval;
        if ((rv = sscanf(p+1, "%d", &ledval)) < 1) {
            TIME(&t1);
            rv = BBCGetLed(bh, &ledval);
            TIME(&t2);
            printf("BBCGetLed returns %d, ledmask %d (%dms)\n",
                   rv, ledval, deltat(t1,t2));
        } else {
            TIME(&t1);
            rv = BBCSetLed(bh, ledval);
            TIME(&t2);
            printf("BBCSetLed returns %d (%dms)\n", rv, deltat(t1,t2));
        }
    } else if (*p == 'J') { /* BBC Set Time */        
#ifndef WIN32
        time_t curtime = time(NULL);
        TIME(&t1);
        rv = BBCSetTime(bh, curtime);
        TIME(&t2);
        printf("BBCSetTime returns %d (%dms)\n", rv, deltat(t1,t2));
#else
        time_t curtime;
        struct tm* gmt;
        time(&curtime);
        TIME(&t1);
        rv = BBCSetTime(bh, curtime);
        TIME(&t2);
        gmt = gmtime(&curtime);
        printf("BBCSetTime returns %d: %s (%dms)\n",
               rv, asctime(gmt), deltat(t1,t2));
#endif
    } else if (*p == 'L') { /* BBC GetContentList */
        rv = get_content_list(bh, p+1);
    } else if (*p == 'U') { /* BBC GetContent */
        rv = get_content(bh, p+1);
    } else if (*p == 'M') { /* BBC StoreContent */
        rv = store_content(bh, p+1);
    } else if (*p == 'R') { /* BBC RemoveContent */
        rv = remove_content(bh, p+1);
#ifndef BBC_IQAHC_DIAG
    } else if (*p == 'P') { /* BBC Store Object */
        rv = put_object(bh, p+1);
    } else if (*p == 'V') { /* BBC Verify SKSA */
        rv = verify_sk(bh, p+1);
    } else if (*p == 'Y') { /* BBC GetState */
        rv = get_state(bh, p+1);
    } else if (*p == 'E') { /* BBC GetStateList */
        rv = get_state_list(bh, p+1);
    } else if (*p == 'Z') { /* BBC RenameState */
        rv = rename_state(bh, p+1);
#endif /* BBC_IQAHC_DIAG */
    } else if (*p == 'Q') { /* BBC Card Close */
        //rv = BBCSetLed(bh, BBC_LED_OFF);
        TIME(&t1);
        rv = BBCClose(bh);
        TIME(&t2);
        printf("BBCClose(%s): ret %d (%dms)\n", udevname, rv, deltat(t1,t2));
        bh = ifd = ofd = -1;
        bbc_mode = BBC_CLOSED;
    }
#ifndef BBC_IQAHC_DIAG
    else if (*p == 'X') {
        char cids[256];
        unsigned int cid;
        if ((rv = sscanf(p+1, "%s", cids)) < 1) {
            fprintf(stderr, "usage: X cid\n");
            return BBC_BADARG;
        } 
        cid = strtoul(cids, NULL, 16);
        TIME(&t1);
        rv = BBCListContentFiles(bh, cid);
        TIME(&t2);
        printf("BBCListContentFiles returns %d (%dms)\n",
               rv, deltat(t1,t2));        
    }
#endif /* BBC_IQAHC_DIAG */
    else {
        rv = BBC_UNKNOWN;
    }

    /* 
     * Bad handle indicates BBCInit was not called
     * Remind people to call BBCInit first
     */
    if (rv == BBC_BADHANDLE && bbc_mode == BBC_CLOSED) {
        printf("Connection to BB player not initialized.\n");
        printf("Please use 'B' (BBCInit) to connect to the BB player.\n");
    }

    return rv;
}

int proc_diag_command(char* p) {
    int rv = 0;

    if (*p == 'w') { /* scan bad blocks */
        int rewrite = 0;
#ifndef BBC_IQAHC_DIAG
        if ((rv = sscanf(p+1, "%d", &rewrite)) < 1) {
            rewrite = 0;
        }
#endif
        TIME(&t1);
        rv = BBCDiagScanBadBlocks(bh, rewrite);
        TIME(&t2);
        printf("BBCDiagScanBadBlocks(%s): ret %d (%dms)\n",
               udevname, rv, deltat(t1,t2));
    }
    else if (*p == 'n') {
        TIME(&t1);
        rv = BBCDiagSKSABlocksHash(bh);
        TIME(&t2);
        printf("BBCDiagSKSABlocksHash(%s): ret %d (%dms)\n",
               udevname, rv, deltat(t1,t2));
    }
#ifdef WIN32
    else if (*p == 'i') {
        BBCDiagPrintInfo();
    }
#endif
#if DUMP_RAW_BLOCKS
    else if (*p == 'v') { /* read block as a fat and dump inode tables */
        int blkno;
        if ((rv = sscanf(p+1, "%d", &blkno)) < 1) {
            if (rv == EOF) {
                /* No argument - using -1 to have libbbc figure out where the FAT table is */
                blkno = -1;
            }
            else {
                /* Got a string */
                fprintf(stderr, "usage: v [blkno]\n");
                return BBC_BADARG;
            }
        }
        TIME(&t1);
        rv = osBbFDump(bh, blkno);
        TIME(&t2);
        fprintf(stderr, "osBbFDump %d returns %d (%dms)\n", blkno, rv, deltat(t1,t2));
    } 
#ifndef WIN32
    else if (*p == 'e') { /* dump a block in ascii */
        int blkno;
        int i, j;
        unsigned short *cp;
        if ((rv = sscanf(p+1, "%d", &blkno)) < 1) {
            fprintf(stderr, "usage: e blkno\n");
            return BBC_BADARG;
        }
        fprintf(stderr, "Read and dump contents of block %d:\n", blkno);
        if ((rv = read_block(block, NULL, blkno)) < 0) {
            fprintf(stderr, "read of blk %d failed\n", blkno);
            return rv;
        }
        cp = (unsigned short *)block;
        for (j = 0; j < 512; j++) {
            printf("%08x -> ", j * 32);
            for (i = 0; i < 16; i++, cp++)
                printf("%04x ", ntohs(*cp));
            printf("\n");
        }
    } else if (*p == 'E') { /* dump a block to a file */
        int blkno;
        int fd;
        char fname[64];
        if ((rv = sscanf(p+1, "%d", &blkno)) < 1) {
                fprintf(stderr, "usage: E blkno\n");
                return BBC_BADARG;
        }
        fprintf(stderr, "Read and dump contents of block %d:\n", blkno);
        if ((rv = read_block(block, NULL, blkno)) < 0) {
            fprintf(stderr, "read of blk %d failed\n", blkno);
            return rv;
        }
        sprintf(fname, "block.%d.p%d", blkno, getpid());
        if ((fd = open(fname, O_CREAT|O_RDWR, 0644)) < 0) {
            perror(fname);
            return BBC_BADARG;
        }
            if (write(fd, block, BB_FL_BLOCK_SIZE) < 0)
                perror("write");
            close(fd);
    }
#endif
#endif  /* DUMP_RAW_BLOCKS */
    else {
        rv = BBC_UNKNOWN;
    }
    
    return rv;
}

int proc_nonbbc_command(char* p) {
    int rv = BBC_UNKNOWN;

#ifndef WIN32
    char file[256], file2[256];
    unsigned int hbuf[2];
    int i;

    memset(hbuf, 0, sizeof hbuf);
    memset(file, 0, sizeof file);
    memset(file2, 0, sizeof file2);
    rv = 0;
    if (*p == 'u') { /* set usb devname */
        if ((rv = sscanf(p+1, "%s", file)) < 1) {
            printf("Current USB device: %s\n", udevname);
        } else {
            strncpy(udevname, file, sizeof udevname);
            printf("New USB device: %s\n", udevname);
        }
        rv = 0;
    } 
    else if (*p == 'O') { /* open USB with no BBC (talks to usbmon) */
        if (bh >= 0) {
            printf("Open: device already open\n");
            return BBC_DEVBUSY;
        }
        TIME(&t1);
        rv = BBCOpenMux(udevname, BBC_SYNC);
        TIME(&t2);
        printf("BBCOpenMux(%s, SYNC) returns %d (%dms)\n",
               udevname, rv, deltat(t1,t2));
        bh = rv;
        if (bh >= 0) {
            ifd = BBCGetFd(bh, 1);
            ofd = BBCGetFd(bh, 0);
        }
        bbc_mode = BBC_OPEN_O;
    } 
    else if (*p == 'p') { /* ping */
        hbuf[0] = REQ_PING;
        send_cmd(hbuf, 8);
        read_rsp(hbuf, 8);
        if (hbuf[0] != 255-REQ_PING || hbuf[1] != 0) {
            fprintf(stderr, "sync loss\n");
            return BBC_SYNCLOST;
        }
    } else if (*p == 'o') { /* off */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        hbuf[0] = REQ_POWER_OFF;
        send_cmd(hbuf, 8);
        read_rsp(hbuf, 8);
        if (hbuf[0] != 255-REQ_POWER_OFF || hbuf[1] != 0) {
            fprintf(stderr, "power off failed\n");
            return BBC_SYNCLOST;
        }
    } else if (*p == 'a') { /* add file */
        if ((rv = sscanf(p+1, "%s %s", file, file2)) < 1) {
            fprintf(stderr, "usage: a file [name]\n");
            return BBC_BADARG;
        }
        if (bbc_mode == BBC_OPEN_O) {
            write_file(file, rv == 1 ? basename(file) : file2);
        }
        else bbc_write_file(bh, file, rv == 1 ? basename(file) : file2);
    } else if (*p == 'c') { /* copy file */
        if ((rv = sscanf(p+1, "%s %s", file, file2)) < 1) {
            fprintf(stderr, "usage: c file [name]\n");
            return BBC_BADARG;
        }
        if (bbc_mode == BBC_OPEN_O) {
            read_file(file, rv == 1 ? file : file2);
        }
        else bbc_read_file(bh, file, rv == 1 ? file : file2);
    } else if (*p == 'd') { /* delete file */
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: d file\n");
            return BBC_BADARG;
        }
        if (bbc_mode == BBC_OPEN_O) {
            delete_file(file, 1);
        }
        else {
            bbc_delete_file(bh, file);
        }
    } else if (*p == 'm') { /* move file */
        if ((rv = sscanf(p+1, "%s %s", file, file2)) < 2) {
            fprintf(stderr, "usage: m old new\n");
            return BBC_BADARG;
        }
        if (bbc_mode == BBC_OPEN_O) {
            move_file(file, file2);
        }
        else {
            bbc_move_file(bh, file, file2);
        }
    } else if (*p == 'f') { /* reload filesystem */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        hbuf[0] = REQ_FS_INIT;
        send_cmd(hbuf, 8);
        read_rsp(hbuf, 8);
        if (hbuf[0] != 255-REQ_FS_INIT || hbuf[1] & 0x80000000)
            fprintf(stderr, "fs reload failed %d\n", hbuf[1]);
        blist_good = 0;
    } else if (*p == 'l') { /* list directory */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        else if (bbc_mode == BBC_OPEN_O) {
            hbuf[0] = REQ_READ_DIR;
            send_cmd(hbuf, 8);
            read_rsp(hbuf, 8);
            printf("read dir %d\n", hbuf[1]);
            if (hbuf[0] != 255-REQ_READ_DIR || hbuf[1] & 0x80000000) {
                fprintf(stderr, "read directory failed %d\n", hbuf[1]);
            } else {
                int size;
                for(i = 0; i < hbuf[1]; i++) {
                    printf("read file %d\n", i);
                    read_data(file, 16);
                    read_data(&size, 4); size = ntohl(size);
                    printf("%.12s %d\n", file, size);
                }
            }
        }
        else {
            bbc_list_files(bh);
        }
    } else if (*p == 'k') { /* update kernel */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: k file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        write_blocks(file, SK_OFF, SK_BLOCKS, 0);
    } else if (*p == 'K') { /* copy kernel */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: K file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        read_blocks(file, SK_OFF, SK_BLOCKS);
    } else if (*p == 's') { /* update sys app */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: s file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        write_blocks(file, SA0_OFF, SA_BLOCKS, SA0_OFF+1);
    } else if (*p == 'S') { /* copy sys app */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: S file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        read_blocks(file, SA0_OFF, SA_BLOCKS);
    } else if (*p == 't') { /* update license */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: t file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        write_blocks(file, SL0_OFF, SL_BLOCKS, SA0_OFF);
    } else if (*p == 'T') { /* copy license */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if (sscanf(p+1, "%s", file) != 1) {
            fprintf(stderr, "usage: T file\n");
            return BBC_BADARG;
        }
        read_blist(1);
        read_blocks(file, SL0_OFF, SL_BLOCKS);
    } else if (*p == 'x') { /* checksum */
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        if ((rv = sscanf(p+1, "%s %s", file, file2)) < 1) {
            fprintf(stderr, "usage: x file [name]\n");
            return BBC_BADARG;
        }
        hbuf[0] = REQ_SUM_FILE;
        hbuf[1] = strlen(file)+1;
        send_cmd(hbuf, 8);
        send_data(file, RND(strlen(file)+1));
        read_rsp(hbuf, 8);
        if (hbuf[0] != 255-REQ_SUM_FILE || (hbuf[1]&0x80000000)) {
            fprintf(stderr, "file sum of %s failed\n", file);
            return BBC_ERROR;
        }
        if (rv > 1) {
            FILE *fp = fopen(file2, "rb");
            unsigned short s = 0;
            if (fp == NULL) {
                perror(file2);
                return BBC_BADARG;
            }
            while(fread(block, 1, sizeof block, fp) > 0) {
                for(i = 0; i < sizeof block; i++)
                    s += block[i];
                memset(block, 0, sizeof block);
            }
            fclose(fp);
            printf("sum %04x %04x\n", hbuf[1], s);
        } else
            printf("sum %04x\n", hbuf[1]);
    } else if (*p == 'z') { /* reformat file system */
        int j, k;
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        read_blist(1);
        memset(fat, 0x0, sizeof fat);
        /* create an empty superblock */
        mkfat(blist, (BbFat16*)fat);
        k = (blocks/BB_FAT16_ENTRIES-1);
        for(j = i = 0; i < BB_FAT16_BLOCKS; j++) {
            if(blist[blocks-1-j] == 0) {
                write_block(fat+k, 0, blocks-1-j);
                if (--k < 0)
                    k = (blocks/BB_FAT16_ENTRIES-1);
                i++;
            }
        }
    } 
    else if (*p == 'b') {
        if (bbc_mode == BBC_CLOSED) {
            fprintf(stderr, "BBC device not open\n");
            return BBC_NODEV;
        }
        read_blist(0);
        for(i = 0; i < blocks; i++) {
            printf("%c", blist[i] == 0 ? '.' : '@');
            if (i % 64 == 63) printf("\n");
        }
    }
    else {
        rv = BBC_UNKNOWN;
    }
#endif  /* !WIN32 */

    return rv;
}

int proc_command(char *p) {
    int rv = 0;

    if (strncmp(p, "run", 3) == 0) {
        rv = run_file(p);
    }
    else if (strncmp(p, "set", 3) == 0) {
        char var[32], value[32];
        /* Sets variable */
        if ((rv = sscanf(p, "set %s %s", var, value)) < 1) {
            printf("bbc_log_level = %d\n", bbc_log_level);
            printf("bbc_log_file  = %s\n", bbc_log_file == NULL? "NULL": bbc_log_file);
            printf("bbc_diag_mode = %d\n", bbc_diag_mode);
        }        
        else if (strcmp(var, "bbc_log_level") == 0) {
            if (rv >= 2) {
                BBCSetLogLevel(atoi(value));
            }
            printf("bbc_log_level = %d\n", bbc_log_level);
        }
        else if (strcmp(var, "bbc_diag_mode") == 0) {
            if (rv >= 2) {
                int val = atoi(value);
                BBCSetDiagMode(val);
                diag_mode = val;
            }
            printf("bbc_diag_mode = %d\n", bbc_diag_mode);
        }
        else if (strcmp(var, "bbc_log_file") == 0) {
            if (rv >= 2) {
                BBCSetLogFile(strdup(value));
            }
            printf("bbc_log_file  = %s\n", bbc_log_file == NULL? "NULL": bbc_log_file);
        }
        else {
            printf("Unknown variable %s\n", var);
        }
    }
#ifdef WIN32
#if TEST_THREAD
    else if (strcmp(p, "start") == 0) {
        bb_test_thread_start(bh);
    } else if (strcmp(p, "stop") == 0) {
        bb_test_thread_end();
    }
#endif
#endif
    else if (*p == 'h' || *p == '?') { /* help */
        printf("\t%s\n", version);
        printf("\tBBC Commands:\n"
               "\tB             - BBCInit for current BBC device\n"
               "\tA             - BBCCardPresent\n"
               "\tC             - BBCStats\n"
#ifndef BBC_IQAHC_DIAG
               "\tW bbid file   - BBAuthChallenge\n"
               "\tAF file       - Add arbitary file\n"
#endif
               "\tI             - BBCGetPlayerIdentity\n"
               "\tGI [file]     - BBCGetIdentity [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPI file       - BBCStoreIdentity from file\n"
#endif
               "\tGC [file]     - BBCGetCert [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPC file       - BBCStoreCert from file\n"
#endif
               "\tGP [file]     - BBCGetPrivateData [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPP file       - BBCStorePrivateData from file\n"
#endif
               "\tGR [file]     - BBCGetCrls [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPR file       - BBCStoreCrls from file\n"
#endif
               "\tGT [file]     - BBCGetTickets [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPT file       - BBCStoreTickets from file\n"
#endif
               "\tGU [file]     - BBCGetUserData [to file]\n"
#ifndef BBC_IQAHC_DIAG
               "\tPU file       - BBCStoreUserData from file\n"
               "\tF [clear]     - BBCFormatCard\n"
               "\t   clear      - if bad block markings should be cleared from FAT\n"
#endif
               "\tH ledval      - BBCSetLed\n"
               "\tJ             - BBCSetTime\n"
               "\tL             - BBCGetContentList\n"
               "\tU file cid    - BBCGetContent file content-id\n"
               "\tM file cid    - BBCStoreContent file content-id\n"
               "\tR cid         - BBCRemoveContent content-id\n"
#ifndef BBC_IQAHC_DIAG
               "\tV file [force]- BBCVerifySKSA with file\n"
               "\tX cid         - BBCListContentFiles - list files related to cid\n"
               "\tE             - BBCGetStateList\n"
               "\tY cid         - BBCGetState cid\n"
               "\tZ ocid ncid   - BBCRenameState old-cid new-cid\n"
#endif
               "\tQ             - BBCClose\n");

        if (bbc_diag_mode) {
            printf(
               "\n\tDiagnostic commands\n"
#ifdef WIN32
               "\ti             - list system information\n"
#endif
#ifndef BBC_IQAHC_DIAG
               "\tw [rewrite]   - scan card for bad blocks (manufacturer and DBE)\n"
               "\t   rewrite    - attempt to fix DBE by rewriting block or not\n"
#else
               "\tw             - scan card for bad blocks (manufacturer and DBE)\n"
#endif
               "\tn             - list sha1 hash for each block in SKSA\n"
#if DUMP_RAW_BLOCKS
               "\tv [blkno]     - read blkno as a FAT and dump inode tables\n"
#ifndef WIN32
               "\te blkno       - print contents of blkno in hex\n"
               "\tE blkno       - write contents of blkno to a file (block.blkno.pid)\n"
#endif
#endif
                );
        }

#ifndef WIN32
        if (!bbc_only) {
            printf(
                "\n\tNon-LIBBBC commands\n"
                "\tu [devname]   - show/set USB device for BBC interface\n"
                "\ta file [name] - add file [name] to BBCard\n"
                "\tc file [name] - copy file from BBCard to host\n"
                "\td file        - delete file from BBCard\n"
                "\tf             - reload file system\n"
                "\tl             - list BBCard files\n"
                "\tm old new     - rename old to new\n"
                "\tk file        - update secure kernel on BBCard\n"
                "\tK file        - upload secure kernel to host\n"
                "\ts file        - update system app on BBCard\n"
                "\tS file        - upload system app to host\n"
                "\tt file        - update system app license on BBCard\n"
                "\tT file        - upload system app license to host\n"
                "\tx file [host] - checksum file and host file\n"
                "\tO             - open USB device for non-BBC access\n"
                "\to             - power off\n"
                "\tp             - ping BB\n"
                "\tb             - list bad blocks\n"
                "\tz             - reformat/make file system\n");
        }
#else
#if TEST_THREAD
        printf(
           "\tstart         - Start test thread\n"
           "\tstop          - Stop  test thread\n"
            );
#endif
#endif

        printf("\n\t%s control commands\n"
               "\th                 - help\n"
               "\trun file [n stop] - Run commands in file n times\n"
               "\t                    stop specifies if the test should stop upon error\n"
               "\tq                 - quit\n", progname);
    }
    else if (*p) {
        rv = proc_bbc_command(p);
        if (rv == BBC_UNKNOWN && bbc_diag_mode)
            rv = proc_diag_command(p);
        if (rv == BBC_UNKNOWN && !bbc_only)
            rv = proc_nonbbc_command(p);
        if (rv == BBC_UNKNOWN)
            fprintf(stderr, "unknown command '%s'\n", p);
    }

    return rv;
}

int run_file(char* p) {
    FILE* fp;
    char file[256];
    char line[256]; 
    int count = 1;
    int stop = 0;
    int i, rv, bad = 0, badcmd = 0, totalcmd = 0;
    if ((rv = sscanf(p, "run %s %d %d", file, &count, &stop)) < 1) {
        fprintf(stderr, "usage: run file [count] [stop on error]\n");
        return BBC_BADARG;
    }
    if ((fp = fopen(file, "r")) == NULL) {
        perror(file);
        return -1;
    }
    for (i = 1; i <= count; i++) {
        printf("Running %s loop %d of %d, stop = %d...\n",
               file, i, count, stop);
        
        rewind(fp);
        while (fgets(line, sizeof line, fp)) {
            if ((p = strrchr(line, '\n'))) *p = '\0';
            for(p = line; *p && isspace(*p); ++p) ;
            printf(">%s\n", p);
            rv = proc_command(p);
            totalcmd++;
            if (rv < 0) {
                badcmd++;
            }
            if (rv < 0 && stop) {                
                break;
            }
        }
        if (badcmd) {
            bad++;
            if (stop)
                break;
        }
    }
    fclose(fp);
    if (i > count) i = count;
    printf("Test %s %s, %d of %d loops done, %d ok, %d err"
           " (%d/%d cmds failed)\n",
           file, (bad==0)? "PASS": "FAIL", i, count, i-bad, bad, 
           badcmd, totalcmd);
    return count;
}

int
main(int argc, char **argv)
{
    char *p;
#ifdef USE_READLINE
    char *line=NULL, *expansion = NULL; 
    int result;
    char history_file[256];
#else
    char line[256]; 
#endif
    int rv;
    char *logfile = NULL, *runfile = NULL;

#ifndef BBC_IQAHC_DIAG
    sprintf(version, "%s %d.%d (%s %s)", argv[0], 
            VERSION_MAJOR, VERSION_MINOR, __DATE__, __TIME__);
#else
    sprintf(version, "IQue@Home Diagnostics %d.%d (%s %s)", 
            VERSION_MAJOR, VERSION_MINOR, __DATE__, __TIME__);
#endif
    printf("%s\n", version);

#ifdef USE_READLINE
    if (getenv("HOME")) {
        strcpy(history_file, getenv("HOME"));
    } else {
        history_file[0] = '.';
        history_file[1] = 0;
    }
    strcat(history_file, "/.bb_history");
    read_history(history_file);
#endif

    while ((rv = getopt(argc, argv, "dx:l:")) != -1) {
        switch (rv) {
        case 'd':
            diag_mode = 1;
            bbc_only = 1;
            break;
        case 'x':
            runfile = optarg;
            break;
        case 'l':
            logfile = optarg;
            break;
        default:
            printf("Usage: %s [-d] [-x file] [-l file]\n", progname);
            printf("-d      Diagnostics mode (libbbc commands only)\n");
            printf("-x file Runs commands in file\n");
            printf("-l file Writes the log to file\n");
            exit(1);
        }
    }

    BBCSetDiagMode(diag_mode);
    if (logfile != NULL)
        BBCSetLogFile(logfile);
    if (runfile != NULL) {
        char command[256];
        sprintf(command, "run %s", runfile);
        rv = proc_command(command);
        return rv;
    }
    for(;;) {
#ifdef USE_READLINE
        if (line) free(line);
        if ((line = readline("> ")) == NULL) break;
        expansion = NULL;
        result = history_expand(line, &expansion);
        if (expansion) {
            free(line);
            line = expansion;
        }
        if (result < 0 || result == 2) {
            printf("%s\n", line);
            continue;
        }
#else
	printf("> "); fflush(stdout);
	if (!fgets(line, sizeof line, stdin)) {
		break;
	}
#endif
	if ((p = strrchr(line, '\n'))) *p = '\0';
	for(p = line; *p && isspace(*p); ++p) ;
#ifdef USE_READLINE
        if (*p) add_history(p);
#endif
        if (*p == 'q') { /* quit */
            if (bh >= 0) {
                rv = BBCClose(bh);
                printf("BBCClose(%s): ret %d\n", udevname, rv);
            }
            break;
        }
        else {
            rv = proc_command(p);
        }
    }

#ifdef USE_READLINE
    write_history(history_file);
    history_truncate_file(history_file, 100);
#endif

    if (uhCloseGame(ifd) != 0) {
	perror("uhCloseGame");
	exit(1);
    }
    return 0;
}