File: libconcord.cpp

package info (click to toggle)
concordance 0.24-1.1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 7,184 kB
  • sloc: sh: 11,237; cpp: 4,651; ansic: 2,665; python: 600; perl: 253; makefile: 99
file content (1419 lines) | stat: -rw-r--r-- 27,607 bytes parent folder | download | duplicates (2)
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
/*
 * vi: formatoptions+=tc textwidth=80 tabstop=8 shiftwidth=8 noexpandtab:
 *
 * $Id: libconcord.cpp,v 1.42 2010/07/27 19:33:52 jaymzh Exp $
 *
 * 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; either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (C) Copyright Phil Dibowitz 2007
 * (C) Copyright Kevin Timmerman 2007
 */

/*
 * This file is entry points into libconcord.
 *   - phil    Sat Aug 18 22:49:48 PDT 2007
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "libconcord.h"
#include "lc_internal.h"
#include "remote.h"
#include "binaryfile.h"
#include "hid.h"
#include "usblan.h"
#include "web.h"
#include "protocol.h"
#include "time.h"
#include <errno.h>
#include <list>

#define ZWAVE_HID_PID_MIN 0xC112
#define ZWAVE_HID_PID_MAX 0xC115

#define FIRMWARE_MAX_SIZE 64*1024

static class CRemoteBase *rmt;
static struct TRemoteInfo ri;
static struct THIDINFO hid_info;
static struct THarmonyTime rtime;

/*
 * BEGIN ACCESSORS
 */
const char *get_mfg()
{
	return ri.model->mfg;
}

const char *get_model()
{
	return ri.model->model;
}

const char *get_codename()
{
	return (ri.model->code_name) ? ri.model->code_name : (char *)"";
}

int get_skin()
{
	return ri.skin;
}

int get_fw_ver_maj()
{
	return ri.fw_ver_major;
}

int get_fw_ver_min()
{
	return ri.fw_ver_minor;
}

int get_fw_type()
{
	return ri.fw_type;
}

int get_hw_ver_maj()
{
	return ri.hw_ver_major;
}

int get_hw_ver_min()
{
	return ri.hw_ver_minor;
}

int get_flash_size()
{
	return ri.flash->size;
}

int get_flash_mfg()
{
	return ri.flash_mfg;
}

int get_flash_id()
{
	return ri.flash_id;
}

const char *get_flash_part_num()
{
	return ri.flash->part;
}

int get_arch()
{
	return ri.architecture;
}

int get_proto()
{
	return ri.protocol;
}

const char *get_hid_mfg_str()
{
	return hid_info.mfg.c_str();
}

const char *get_hid_prod_str()
{
	return hid_info.prod.c_str();
}

int get_hid_irl()
{
	return hid_info.irl;
}

int get_hid_orl()
{
	return hid_info.orl;
}

int get_hid_frl()
{
	return hid_info.frl;
}

int get_usb_vid()
{
	return hid_info.vid;
}

int get_usb_pid()
{
	return hid_info.pid;
}

int get_usb_bcd()
{
	return hid_info.ver;
}

char *get_serial(int p)
{
	switch (p) {
		case 1:
			return ri.serial1;
			break;
		case 2:
			return ri.serial2;
			break;
		case 3:
			return ri.serial3;
			break;
	}

	return (char *)"";
}

int get_config_bytes_used()
{
	return ri.config_bytes_used;
}

int get_config_bytes_total()
{
	return ri.max_config_size;
}

int get_time_second()
{
	return rtime.second;
}

int get_time_minute()
{
	return rtime.minute;
}

int get_time_hour()
{
	return rtime.hour;
}

int get_time_day()
{
	return rtime.day;
}

int get_time_dow()
{
	return rtime.dow;
}

int get_time_month()
{
	return rtime.month;
}

int get_time_year()
{
	return rtime.year;
}

int get_time_utc_offset()
{
	return rtime.utc_offset;
}

const char *get_time_timezone()
{
	return rtime.timezone.c_str();
}


/*
 * PUBLIC HELPER FUNCTIONS
 */

const char *lc_strerror(int err)
{
	switch (err) {
		case LC_ERROR:
			return "Unknown error";
			break;

		case LC_ERROR_INVALID_DATA_FROM_REMOTE:
			return "Invalid data received from remote";
			break;

		case LC_ERROR_READ:
			return "Error while reading from the remote";
			break;

		case LC_ERROR_WRITE:
			return "Error while writing to the remote";
			break;

		case LC_ERROR_INVALIDATE:
			return 
			"Error while asking the remote to invalidate it's flash";
			break;

		case LC_ERROR_ERASE:
			return "Error while erasing flash";
			break;

		case LC_ERROR_VERIFY:
			return "Error while verifying flash";
			break;

		case LC_ERROR_POST:
			return "Error sending post data to Harmony website";
			break;

		case LC_ERROR_GET_TIME:
			return "Error getting time from remote";
			break;

		case LC_ERROR_SET_TIME:
			return "Error setting time on the remote";
			break;

		case LC_ERROR_CONNECT:
			return "Error connecting or finding the remote";
			break;

		case LC_ERROR_OS:
			return "OS-level error";
			break;

		case LC_ERROR_OS_FILE:
			return "OS-level error related to file operations";
			break;

		case LC_ERROR_OS_NET:
			return "OS-level error related to network operations";
			break;

		case LC_ERROR_UNSUPP:
			return 
			"Model or configuration or operation unsupported";
			break;

		case LC_ERROR_INVALID_CONFIG:
			return 
			"The configuration present on the remote is invalid";
			break;

		case LC_ERROR_IR_OVERFLOW:
			return 
			"Received IR signal is too long - release key earlier";
			break;
	}

	return "Unknown error";
}

void delete_blob(uint8_t *ptr)
{
	delete[] ptr;
}

int identify_file(uint8_t *in, uint32_t size, int *type)
{
	int err;

	/*
	 * Validate this is a remotely sane XML file
	 */
	uint8_t *start_info_ptr;
	err = GetTag("INFORMATION", in, size, start_info_ptr);
	if (err == -1) {
		return LC_ERROR;
	}

	uint8_t *end_info_ptr;
	err = GetTag("/INFORMATION", in, size, end_info_ptr);
	if (err == -1) {
		return LC_ERROR;
	}

	/*
	 * Determine size of binary data following /INFORMATION
	 */
	uint32_t data_len = size - (end_info_ptr - in);
	/*
	 * Account for CRLF after /INFORMATION>
	 * But, don't screw up if it's missing
	 */
	if (data_len >= 2) {
		data_len -= 2;
	}

	/*
	 * Search for tag only in "connectivity test" files
	 */
	bool found_get_zaps_only = false;
	uint8_t *tmp_data = in;
	uint32_t tmp_size = size - data_len;
	while (1) {
		uint8_t *tag_ptr;
		string tag_s;
		err = GetTag("KEY", tmp_data, tmp_size, tag_ptr, &tag_s);
		if (err == -1) {
			break;
		}
		if (!stricmp(tag_s.c_str(), "GETZAPSONLY")) {
			found_get_zaps_only = true;
			break;
		}
		tmp_data = tag_ptr + tag_s.length();
		tmp_size = end_info_ptr - tmp_data;
	}

	/*
	 * Search for tag only in "firmware" files
	 */
	bool found_firmware = false;
	tmp_data = in;
	tmp_size = size - data_len;
	while (1) {
		uint8_t *tag_ptr;
		string tag_s;
		err = GetTag("TYPE", tmp_data, tmp_size, tag_ptr, &tag_s);
		if (err == -1) {
			break;
		}
		if (!stricmp(tag_s.c_str(), "Firmware_Main")) {
			found_firmware = true;
			break;
		}
		tmp_data = tag_ptr + tag_s.length();
		tmp_size = end_info_ptr - tmp_data;
	}

	/*
	 * Search for tag only in "IR learning files.
	 */
	uint8_t *tag_ptr;
	err = GetTag("CHECKKEYS", in, size - data_len, tag_ptr);
	bool found_learn_ir = (err != -1);

	/*
	 * Check tag search results for consistency, and deduce the file type
	 */
	if (found_get_zaps_only && !data_len && !found_firmware &&
		!found_learn_ir) {
		*type = LC_FILE_TYPE_CONNECTIVITY;
		return 0;
	}
	if (!found_get_zaps_only && (data_len >= 16) && !found_firmware &&
		!found_learn_ir) {
		*type = LC_FILE_TYPE_CONFIGURATION;
		return 0;
	}
	if (!found_get_zaps_only && !data_len && found_firmware &&
		!found_learn_ir) {
		*type = LC_FILE_TYPE_FIRMWARE;
		return 0;
	}
	if (!found_get_zaps_only && !data_len && !found_firmware &&
		found_learn_ir) {
		*type = LC_FILE_TYPE_LEARN_IR;
		return 0;
	}

	/*
	 * Findings didn't match a single file type; indicate a problem
	 */
	return LC_ERROR;
}

/*
 * Common routine to read contents of file named *file_name into
 * byte buffer **out. Get size from file and return out[size] 
 * as read from file.
 */
int read_file(char *file_name, uint8_t **out, uint32_t *size)
{
	binaryinfile file;

	if (file_name == NULL) {
		debug("Empty file_name");
		return LC_ERROR_OS_FILE;
	}

	if (file.open(file_name) != 0) {
		debug("Failed to open %s", file_name);
		return LC_ERROR_OS_FILE;
	}

	*size = file.getlength();
	*out = new uint8_t[*size];
	file.read(*out, *size);

	if (file.close() != 0) {
		debug("Failed to close %s\n", file_name);
		return LC_ERROR_OS_FILE;
	}
	return 0;
}


/*
 * PRIVATE HELPER FUNCTIONS
 */

int _is_fw_update_supported(int direct)
{
	/*
	 * If we don't have a fw_base, then we don't support fw updates
	 * in anyway (direct or live).
	 *
	 * If we're in 'live' mode, then we need to make sure we we have a
	 * fw_up_base (we know we have a fw_base from previous portion of if),
	 * to know we're capable of doing it.
	 *
	 * Also, only allow architectures where we've figured out the
	 * structure of the initial magic bytes.
	 */
	if (ri.arch->firmware_base == 0
	    || (!direct && ri.arch->firmware_update_base == 0)
	    || (ri.arch->firmware_4847_offset == 0)) {
		return 0;
	}

	return 1;
}

int _write_fw_to_remote(uint8_t *in, uint32_t size, uint32_t addr,
	lc_callback cb,	void *cb_arg)
{
	int err = 0;

	if ((err = rmt->WriteFlash(addr, size, in,
			ri.protocol, cb, cb_arg))) {
		return LC_ERROR_WRITE;
	}
	return 0;
}

int _read_fw_from_remote(uint8_t *&out, uint32_t size, uint32_t addr,
	lc_callback cb,	void *cb_arg)
{
	out = new uint8_t[size];
	int err = 0;

	if (!cb_arg) {
		cb_arg = (void *)true;
	}

	if ((err = rmt->ReadFlash(addr, size, out,
				ri.protocol, false, cb, cb_arg))) {
		return LC_ERROR_READ;
	}

	return 0;
}

/*
 * Fix the magic bytes of the firmware binaries...
 *
 * The first few bytes of the firmware file we receive from the
 * website will be blanked out (0xFF), and we need to fill them
 * by calculating appropriate content.
 *
 * So why don't we always do this? If the user has a dump from us,
 * it already has the right initial bytes... and if somehow the
 * firmware on the device is messed up, we don't want to ignore
 * that useful data in the file.
 *
 * So we only overwrite the initial bytes if they are missing.
 * For most users, that will be all the time.
 *
 *   - Phil Dibowitz    Tue Mar 11 23:17:53 PDT 2008
 */
int _fix_magic_bytes(uint8_t *in, uint32_t size)
{
	if (size < (ri.arch->firmware_4847_offset + 2)) {
		return LC_ERROR;
	}

	if (in[0] == 0xFF && in[1] == 0xFF) {
		/*
		 * There are "always" two bytes at some location that
		 * contain 0x48 and 0x47.
		 *
		 * Note: For some arch's (10 currently) we haven't
		 * investigated where these go, hence the check for
		 * a valid location in _is_fw_update_supported.
		 *
		 * Note: Arch 2 may be an exception to rule, and needs
		 * more investigation.
		 */
		in[ri.arch->firmware_4847_offset] = 0x48;
		in[ri.arch->firmware_4847_offset + 1] = 0x47;

		/*
		 * The first 2 bytes are a simple 16-bit checksum, computed
		 * beginning at the location of the hard-coded 0x48/0x47
		 * bytes through the end of the firmware.
		 */
		uint8_t suma = 0x21;
		uint8_t sumb = 0x43;
		for (
			uint32_t index = ri.arch->firmware_4847_offset;
			index < FIRMWARE_MAX_SIZE;
			index += 2
		) {
			suma ^= in[index];
			sumb ^= in[index + 1];
		}
		in[0] = suma;
		in[1] = sumb;
	}

	return 0;
}

/*
 * Chunk the hex into words, tack on an '0x', and then throw
 * it through strtoul to get binary data (int) back.
 */
int _convert_to_binary(string hex, uint8_t *&ptr)
{
	size_t size = hex.length();
	for (size_t i = 0; i < size; i += 2) {
		char tmp[6];
		sprintf(tmp, "0x%s ", hex.substr(i, 2).c_str());
		ptr[0] = (uint8_t)strtoul(tmp, NULL, 16);
		ptr++;
	}
	return 0;
}


/*
 * GENERAL REMOTE STUFF
 */
int init_concord()
{
	int err;
	rmt = NULL;

#ifdef WIN32
	// Initialize WinSock
	WSADATA wsainfo;
	int error = WSAStartup(1*256 + 1, &wsainfo);
	if (error) {
		debug("WSAStartup() Error: %i", error);
		return LC_ERROR_OS_NET;
	}
#endif

	if (InitUSB()) {
		return LC_ERROR_OS;
	}

	if ((err = FindRemote(hid_info))) {
		hid_info.pid = 0;

#ifdef WIN32
		if ((err = FindUsbLanRemote())) {
			return LC_ERROR_CONNECT;
		}

		rmt = new CRemoteZ_TCP;
#else
		return LC_ERROR_CONNECT;
#endif
	}

	/*
	 * If hid_info is defined AND pid is 0XC11F, we found something
	 * via HID that's a 1000... that REALLY shouldn't even be possible
	 * but this'll catch that.
	 */
	if (hid_info.pid == 0xC11F) {
		return LC_ERROR_INVALID_DATA_FROM_REMOTE;
	}

	if (!rmt) {
		if (hid_info.pid >= ZWAVE_HID_PID_MIN &&
		    hid_info.pid <= ZWAVE_HID_PID_MAX) {
			// 890, Monstor, etc.
			rmt = new CRemoteZ_HID;
		} else {
			rmt = new CRemote;
		}
	}	

	return 0;
}

int deinit_concord()
{
	ShutdownUSB();
	delete rmt;
	return 0;
}

int get_identity(lc_callback cb, void *cb_arg)
{
	if ((rmt->GetIdentity(ri, hid_info, cb, cb_arg))) {
		return LC_ERROR;
	}

	/* Do some sanity checking */
	if (ri.flash->size == 0) {
		return LC_ERROR_INVALID_CONFIG;
	}

	if (ri.arch == NULL || ri.arch->cookie == 0) {
		return LC_ERROR_INVALID_CONFIG;
	}

	if (!ri.valid_config) {
		return LC_ERROR_INVALID_CONFIG;
	}

	return 0;
}

int reset_remote()
{
	int err = rmt->Reset(COMMAND_RESET_DEVICE);
	return err;
}

int invalidate_flash()
{
	int err = 0;

	if ((err = rmt->InvalidateFlash()))
		return LC_ERROR_INVALIDATE;

	return 0;
}

int post_preconfig(uint8_t *data, uint32_t size)
{
	return Post(data, size, "POSTOPTIONS", ri, true);
}

int post_postfirmware(uint8_t *data, uint32_t size)
{
	return Post(data, size, "COMPLETEPOSTOPTIONS", ri, false);
}

int post_postconfig(uint8_t *data, uint32_t size)
{
	return Post(data, size, "COMPLETEPOSTOPTIONS", ri, true);
}

int post_connect_test_success(uint8_t *data, uint32_t size)
{
	/*
	 * If we arrived, we can talk to the remote - so if it's
	 * just a connectivity test, tell the site we succeeded
	 */

	/*
	 * For some reason, on arch 9, the site sends a file missing
	 * one cookie value, so we need to tell Post() to add it in.
	 * Note that it ONLY does this for the connectivity test...
	 */
	bool add_cookiekeyval = false;
	if (ri.architecture == 9) {
		add_cookiekeyval = true;
	}

	return Post(data, size, "POSTOPTIONS", ri, true, add_cookiekeyval);
}

int get_time()
{
	int err;
	if ((err = rmt->GetTime(ri, rtime)))
		return LC_ERROR_GET_TIME;

	return 0;
}

int set_time()
{
	const time_t t = time(NULL);
	struct tm *lt = localtime(&t);

	rtime.second = lt->tm_sec;
	rtime.minute = lt->tm_min;
	rtime.hour = lt->tm_hour;
	rtime.day = lt->tm_mday;
	rtime.dow = lt->tm_wday;
	rtime.month = lt->tm_mon + 1;
	rtime.year = lt->tm_year + 1900;
	rtime.utc_offset = 0;
	rtime.timezone = "";

	int err = rmt->SetTime(ri, rtime);
	if (err != 0) {
		return err;
	}

	return 0;
}


/*
 * CONFIG-RELATED
 */

int read_config_from_remote(uint8_t **out, uint32_t *size,
	lc_callback cb, void *cb_arg)
{
	int err = 0;

	if (!ri.valid_config) {
		return LC_ERROR_INVALID_CONFIG;
	}

	if (!cb_arg) {
		cb_arg = (void *)true;
	}

	*size = ri.config_bytes_used;
	*out = new uint8_t[*size];

	if ((err = rmt->ReadFlash(ri.arch->config_base, *size,
			*out, ri.protocol, false, cb, cb_arg))) {
		return LC_ERROR_READ;
	}

	return 0;
}

int write_config_to_remote(uint8_t *in, uint32_t size,
	lc_callback cb, void *cb_arg)
{
	int err = 0;

	if (!cb_arg) {
		cb_arg = (void *)true;
	}

	if ((err = rmt->WriteFlash(ri.arch->config_base, size, in,
			ri.protocol, cb, cb_arg))) {
		return LC_ERROR_WRITE;
	}

	return 0;
}

int write_config_to_file(uint8_t *in, uint32_t size, char *file_name,
	int binary)
{
	binaryoutfile of;

	if (of.open(file_name) != 0) {
		debug("Failed to open %s", file_name);
		return LC_ERROR_OS_FILE;
	}

	if (!binary) {
		uint32_t u = size;
		uint8_t chk = 0x69;
		uint8_t *pc = in;
		while (u--)
			chk ^= *pc++;

		/*
		 * Build XML
		 *    FIXME: Abstract this.
		 */
		extern const char *config_header;
		char *ch = new char[strlen(config_header) + 200];
		const int chlen = sprintf(ch,
			config_header, ri.protocol,
			ri.skin ,ri.flash_mfg,
			ri.flash_id, ri.hw_ver_major,
			ri.hw_ver_minor, ri.fw_type,
			ri.protocol, ri.skin,
			ri.flash_mfg, ri.flash_id,
			ri.hw_ver_major, ri.hw_ver_minor,
			ri.fw_type, ri.config_bytes_used, chk);

		of.write(reinterpret_cast<uint8_t*>(ch), chlen);
		free(ch);
	}

	of.write(in, ri.config_bytes_used);

	if (of.close() != 0) {
		debug("Failed to close %s", file_name);
		return LC_ERROR_OS_FILE;
	}

	return 0;
}

int verify_remote_config(uint8_t *in, uint32_t size, lc_callback cb,
	void *cb_arg)
{
	int err = 0;

	if ((err = rmt->ReadFlash(ri.arch->config_base, size, in,
			ri.protocol, true, cb, cb_arg))) {
		return LC_ERROR_VERIFY;
	}

	return 0;
}

int prep_config()
{
	int err = 0;

	if ((err = rmt->PrepConfig(ri))) {
		return LC_ERROR;
	}

	return 0;
}

int finish_config()
{
	int err = 0;

	if ((err = rmt->FinishConfig(ri))) {
		return LC_ERROR;
	}

	return 0;
}

int erase_config(uint32_t size, lc_callback cb, void *cb_arg)
{
	int err = 0;

	if ((err = rmt->EraseFlash(ri.arch->config_base, size, ri, cb,
			cb_arg))) {
		return LC_ERROR_ERASE;
	}

	return 0;
}

int find_config_binary(uint8_t *config, uint32_t config_size,
	uint8_t **binary_ptr, uint32_t *binary_size)
{
	int err;

        err = GetTag("/INFORMATION", config, config_size, *binary_ptr);
	if (err == -1)
		return LC_ERROR;

	*binary_ptr += 2;
	*binary_size = config_size - (*binary_ptr - config);

        // Limit tag searches to XML portion
        config_size -= *binary_size;

	string binary_tag_size_s;
	uint8_t *n = 0;
	err = GetTag("BINARYDATASIZE", config, config_size, n,
		&binary_tag_size_s);
	if (err == -1)
		return LC_ERROR;
        uint32_t binary_tag_size = (uint32_t)atoi(binary_tag_size_s.c_str());

	debug("actual data size %i", *binary_size);
	debug("reported data size %i", binary_tag_size);

	if (*binary_size != binary_tag_size) {
		debug("Config data size mismatch");
		return LC_ERROR;
	}

	string s;
	err = GetTag("CHECKSUM", config, config_size, n, &s);
	if (err != 0)
		return err;
	const uint8_t checksum = atoi(s.c_str());

	// Calculate checksum
	uint32_t u = *binary_size;
	uint8_t calc_checksum = 0x69;
	uint8_t *pc = *binary_ptr;
	while (u--)
		calc_checksum ^= *pc++;

	debug("reported checksum %i %02x", checksum, checksum);
	debug("actual checksum %i %02x", calc_checksum, calc_checksum);

	if (calc_checksum != checksum) {
		debug("Config checksum mismatch");
		return LC_ERROR;
	}

	return 0;
}


/*
 * SAFEMODE FIRMWARE RELATED
 */

int erase_safemode(lc_callback cb, void *cb_arg)
{
	int err = 0;

	if ((err = rmt->EraseFlash(ri.arch->flash_base, FIRMWARE_MAX_SIZE, ri,
			cb, cb_arg))) {
		return LC_ERROR_ERASE;
	}

	return 0;
}

int read_safemode_from_remote(uint8_t **out, uint32_t *size, lc_callback cb,
	void *cb_arg)
{
	*size = FIRMWARE_MAX_SIZE;
	return _read_fw_from_remote(*out, *size, ri.arch->flash_base, cb,
		cb_arg);
}

int write_safemode_to_file(uint8_t *in, uint32_t size, char *file_name)
{
	binaryoutfile of;

	if (of.open(file_name) != 0) {
		return LC_ERROR_OS_FILE;
	}

	of.write(in, size);

	if (of.close() != 0) {
		return LC_ERROR_OS_FILE;
	}

	return 0;
}


/*
 * FIRMWARE RELATED
 */

int is_fw_update_supported(int direct)
{
	/*
	 * Currently firmware upgrades are only available certain remotes.
	 */
	if (_is_fw_update_supported(direct)) {
		return 0;
	} else {
		return LC_ERROR_UNSUPP;
	}
}

int is_config_safe_after_fw()
{
	/*
	 * For some remotes, firmware updates wipes out the config. The
	 * user code needs to be able to determine this so they can tell
	 * the user and/or update the config.
	 */
	if (ri.arch->firmware_update_base == ri.arch->config_base) {
		return LC_ERROR;
	} else {
		return 0;
	}
}

int prep_firmware()
{
	int err = 0;

	if ((err = rmt->PrepFirmware(ri))) {
		return LC_ERROR;
	}

	return 0;
}

int finish_firmware()
{
	int err = 0;

	if ((err = rmt->FinishFirmware(ri))) {
		return LC_ERROR;
	}

	return 0;
}

int erase_firmware(int direct, lc_callback cb, void *cb_arg)
{
	int err = 0;

	if (!_is_fw_update_supported(direct)) {
		return LC_ERROR_UNSUPP;
	}

	uint32_t addr = ri.arch->firmware_update_base;
	if (direct) {
		debug("Writing direct");
		addr = ri.arch->firmware_base;
	}

	if ((err = rmt->EraseFlash(addr, FIRMWARE_MAX_SIZE, ri, cb, cb_arg))) {
		return LC_ERROR_ERASE;
	}

	return 0;
}

int read_firmware_from_remote(uint8_t **out, uint32_t *size, lc_callback cb,
	void *cb_arg)
{
	*size = FIRMWARE_MAX_SIZE;
	return _read_fw_from_remote(*out, *size, ri.arch->firmware_base, cb,
		cb_arg);
}

int write_firmware_to_remote(uint8_t *in, uint32_t size, int direct,
	lc_callback cb,	void *cb_arg)
{
	uint32_t addr = ri.arch->firmware_update_base;
	int err = 0;

	if (!_is_fw_update_supported(direct)) {
		return LC_ERROR_UNSUPP;
	}

	if (size > FIRMWARE_MAX_SIZE) {
		return LC_ERROR;
	}

	if (direct) {
		debug("Writing direct");
		addr = ri.arch->firmware_base;
	}

	if ((err = _fix_magic_bytes(in, size))) {
		return LC_ERROR_READ;
	}

	return _write_fw_to_remote(in, size, addr, cb, cb_arg);
}

int write_firmware_to_file(uint8_t *in, uint32_t size, char *file_name,
	int binary)
{
	binaryoutfile of;
	if (of.open(file_name) != 0) {
		return LC_ERROR_OS_FILE;
	}

	if (binary) {
		of.write(in, size);
	} else {
#ifdef _DEBUG
		/// todo: file header
		uint16_t *pw =
		   reinterpret_cast<uint16_t*>(in);

		/*
		 * Calculate checksum
		 */
		uint16_t wc = 0x4321;
		uint32_t n = 32*1024;
		while (n--)
			wc ^= *pw++;
		debug("Checksum: %04X", wc);
#endif

		uint8_t *pf = in;
		const uint8_t *fwend = in + size;
		do {
			of.write("\t\t\t<DATA>");
			char hex[16];
			uint32_t u = 32;
			if (u > size) {
				u = size;
			}
			while (u--) {
				// convert to hex
				sprintf(hex, "%02X", *pf++);
				of.write(hex);
				size--;
			}
			of.write("</DATA>\n");
		} while (pf < fwend);
	}

	if (of.close() != 0) {
		return LC_ERROR_OS_FILE;
	}

	return 0;
}

int extract_firmware_binary(uint8_t *xml, uint32_t xml_size, uint8_t **out,
	uint32_t *size)
{
	uint32_t o_size = FIRMWARE_MAX_SIZE;
	*out = new uint8_t[o_size];
	uint8_t *o = *out;

	uint8_t *x = xml;
	uint32_t x_size = xml_size;

	string hex;
	while (GetTag("DATA", x, x_size, x, &hex) == 0) {
		uint32_t hex_size = hex.length() / 2;
		if (hex_size > o_size) {
			return LC_ERROR;
		}

		_convert_to_binary(hex, o);

		x_size = xml_size - (x - xml);
		o_size -= hex_size;
	}

	*size = o - *out;

	return 0;
}


/*
 * IR stuff
 */

/*
 * List of key names to be learned is passed in section INPUTPARMS
 * as e.g.:
 * <PARAMETER><KEY>KeyName</KEY><VALUE>PowerToggle</VALUE></PARAMETER>
 * First of these is repeated in section PARAMETERS, so we must
 * concentrate on INPUTPARMS to avoid duplication.
 */

/*
 * locate the INPUTPARMS section in *data:
 */
int _init_key_scan(uint8_t *data, uint32_t size, 
	uint8_t **inputparams_start, uint8_t **inputparams_end)
{
	int err;
		
	/* locating start tag "<INPUTPARMS>" */
	err = GetTag("INPUTPARMS", data, size, *inputparams_start);
	if (err == 0) {
		/* locating end tag "</INPUTPARMS>" */
		err = GetTag("/INPUTPARMS", *inputparams_start, 
			size - (*inputparams_start - data), *inputparams_end);
	}
	return err;
}
	
int _next_key_name(uint8_t **start, uint8_t *inputparams_end, string *keyname)
{
	int err;
	/*
	 * to be really paranoid, we would have to narrow the search range
	 * further down to next <PARAMETER>...</PARAMETER>, but IMHO it
	 * should be safe to assume that Logitech always sends sane files:
	 */
	do {
		err = GetTag("KEY", *start, (inputparams_end - *start),
				*start, keyname);
		if (err != 0) {
			return err;
		}
	} while (*keyname != "KeyName");

	err = GetTag("VALUE", *start, (inputparams_end - *start),
			*start, keyname);

	if (err == 0) {
		/* found next key name : */
		debug("Key Name: %s\n", (*keyname).c_str());
	}
	return err;
}


int get_key_names(uint8_t *data, uint32_t size,
	char ***key_names, uint32_t *key_names_length)
{
	using namespace std;
	uint8_t *cursor = data;
	uint8_t *inputparams_end;
	uint32_t key_index = 0;
	list<string> key_list;
	string key_name;
	
	if ((data == NULL) || (size == 0) || (key_names == NULL)
		     	|| (key_names_length == NULL)) {
		return LC_ERROR;
	}
	/* setup data scanning, locating start and end of keynames section: */
	if (_init_key_scan(data, size, &cursor, &inputparams_end) != 0) {
		return LC_ERROR;
	}
	
	/* scan for key names and append found names to list: */
	while (_next_key_name(&cursor, inputparams_end, &key_name) == 0) {
		key_list.push_back(key_name);
	}
	
	if (key_list.size() == 0) {
		return LC_ERROR;
	}
	
	*key_names_length = key_list.size();
	*key_names = new char*[*key_names_length];
			
	/* copy list of found names to allocated buffer: */
	for (
		list<string>::const_iterator cursor = key_list.begin();
		cursor != key_list.end();
		++cursor
	) {
		(*key_names)[key_index++] = strdup((*cursor).c_str());
	}
	/* C++ should take care of key_name and key_list deallocation */
	return 0;
}

/*
 * Free memory allocated by get_key_names:
 */
void delete_key_names(char **key_names, uint32_t key_names_length)
{
	uint32_t key_count = 0;
	if (key_names != NULL) {
		for (key_count = 0; key_count < key_names_length; key_count++) {
			free(key_names[key_count]);
			/* allocated by strdup -> free() */
		}
		delete[](key_names); /* allocated by new[] -> delete[] */
	}
}

/*
 * Fill ir_data with IR code learned from other remote
 * via Harmony IR receiver.
 * Returns 0 for success, error code for failure.
 */
int learn_from_remote(uint32_t *carrier_clock,
	uint32_t **ir_signal, uint32_t *ir_signal_length,
	lc_callback cb, void *cb_arg)
{
	if (rmt == NULL){
		return LC_ERROR_CONNECT;
	}
	if ((carrier_clock == NULL) || (ir_signal == NULL)
			|| (ir_signal_length == NULL)){
		/* nothing to write to: */
		return LC_ERROR;
	}
	
	/* try to learn code via Harmony from original remote: */
	return rmt->LearnIR(carrier_clock, ir_signal, ir_signal_length, cb,
		cb_arg);
}

/*
 * Free memory allocated by learn_from_remote:
 */
void delete_ir_signal(uint32_t *ir_signal)
{
	delete[] ir_signal;  /* allocated by new[] -> delete[] */
}

/*
 * Fill encoded_signal with IR code encoded to Logitech
 * posting string format.
 * Returns 0 for success, error code in case of failure.
 */
int encode_for_posting(uint32_t carrier_clock,
	uint32_t *ir_signal, uint32_t ir_signal_length,
	char **encoded_signal)
{
	int err = 0;
	string encoded;
	if ((ir_signal == NULL) || (ir_signal_length == 0)
			|| (encoded_signal == NULL)) {
		return LC_ERROR;	/* cannot do anything without */
	}
	err = encode_ir_signal(carrier_clock, 
			ir_signal, ir_signal_length, &encoded);
	if (err == 0) {
		debug("Learned code: %s",encoded.c_str());
		*encoded_signal = strdup(encoded.c_str());
	}
	return err;
}

/*
 * Free memory allocated by encode_for_posting:
 */
void delete_encoded_signal(char *encoded_signal)
{
	free(encoded_signal); /* allocated by strdup -> free() */
}

/*
 * Post encoded IR-code with key_name and additional 
 * information from XML data[size] to Logitech.
 * Returns 0 for success, error code for failure.
 */
int post_new_code(uint8_t *data, uint32_t size, 
	char *key_name, char *encoded_signal)
{
	string learn_key;
	string learn_seq;

	if ((key_name == NULL) || (encoded_signal == NULL)
			|| (data == NULL) || (size == 0)) {
		return LC_ERROR_POST;	/* cannot do anything without */
	}

	learn_key = key_name;
	learn_seq = encoded_signal;

	return Post(data, size, "POSTOPTIONS", ri, true, false,
			&learn_seq, &learn_key);
}

/*
 * PRIVATE-SHARED INTERNAL FUNCTIONS
 * These are functions used by the whole library but are NOT part of the API
 * and probably should be somewhere else...
 */

void report_net_error(const char *msg)
{
	int err;
#ifdef WIN32
	err = WSAGetLastError();
	debug("Net error: %s failed with error %i", msg, err);
#else
	debug("Net error: %s failed with error %s", msg, strerror(errno));
#endif
}