summaryrefslogtreecommitdiff
path: root/lthor.c
blob: e9419f04b46f7f86fcd472cb676196f4549a52da (plain)
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
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/mman.h>
#include <poll.h>
#include <errno.h>
#include <dirent.h>
#include <libgen.h>

#include <archive.h>
#include <archive_entry.h>

#include "thor-proto.h"

#define USB_VENDOR_SAMSUNG "04e8"
#define USB_DEVICE_Z100 "6601"
#define USB_DEVICE_Z100_DEVGURU "6860"
#define USB_DEVICE_DEVGURU "685d"
#define USB_DEVICE_OLD_DOWNLOADER "1204"

#define KB			(1024)
#define MB			(1024*KB)
#define DEFAULT_PKT_SIZE	(1*MB)
#define DEFAULT_TIMEOUT	(60000)			/* 1 minute */
#define DEFAULT_PORT		"/dev/ttyACM0"

/* data abstraction */
struct data_src {
	size_t (*get_data_length)(struct data_src *src);
	size_t (*get_data_block)(struct data_src *src, void *data, size_t len);
	const char* (*get_data_name)(struct data_src *src);
};

int opt_verbose = 0;
int opt_test = 0;
size_t trans_unit_size = DEFAULT_PKT_SIZE;

static void dump(const char *msg, void *bytes, int len)
{
	int i;

	if (!opt_verbose)
		return;

	fprintf(stderr, "%s :", msg);
	for (i=0; i<len; i++) {
		if (i && (0==i%16))
			fprintf(stderr, "      ");
		fprintf(stderr, "%02x%c", ((unsigned char*)bytes)[i],
				((len == i+1) || (i+1)%16==0) ? '\n': ' ');
	}
}

static off_t file_size(const char *filename)
{
	struct stat st;
	if (stat(filename, &st) < 0)
		return -1;

	return st.st_size;
}

int serial_read(int fd, void *addr, size_t len, int timeout)
{
	unsigned char *p = addr;
	int n = 0, r;

	while (n < len) {
		struct pollfd fds;
		fds.fd = fd;
		fds.events = POLLIN;
		fds.revents = 0;
		r = poll(&fds, 1, timeout);
		if (r < 0) {
			fprintf(stderr, "line %d: poll failed\n", __LINE__);
			return -1;
		}

		if (r == 0) {
			if (opt_verbose)
				fprintf(stderr, "line %d: timeout after reading %d bytes\n", __LINE__, n);
			return n;
		}

		if (!(fds.revents & POLLIN)) {
			fprintf(stderr, "line %d: poll returned non-read event %08x\n", __LINE__, fds.revents);
			continue;
		}

		r = read(fd, &p[n], len - n);
		if (r < 0) {
			fprintf(stderr, "line %d: read failed\n", __LINE__);
			return -1;
		}

		n += r;
	}

	return n;
}

static double timediff (struct timeval *atv, struct timeval *btv)
{
	double diff;

	if (btv->tv_usec < atv->tv_usec) {
		diff = btv->tv_sec - atv->tv_sec - 1;
		diff += (double)(1*1000*1000 - atv->tv_usec +
				btv->tv_usec)/(1000*1000);
	} else {
		diff = btv->tv_sec - atv->tv_sec;
		diff += (double)(btv->tv_usec - atv->tv_usec)/(1000*1000);
	}

	return diff;
}

int send_chunks(int fd, struct data_src *senddata, size_t size)
{
	unsigned char *chunk;
	struct data_res_pkt resp;
	size_t n = 0;
	int chunksize, chunk_number = 1;
	struct timeval stv, etv, ltv;
	int r;

	chunk = malloc(trans_unit_size);
	if (chunk == NULL) {
		fprintf(stderr, "Unable to allocate memory.\n");
		return -1;
	}

	if (opt_verbose)
		fprintf(stderr, "Downloading: %zd bytes\n", size);

	gettimeofday(&stv, NULL);
	memcpy(&ltv, &stv, sizeof(struct timeval));

	while (n < size) {
		if (size - n >= trans_unit_size)
			chunksize = trans_unit_size;
		else
			chunksize = size - n;

		chunksize = senddata->get_data_block(senddata, chunk, chunksize);
		if (chunksize <= 0) {
			fprintf(stderr, "\nline %d: Broken tar archive - check download!\n", __LINE__);
			exit(1);
		}

		if (opt_verbose)
			fprintf(stderr, "read %d bytes\n", chunksize);

		assert(chunksize > 0 && chunksize <= trans_unit_size);
		memset(&chunk[chunksize], 0, trans_unit_size - chunksize);

		if (opt_verbose)
			fprintf(stderr, "sending %zd/%zd\n", n + chunksize, size);

		r = write(fd, chunk, trans_unit_size);
		if (r != trans_unit_size) {
			fprintf(stderr, "line %d: failed to send data\n", __LINE__);
			free(chunk);
			return -1;
		}

		memset(&resp, 0, DATA_RES_PKT_SIZE);
		r = serial_read(fd, &resp, DATA_RES_PKT_SIZE, DEFAULT_TIMEOUT);
		if (r != DATA_RES_PKT_SIZE) {
			fprintf(stderr, "line %d: read failed %d\n", __LINE__, r);
			free(chunk);
			return -1;
		}

		if (resp.cnt != chunk_number) {
			printf("\nsending %zd/%zd : sequence wrong %08x, expected %08x\n",
				n, size, resp.cnt, chunk_number);
			//return -1;
		}

		n += chunksize;

		if (opt_verbose) {
			printf("response %08x %08x\n", resp.ack, resp.cnt);

		} else {
			int now = n/KB;
			int total = size/KB;
			char progress [4] = { '-', '\\', '|', '/' };
			char c = progress[(now/30)%4];
			double elaps;

			gettimeofday(&etv, NULL);
			if (n >= size) {
				elaps = timediff(&stv, &etv);
				fprintf(stderr, "\x1b[1A\x1b[16C%c sending %6dk/%6dk %3d%% block %-6d", 
						c, now, total, ((now*100)/total), chunk_number);
				fprintf(stderr, " [avg %.2f MB/s]\n", (double)(size/elaps)/(MB));
			} else {
				elaps = timediff(&ltv, &etv);
				memcpy(&ltv, &etv, sizeof(struct timeval));
				fprintf(stderr, "\x1b[1A\x1b[16C%c sending %6dk/%6dk %3d%% block %-6d", 
						c, now, total, ((now*100)/total), chunk_number);
				fprintf(stderr, " [%.2f MB/s]\n", (double)(chunksize/elaps)/(MB));
			}
		}
		chunk_number++;
	}

	free(chunk);

	return 0;
}

/*
 * function that doesn't wait for response data, used by standard requests and
 * REQ_PIT_DATA_START, which doesn't want a response
 */
int write_request(int fd, request_type req_id, int req_sub_id,
	int *idata, int icnt, char **sdata, int scnt)
{
	struct rqt_pkt req;
	int r, i;

	assert(icnt <= sizeof(req.int_data)/sizeof(req.int_data[0]));
	assert(icnt >= 0);
	assert(scnt <= sizeof(req.str_data)/sizeof(req.str_data[0]));
	assert(scnt >= 0);

	memset(&req, 0, sizeof(req));

	req.id = req_id;
	req.sub_id = req_sub_id;

	if (idata) {
		for (i=0; i<icnt; i++)
			req.int_data[i] = idata[i];
	}

	if (sdata) {
		for (i=0; i<scnt; i++)
			strcpy(req.str_data[i],sdata[i]);
	}

	dump("send", &req, 0x20);

	r = write(fd, &req, RQT_PKT_SIZE);
	if (r != RQT_PKT_SIZE) {
		fprintf(stderr, "line %d: failed to send data r = %d\n",
				__LINE__, r);
		return -1;
	}

	return 0;
}

int send_request_timeout(int fd, request_type req_id, int req_sub_id,
	int *idata, int icnt, char **sdata, int scnt, struct res_pkt *pres, int timeout)
{
	struct res_pkt resp;
	int r;

	r = write_request(fd, req_id, req_sub_id, idata, icnt, sdata, scnt);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to write request r = %d\n",
				__LINE__, r);
		return -1;
	}

	r = serial_read(fd, &resp, sizeof resp, timeout);
	if (r >= 0)
		dump("recv", &resp, sizeof resp);
	if (r != sizeof resp) {
		fprintf(stderr, "line %d: failed to receive data r = %d\n",
				__LINE__, r);
		return -1;
	}

	if (pres)
		memcpy(pres, &resp, RES_PKT_SIZE);

	if (resp.ack != 0) {
		fprintf(stderr, "line %d: ack reports fail. ack = %d\n",
				__LINE__, resp.ack);
		return -1;
	}

	return resp.ack;
}

int send_request(int fd, request_type req_id, int req_sub_id, int *idata, int icnt)
{
	return send_request_timeout(fd, req_id, req_sub_id, idata, icnt,
		NULL, 0, NULL, DEFAULT_TIMEOUT);
}

int request_reboot(int fd)
{
	int r;
	r = send_request(fd, RQT_CMD, RQT_CMD_REBOOT, NULL, 0);
	if (r)
		fprintf(stderr, "RQT_CMD_REBOOT,   status = %08x\n", r);
	return r;
}

int thor_handshake(int fd)
{
	char buffer[4];
	int r;

	r = write(fd, "THOR", 4);
	if (r != 4) {
		fprintf(stderr, "line %d: failed to write signature bytes\n",
				__LINE__);
		return -1;
	}

	r = serial_read(fd, buffer, 4, DEFAULT_TIMEOUT);
	if (r != 4) {
		fprintf(stderr, "line %d: failed to read signature bytes\n",
				__LINE__);
		return -1;
	}

	if (memcmp(buffer, "ROHT", 4)) {
		fprintf(stderr, "line %d: signature byte mismatch\n", __LINE__);
		return -1;
	}

	return 0;
}

int getfile(const char *devpath, char *buffer, size_t bufsize)
{
	int fd, r = 0;

	fd = open(devpath, O_RDONLY);
	if (fd >= 0) {
		r = read(fd, buffer, bufsize - 1);
		if (r < 0)
			r = 0;
		close(fd);
	}
	else if (opt_verbose)
		fprintf(stderr, "failed to open %s\n", devpath);
	if (r && buffer[r - 1] == '\n')
		r--;
	buffer[r] = 0;
	return r;
}

/*
 * Given USB path, return tty name
 * FIXME: probably should look up the /dev from device major:minor
 * There seems to be two styles of device name:
 *  1. /sys/bus/usb/devices/1-2/1-2\:2.0/tty/ttyACM0/dev
 *  2. /sys/bus/usb/devices/1-2/1-2\:2.0/tty:ttyACM0
 */
char *device_from_usb_tty_directory(const char *usbpath)
{
	static char ttypath[0x400];
	static char devpath[0x400];
	char *ret = NULL;
	DIR *d;

	strcpy(ttypath, usbpath);
	strcat(ttypath, "/tty");

	d = opendir(ttypath);
	if (d) {
		if (opt_verbose)
			fprintf(stderr, "listing %s:\n", ttypath);

		/* device name is under tty directory */
		while (!ret) {
			struct dirent *de;

			de = readdir(d);
			if (!de)
				break;

			if (opt_verbose)
				fprintf(stderr, "%s\n", de->d_name);

			if (de->d_name[0] == '.')
				continue;

			strcpy(devpath, "/dev/");
			strcat(devpath, de->d_name);

			ret = devpath;
		}
	} else	{
		/* device name is in directory */
		d = opendir(usbpath);
		if (!d)
			return NULL;

		if (opt_verbose)
			fprintf(stderr, "listing %s:\n", usbpath);

		while (!ret) {
			struct dirent *de;

			de = readdir(d);
			if (!de)
				break;

			if (opt_verbose)
				fprintf(stderr, "%s\n", de->d_name);

			if (strncmp(de->d_name, "tty:", 4))
				continue;

			strcpy(devpath, "/dev/");
			strcat(devpath, &de->d_name[4]);

			ret = devpath;
		}
	}

	closedir(d);

	if (ret) {
		fprintf(stderr, "USB port is detected : %s\n\n", ret);
	} else {
		fprintf(stderr, "USB port is "
			"\x1b[0;31;1mnot\x1b[0m detected !\n\n", ret);
	}

	return ret;
}

const char* find_usb_device(void)
{
	DIR *d;
	char *p;
	char buffer[11];
	const char *dirname = "/sys/bus/usb/devices";
	char usbpath[0x400];
	char usbdir[0x100];
	char *tty = NULL;

	d = opendir(dirname);
	if (!d)
		return NULL;

	while (1) {
		struct dirent *de;

		de = readdir(d);
		if (!de)
			break;

		if (de->d_name[0] == '.')
			continue;

		strcpy(usbdir, de->d_name);
		strcpy(usbpath, dirname);
		strcat(usbpath, "/");
		strcat(usbpath, usbdir);
		strcat(usbpath, "/");
		p = &usbpath[strlen(usbpath)];

		/* match the vendor ID */
		strcat(p, "idVendor");
		getfile(usbpath, buffer, sizeof buffer);
		if (opt_verbose)
			fprintf(stderr, "vendorId = >%s< %zd\n", buffer,
					strlen(buffer));
		if (strcmp(buffer, USB_VENDOR_SAMSUNG))
			continue;

		/* match the product ID */
		strcpy(p, "idProduct");
		getfile(usbpath, buffer, sizeof buffer);
		if (opt_verbose)
			fprintf(stderr, "product = >%s< %zd\n", buffer,
					strlen(buffer));

		if (!strcmp(buffer, USB_DEVICE_OLD_DOWNLOADER))
			fprintf(stderr, "Old bootloader detected!\n");

		/* supported product ID */
		if (strcmp(buffer, USB_DEVICE_Z100) &&
			strcmp(buffer, USB_DEVICE_Z100_DEVGURU) &&
			strcmp(buffer, USB_DEVICE_DEVGURU))
			continue;

		if (opt_verbose)
			fprintf(stderr, "found %s:%s!\n", USB_VENDOR_SAMSUNG,
					buffer);
		closedir(d);

		p[0] = 0x00;
		d = opendir(usbpath);
		if (opt_verbose)
			fprintf(stderr, "at %s\n", usbpath);
		while ((de = readdir(d))) {
			if (strlen(de->d_name) < strlen(usbdir))
				continue;
			if (de->d_type != DT_DIR)
				continue;
			if (strncmp(de->d_name, usbdir, strlen(usbdir)))
				continue;

			strcpy(p, de->d_name);
			if (opt_verbose)
				fprintf(stderr, "search for tty on %s\n", usbpath);
			tty = device_from_usb_tty_directory(usbpath);
			if (tty)
				break;
		}

		closedir(d);
		if ((opt_verbose) && (!tty))
			fprintf(stderr, "idVendor and idProduct are matched"
				"but no tty description\n");

		return tty;
	}

	closedir(d);

	if (opt_verbose)
		fprintf(stderr, "No USB device found with matching "
			"idVendor and idProduct\n" );

	return NULL;
}


int open_port(const char *portname, int wait)
{
	int once = 0;
	int fd;
	int r;
	struct termios tios;
	const char *dev;

	if (opt_test)
		return open("/dev/null", O_RDWR);

	while (1) {
		if (!portname)
			dev = find_usb_device();
		else
			dev = portname;

		if (!wait && dev == NULL) {
			fprintf(stderr, "line %d: device not found\n", __LINE__);
			return -1;
		}

		if (dev) {
			fd = open(dev, O_RDWR);
			if (fd == -1) {
				perror("port open error!!\n");
				return -1;
			}
			break;
		}

		if (!once) {
			if (!wait)
			    return -1;
			printf("\nUSB port is not detected yet... \n");
			printf("Make sure phone(device) should be in a download mode \n");
			printf("before connecting phone to PC with USB cable.\n");
			printf("(How to enter download mode : press <volume-down> + <power> key)\n\n");
			once = 1;
		}
		sleep(1);
	}

	r = tcgetattr(fd, &tios);
	if (r < 0) {
		fprintf(stderr, "line %d: tcgetattr failed\n", __LINE__);
		close(fd);
		return -1;
	}

	/*
	 * Firmware BUG alert!!!
	 * Flow control (RTS/CTS) should be disabled, because
	 * the firmware doesn't deal with it properly.
	 */
        cfmakeraw(&tios);
	r = tcsetattr(fd, TCSANOW, &tios);
	if (r < 0) {
		fprintf(stderr, "line %d: tcsetattr failed\n", __LINE__);
		close(fd);
		return -1;
	}

	r = tcflush(fd, TCIOFLUSH);
	if (r < 0) {
		fprintf(stderr, "line %d: tcflush failed\n", __LINE__);
		close(fd);
		return -1;
	}

	r = thor_handshake(fd);
	if (r < 0) {
		fprintf(stderr, "line %d: handshake failed\n", __LINE__);
		close(fd);
		return -1;
	}

	return fd;
}

int wait_and_open_port(const char *portname)
{
	return open_port(portname, 1);
}

/*
 * Write a data source (file) into a partition
 *
 * data_src abstraction provided so sending a single file
 * from a non-tar source is possible one day
 */
int download_single_file(int fd, struct data_src *senddata, int filetype)
{
	int r;
	size_t filesize;
	const char *filename;
	struct res_pkt resp;
	int32_t	int_data[2];

	filesize = senddata->get_data_length(senddata);
	filename = senddata->get_data_name(senddata);

	int_data[0] = filetype;
	int_data[1] = filesize;
	r = send_request_timeout(fd, RQT_DL, RQT_DL_FILE_INFO, int_data, 2,
		(char **)&filename, 1, &resp, DEFAULT_TIMEOUT);
	if (r < 0) {
		fprintf(stderr, "RQT_DL_FILE_INFO, status = %08x\n", r);
		return -1;
	}
	trans_unit_size = resp.int_data[0];

	r = send_request(fd, RQT_DL, RQT_DL_FILE_START, NULL, 0);
	if (r < 0) {
		fprintf(stderr, "RQT_DL_FILE_START, status = %08x\n", r);
		return -1;
	}

	r = send_chunks(fd, senddata, filesize);
	if (r < 0) {
		fprintf(stderr, "send_chunks(), status = %08x\n", r);
		return -1;
	}

	r = send_request(fd, RQT_DL, RQT_DL_FILE_END, NULL, 0);
	if (r < 0) {
		fprintf(stderr, "RQT_DL_FILE_END, status = %08x\n", r);
		return -1;
	}

	return 0;
}

struct file_data_src {
	struct data_src src;
	int fd;
	const char* filename;
	size_t filesize;
};

size_t file_get_data_length(struct data_src *src)
{
	struct file_data_src *filedata = (struct file_data_src *) src;

	return filedata->filesize;
}

size_t file_get_data_block(struct data_src *src, void *data, size_t len)
{
	struct file_data_src *filedata = (struct file_data_src *) src;

	return read(filedata->fd, data, len);
}

const char *file_get_data_name(struct data_src *src)
{
	struct file_data_src *filedata = (struct file_data_src *) src;

	return filedata->filename;
}

int filedata_open(struct file_data_src *filedata, const char *filename)
{
	int r;
	char *basefile;

	if (!filedata)
		return -1;

	memset((void*)filedata, 0x00, sizeof(struct file_data_src));

	r = open(filename, O_RDONLY);
	if (r < 0)
		return r;

	filedata->fd = r;

	/* According to the man page basename() might modify the argument or
	 * return a pointer to statically allocated memory. Thus two strdup()s */
	basefile = strdup(filename);
	filedata->filename = strdup(basename(basefile));
	free(basefile);

	filedata->filesize = lseek(filedata->fd, 0, SEEK_END);
	lseek(filedata->fd, 0, SEEK_SET);

	filedata->src.get_data_length = &file_get_data_length;
	filedata->src.get_data_block = &file_get_data_block;
	filedata->src.get_data_name = &file_get_data_name;

	return r;
}

int filedata_close(struct file_data_src *filedata)
{
	close(filedata->fd);
	free((void *)filedata->filename);
	return 0;
}

struct tar_data_src {
	struct data_src src;
	struct archive *ar;
	struct archive_entry *ae;
};

size_t te_get_data_length(struct data_src *src)
{
	struct tar_data_src *tardata = (struct tar_data_src *) src;

	return archive_entry_size(tardata->ae);
}

size_t te_get_data_block(struct data_src *src, void *data, size_t len)
{
	struct tar_data_src *tardata = (struct tar_data_src *) src;

	return archive_read_data(tardata->ar, data, len);
}

const char *te_get_data_name(struct data_src *src)
{
	struct tar_data_src *tardata = (struct tar_data_src *) src;

	return archive_entry_pathname(tardata->ae);
}

int tardata_open(struct tar_data_src *tardata, const char *tarfile)
{
	int r;

	/* open the tar archive */
	tardata->ar = archive_read_new();

	archive_read_support_format_tar(tardata->ar);
	archive_read_support_compression_gzip(tardata->ar);
	archive_read_support_compression_bzip2(tardata->ar);

	if (!strcmp(tarfile, "-"))
		r = archive_read_open_FILE(tardata->ar, stdin);
	else
		r = archive_read_open_filename(tardata->ar, tarfile, 512);

	if (r) {
		fprintf(stderr, "line %d: failed to open %s\n", __LINE__, tarfile);
		return r;
	}

	tardata->src.get_data_length = &te_get_data_length;
	tardata->src.get_data_block = &te_get_data_block;
	tardata->src.get_data_name = &te_get_data_name;
	tardata->ae = NULL;

	return r;
}

const char *tardata_next(struct tar_data_src *tardata)
{
	int64_t partsize;
	int r;

	r = archive_read_next_header(tardata->ar, &tardata->ae);
	if (r == ARCHIVE_EOF)
		return NULL;

	if (r != ARCHIVE_OK) {
		fprintf(stderr, "line %d: archive_read_next_header error %d\n",
				__LINE__, r);
		return NULL;
	}

	partsize = archive_entry_size(tardata->ae);
	if (partsize > SIZE_MAX) {
		/*
		 * FIXME: fix source (and maybe firmware) to deal with files
		 * bigger than 4G
		 */
		fprintf(stderr, "line %d: Large file %llx (>4GB) is not"
				" supported\n", __LINE__, (unsigned long long)
				partsize);
		return NULL;
	}

	return archive_entry_pathname(tardata->ae);
}

int tardata_close(struct tar_data_src *tardata)
{
	archive_read_close(tardata->ar);
	archive_read_finish(tardata->ar);
	return 0;
}

int get_entry_size_in_tar(const char *tarfile, unsigned long long *total)
{
	struct tar_data_src tardata;
	const char *filename;
	int r;

	r = tardata_open(&tardata, tarfile);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to open %s\n", __LINE__,
				tarfile);
		return r;
	}

	*total = 0;

	while (1) {
		size_t size = 0;

		filename = tardata_next(&tardata);
		if (!filename)
			break;

		size = tardata.src.get_data_length(&tardata.src);
		printf("[\x1b[0;32;1m%s\x1b[0m]\t%zuk\n", filename, size/KB);

		*total += size;
	}

	tardata_close(&tardata);

	return 0;
}

int download_pitfile(int fd, const char *pitfile)
{
	struct file_data_src filedata;
	int r;

	r = filedata_open(&filedata, pitfile);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to open %s\n", __LINE__, pitfile);
		return r;
	}


	printf("[\x1b[0;32;1m%s\x1b[0m]\n", pitfile);
	r = download_single_file(fd, &filedata.src, BINARY_TYPE_PIT);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to download %s\n", __LINE__,
				pitfile);
		return r;
	}

	fprintf(stderr, "\n%s completed\n", pitfile);

	filedata_close(&filedata);

	return r;
}

int download_single_tarfile(int fd, const char *tarfile)
{
	struct tar_data_src tardata;
	const char *filename;
	int r;

	r = tardata_open(&tardata, tarfile);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to open %s\n", __LINE__, tarfile);
		return r;
	}

	while (1) {
		filename = tardata_next(&tardata);
		if (!filename)
			break;

		printf("[\x1b[0;32;1m%s\x1b[0m]\n", filename);
		r = download_single_file(fd, &tardata.src, BINARY_TYPE_NORMAL);
		if (r < 0) {
			fprintf(stderr, "line %d: failed to download %s\n",
					__LINE__, filename);
			break;
		}
	}

	fprintf(stderr, "\n%s completed\n", tarfile);

	tardata_close(&tardata);

	return r;
}

int process_download(const char *portname, const char *pitfile, char **tarfilelist)
{
	int r;
	char **tfl;
	off_t pit_length = 0;
	int fd;
	unsigned long long total;

	/* now connect to the target */
	fd = wait_and_open_port(portname);
	if (fd < 0) {
		fprintf(stderr, "line %d: failed to open port %s\n", __LINE__,
				portname);
		return -1;
	}

	total = 0;
	tfl = tarfilelist;
	while (tfl && *tfl) {
		unsigned long long len = 0;
		printf("\x1b[0;33;1m%s :\x1b[0m\n", *tfl);
		if (get_entry_size_in_tar(*tfl, &len) < 0) {
			perror("Error");
			close(fd);
			return -1;
		}
		total += len;
		tfl++;
	}

	if (pitfile) {
		pit_length = file_size(pitfile);
		if (pit_length < 0) {
			fprintf(stderr, "line %d: failed to get pit length\n"
				, __LINE__);
			close(fd);
			return -1;
		}
		total += pit_length;
		printf("\x1b[0;33;1m%s : \x1b[0m%zuk\n", pitfile,
			(size_t)pit_length/KB);
	}
	printf("-------------------------\n");
	printf("\t\x1b[0;33;1mtotal\x1b[0m :\t%.2fMB\n\n", (double)total/MB);

	/* for updating progress bar in the target */
	r = send_request(fd, RQT_DL, RQT_DL_INIT, (int*)&total, 1);
	/*
	 * FIXME : if total > SIZE_MAX then DL_INIT must change it's protocol to
	 * send/receive 64bit size data.
	 */
	if (r) {
		fprintf(stderr, "RQT_DL_INIT, status = %08x\n", r);
		close(fd);
		return -1;
	}

	if (pitfile) {
		fprintf(stderr, "\nDownload PIT file : %s\n\n", pitfile);
		r = download_pitfile(fd, pitfile);
		if (r < 0) {
			fprintf(stderr, "failed to download %s\n", pitfile);
			close(fd);
			return r;
		}
	}

	while (tarfilelist && *tarfilelist) {
		fprintf(stderr, "\nDownload files from %s\n\n", *tarfilelist);
		r = download_single_tarfile(fd, *tarfilelist);
		if (r < 0) {
			fprintf(stderr, "failed to download %s\n", *tarfilelist);
			close(fd);
			return r;
		}
		tarfilelist++;
	}

	r = send_request(fd, RQT_DL, RQT_DL_EXIT, NULL, 0);
	if (r) {
		fprintf(stderr, "\x1b[0;33;1mmissing RQT_DL_EXIT response "
			"from broken bootloader\x1b[0m\n");
	}

	fprintf(stderr, "\nrequest target reboot : ");

	r = request_reboot(fd);
	if (r)
		fprintf(stderr, "\x1b[0;31;1mfailed\x1b[0m\n");
	else
		fprintf(stderr, "\x1b[0;32;1msuccess\x1b[0m\n");

	close(fd);

	return 0;
}

/* Check if LHOR protocol is in working state */
int check_proto(const char *portname)
{
	int fd;
	/* int r;
        struct res_pkt resp;*/

	/* connect to the target */
	fd = open_port(portname, 0);
        if (fd < 0)
		return -1;

	/* Below I commented out my attempt to check if LHOR protocol is enabled
	 * by quering protocol version.
	 * The main problem is that I didn't find a way to 'close' the session,
	 * to put protocol into previous state.
	 * */

	/*
	r = thor_handshake(fd);
	if (r < 0) {
		fprintf(stderr, "line %d: handshake failed\n", __LINE__);
		return -1;
        }

	r = send_request_timeout(fd, RQT_INFO, RQT_INFO_VER_PROTOCOL, NULL, 0, NULL, 0, &resp, DEFAULT_TIMEOUT);
        if (r) {
		fprintf(stderr, "RQT_INFO_VER_PROTOCOL, status = %08x\n", r);
		return -1;
	} */

	/* Here should be some code, which closes protocol session, resets it somehow */
	
	close(fd);

	return 0;
}

int test_tar_entry(struct data_src *tardata)
{
	static unsigned char *chunk;
	size_t n = 0, size;
	int chunksize;

	chunk = (unsigned char*)malloc(trans_unit_size);
	if (chunk == NULL) {
		fprintf(stderr, "Unable to allocate memory.\n");
		return -1;
	}

	size = tardata->get_data_length(tardata);
	while (n < size) {
		if (size - n >= trans_unit_size)
			chunksize = trans_unit_size;
		else
			chunksize = size - n;

		chunksize = tardata->get_data_block(tardata, chunk, chunksize);
		if (chunksize <= 0) {
			free(chunk);
			return -1;
		}

		if ((!chunksize > 0 && chunksize <= trans_unit_size)) {
			free(chunk);
			return -1;
		}

		if ((n/chunksize)%4 == 0)
			fprintf(stderr, ".");

		n += chunksize;
	}

	free(chunk);

	return 0;
}

int test_tar_file(const char *tarfile)
{
	struct tar_data_src tardata;
	const char *filename;
	int r = 0;

	fprintf(stderr, "tar %s\n", tarfile);

	r = tardata_open(&tardata, tarfile);
	if (r < 0) {
		fprintf(stderr, "line %d: failed to open %s\n", __LINE__, tarfile);
		return r;
	}

	while (1) {
		filename = tardata_next(&tardata);
		if (!filename)
			break;

		fprintf(stderr, " entry %s ", filename);

		r = test_tar_entry(&tardata.src);
		if (r) {
			fprintf(stderr, "bad\n");
			break;
		}

		fprintf(stderr, "\n");
	}

	tardata_close(&tardata);

	return r;
}


int test_tar_file_list(char **tarfilelist)
{
	int r;

	while (*tarfilelist) {
		char *tarfile = *tarfilelist;

		r = test_tar_file(tarfile);
		if (r < 0)
			fprintf(stderr, "failed to load %s\n", *tarfilelist);
		tarfilelist++;
	}

	return 0;
}

void usage(const char *exename)
{
	fprintf(stderr, "%s: [-t] [-v] [-i] [-d port] [-p pitfile] [tar] [tar] ..\n",
			exename);
	exit(1);
}

int main(int argc, char **argv)
{
	const char *exename, *portname, *pitfile;
	int opt;
	int opt_check = 0;

	exename = argv[0];

	opt = 1;

	pitfile = NULL;
	portname = NULL;

	printf("\n");
	printf("Linux Thor downloader, version %s \n", PACKAGE_VERSION);
	printf("Authors: YoungJin Lee <yj0701.lee@samsung.com>\n\n");

	while (opt < argc) {
		/* check if we're verbose */
		if (!strcmp(argv[opt], "-v")) {
			opt_verbose = 1;
			opt++;
			continue;
		}

		if (!strcmp(argv[opt], "-t")) {
			opt_test = 1;
			opt++;
			continue;
		}

		if  (!strcmp(argv[opt], "-c")) {
		        opt_check = 1;
		        opt++;
		        continue;
		}

		if (!strcmp(argv[opt], "-p")) {
			pitfile = argv[opt+1];
			opt += 2;
			continue;
		}

		if (!strcmp(argv[opt], "-d") && (opt+1) < argc) {
			portname = argv[opt+1];
			opt += 2;
			continue;
		}

		break;
	}

	if (opt_test)
		return test_tar_file_list(&argv[opt]);

	if (opt_check)
		return check_proto(portname);

	if ((pitfile)&&(opt == argc))
		return process_download(portname, pitfile, NULL);

	if (opt < argc)
		return process_download(portname, pitfile, &argv[opt]);

	usage(exename);
	return 0;
}