1 /**
2   ******************************************************************************
3   * @file    rtl8721d_ota.c
4   * @author
5   * @version V1.0.0
6   * @date    2016-12-19
7   * @brief   This file contains the code which is used to update firmware over the air(OTA) in local area network
8   *
9   *  @verbatim
10   *
11   *          ===================================================================
12   *                                 How to use the local OTA upgrade code
13   *          ===================================================================
14   *          1. Firstly, read the OTA related documents to know about how the code to realize updating firmware
15   *              over the air(OTA), and some protocol included in it.
16   *
17   *          2. Read the source code and APIs in this file.
18   *
19   *          3. Porting this code in this file to the specified cloud platform according to the upgrade flow and parameters of
20   *              the specified cloud service providers
21   *
22   *          4. Test the code after porting on the specified cloud platform.
23   *
24   *          5. Generate the release verision that will run.
25   *
26   *          ===================================================================
27   *                                 the basic flow of the local ota upgrade code
28   *          ===================================================================
29   *          (1) Connects to server
30   *
31   *          (2) Receive newer firmware file header from server
32   *
33   *          (3) Parse firmware file header and get the target OTA image header
34   *
35   *          (4) Erase flash space for new firmware
36   *
37   *          (5) Download new firmware from server and write it to flash
38   *
39   *          (6) Verify checksum and update signature
40   *
41   *	      (7) OTA upgrade successfully, restart device
42   *  @endverbatim
43   *
44   ******************************************************************************
45   * @attention
46   *
47   * This module is a confidential and proprietary property of RealTek and
48   * possession or use of this module requires written permission of RealTek.
49   *
50   * Copyright(c) 2016, Realtek Semiconductor Corporation. All rights reserved.
51   ******************************************************************************
52   */
53 #include <stdlib.h>
54 #include <string.h>
55 #include <FreeRTOS.h>
56 //#include <task.h>
57 #include <lwip/sockets.h>
58 //#include <sys.h>
59 
60 #include <device_lock.h>
61 #include "ameba_soc.h"
62 #include "lwip/netdb.h"
63 
64 #include "osdep_service.h"
65 //sys_thread_t TaskOTA = NULL;
66 
67 void rtc_backup_timeinfo(void);
68 
69 #if (SERVER_TYPE == SERVER_LOCAL)
70 
71 typedef struct
72 {
73 	uint32_t	ip_addr;
74 	uint16_t	port;
75 }update_cfg_local_t;
76 
77 const u32 IMG_ADDR[MAX_IMG_NUM][2] = {
78 	{LS_IMG2_OTA1_ADDR, LS_IMG2_OTA2_ADDR},
79 };
80 
81 /**
82   * @brief  Allocate memory from heap.
83   * @param  size: the number of bytes to be allocated.
84   * @retval The pointer to the allocated memory.
85   */
ota_update_malloc(unsigned int size)86 void* ota_update_malloc(unsigned int size)
87 {
88 	return rtw_malloc(size);
89 }
90 
91 /**
92   * @brief  Deallocate memory from heap.
93   * @param  buf: the pointer to the memory to be deallocated.
94   * @retval none
95   */
ota_update_free(void * buf)96 void ota_update_free(void *buf)
97 {
98 	rtw_free(buf);
99 }
100 
101 /**
102   * @brief  Reset CPU
103   * @param  none
104   * @retval none
105   */
ota_platform_reset(void)106 void ota_platform_reset(void)
107 {
108 	WDG_InitTypeDef WDG_InitStruct;
109 	u32 CountProcess;
110 	u32 DivFacProcess;
111 
112 	rtw_msleep_os(100);
113 
114 	/* CPU reset: Cortex-M3 SCB->AIRCR*/
115 	//NVIC_SystemReset();
116 
117 #if defined(CONFIG_MBED_API_EN) && CONFIG_MBED_API_EN
118 	rtc_backup_timeinfo();
119 #endif
120 
121 	WDG_Scalar(50, &CountProcess, &DivFacProcess);
122 	WDG_InitStruct.CountProcess = CountProcess;
123 	WDG_InitStruct.DivFacProcess = DivFacProcess;
124 	WDG_Init(&WDG_InitStruct);
125 
126 	WDG_Cmd(ENABLE);
127 }
128 
129 /**
130   * @brief  Read a stream of data from specified address in user mode
131   * @param obj: Flash object define in application software.
132   * @param  address: Specifies the starting address to read from.
133   * @param  len: Specifies the length of the data to read.
134   * @param  data: Specified the address to save the readback data.
135   * @retval   status: Success:1 or Failure: Others.
136   * @note SPIC user mode is used because this mode can bypass RSIP(include OTF and MMU).
137   *           User mode can read original data from physical address without decrypting, which is
138   *           useful when calculate checksum.
139   */
140 IMAGE2_RAM_TEXT_SECTION
ota_readstream_user(u32 address,u32 len,u8 * data)141 int  ota_readstream_user(u32 address, u32 len, u8 * data)
142 {
143 	assert_param(data != NULL);
144 
145 	u32 offset_to_align;
146 	u32 i;
147 	u32 read_word;
148 	u8 *ptr;
149 	u8 *pbuf;
150 
151 	FLASH_Write_Lock();
152 
153 	offset_to_align = address & 0x03;
154 	pbuf = data;
155 	if (offset_to_align != 0) {
156 		/* the start address is not 4-bytes aligned */
157 		FLASH_RxData(0, address - offset_to_align, 4, (u8*)&read_word);
158 
159 		ptr = (u8*)&read_word + offset_to_align;
160 		offset_to_align = 4 - offset_to_align;
161 		for (i=0;i<offset_to_align;i++) {
162 			*pbuf = *(ptr+i);
163 			pbuf++;
164 			len--;
165 			if (len == 0) {
166 				break;
167 			}
168 		}
169 	}
170 
171 	/* address = next 4-bytes aligned */
172 	address = (((address-1) >> 2) + 1) << 2;
173 
174 	ptr = (u8*)&read_word;
175 	if ((u32)pbuf & 0x03) {
176 		while (len >= 4) {
177 			FLASH_RxData(0, address, 4, (u8*)&read_word);
178 
179 			for (i=0;i<4;i++) {
180 				*pbuf = *(ptr+i);
181 				pbuf++;
182 			}
183 			address += 4;
184 			len -= 4;
185 		}
186 	} else {
187 		while (len >= 4) {
188 			FLASH_RxData(0, address, 4, pbuf);
189 
190 			pbuf += 4;
191 			address += 4;
192 			len -= 4;
193 		}
194 	}
195 
196 	if (len > 0) {
197 		FLASH_RxData(0, address, 4, (u8*)&read_word);
198 
199 		for (i=0;i<len;i++) {
200 			*pbuf = *(ptr+i);
201 			pbuf++;
202 		}
203 	}
204 
205 	FLASH_Write_Unlock();
206 
207 	return 1;
208 }
209 
210 /**
211   * @brief  Write a stream of data to specified address in user mode
212   * @param  address: Specifies the starting address to write to.
213   * @param  len: Specifies the length of the data to write.
214   * @param  data: Pointer to a byte array that is to be written.
215   * @retval   status: Success:1 or Failure: Others.
216   * @note   SPIC user mode is used because this mode can bypass RSIP(include OTF and MMU).
217   *           User mode can read original data from physical address without decrypting, which is
218   *           useful when address or len is not 4 byte aligned.
219   */
220 IMAGE2_RAM_TEXT_SECTION
ota_writestream_user(u32 address,u32 len,u8 * data)221 int  ota_writestream_user(u32 address, u32 len, u8 * data)
222 {
223 	// Check address: 4byte aligned & page(256bytes) aligned
224 	u32 page_begin = address &  (~0xff);
225 	u32 page_end = (address + len) & (~0xff);
226 	u32 page_cnt = ((page_end - page_begin) >> 8) + 1;
227 
228 	u32 addr_begin = address;
229 	u32 addr_end = (page_cnt == 1) ? (address + len) : (page_begin + 0x100);
230 	u32 size = addr_end - addr_begin;
231 	u8 *buffer = data;
232 	u8 write_data[12];
233 
234 	u32 offset_to_align;
235 	u32 read_word;
236 	u32 i;
237 
238 	FLASH_Write_Lock();
239 	while(page_cnt){
240 		offset_to_align = addr_begin & 0x3;
241 
242 		if(offset_to_align != 0){
243 			FLASH_RxData(0, addr_begin - offset_to_align, 4, (u8*)&read_word);
244 
245 			for(i = offset_to_align;i < 4;i++){
246 				read_word = (read_word &  (~(0xff << (8*i)))) |( (*buffer) <<(8*i));
247 				size--;
248 				buffer++;
249 				if(size == 0)
250 					break;
251 			}
252 			FLASH_TxData12B(addr_begin - offset_to_align, 4, (u8*)&read_word);
253 		}
254 
255 		addr_begin = (((addr_begin-1) >> 2) + 1) << 2;
256 		for(;size >= 12 ;size -= 12){
257 			_memcpy(write_data, buffer, 12);
258 			FLASH_TxData12B(addr_begin, 12, write_data);
259 
260 			buffer += 12;
261 			addr_begin += 12;
262 		}
263 
264 		for(;size >= 4; size -=4){
265 			_memcpy(write_data, buffer, 4);
266 			FLASH_TxData12B(addr_begin, 4, write_data);
267 
268 			buffer += 4;
269 			addr_begin += 4;
270 		}
271 
272 		if(size > 0){
273 			FLASH_RxData(0, addr_begin, 4, (u8*)&read_word);
274 
275 			for( i = 0;i < size;i++){
276 				read_word = (read_word & (~(0xff << (8*i)))) | ((*buffer) <<(8*i));
277 				buffer++;
278 			}
279 			FLASH_TxData12B(addr_begin, 4, (u8*)&read_word);
280 		}
281 
282 		page_cnt--;
283 		addr_begin = addr_end;
284 		addr_end = (page_cnt == 1) ? (address + len) : (((addr_begin>>8) + 1)<<8);
285 		size = addr_end - addr_begin;
286 	}
287 
288 	DCache_Invalidate(address, len);
289 	FLASH_Write_Unlock();
290 
291 	return 1;
292 }
293 
294 /**
295   * @brief  get current image2 location
296   * @param  none
297   * @retval  The retval can be one of the followings:
298   *              OTA_INDEX_1: current images located in OTA1 address space
299   *              OTA_INDEX_2: current images located in OTA2 address space
300   */
ota_get_cur_index(void)301 u32 ota_get_cur_index(void)
302 {
303 	u32 AddrStart, Offset, IsMinus, PhyAddr;;
304 
305 	RSIP_REG_TypeDef* RSIP = ((RSIP_REG_TypeDef *) RSIP_REG_BASE);
306 	u32 CtrlTemp = RSIP->FLASH_MMU[0].MMU_ENTRYx_CTRL;
307 
308 	if (CtrlTemp & MMU_BIT_ENTRY_VALID) {
309 		AddrStart = RSIP->FLASH_MMU[0].MMU_ENTRYx_STRADDR;
310 		Offset = RSIP->FLASH_MMU[0].MMU_ENTRYx_OFFSET;
311 		IsMinus = CtrlTemp & MMU_BIT_ENTRY_OFFSET_MINUS;
312 
313 		if(IsMinus)
314 			PhyAddr = AddrStart - Offset;
315 		else
316 			PhyAddr = AddrStart + Offset;
317 
318 		if(PhyAddr == LS_IMG2_OTA1_ADDR)
319 			return OTA_INDEX_1;
320 		else if(PhyAddr == LS_IMG2_OTA2_ADDR)
321 			return OTA_INDEX_2;
322 	}
323 
324 	return OTA_INDEX_1;
325 }
326 
327 /**
328   * @brief  disable flash run time decrypt in some special FLASH area
329   * @param Addr: FLASH area address (should 4k alignment)
330   * @param Len: number of bytes
331   * @param NewStatus This parameter can be one of the following values
332   *		 @arg DISABLE close this area run time decypt mask
333   *		 @arg ENABLE enable this area run time decypt mask (this area will not be decrypt when read)
334   */
ota_rsip_mask(u32 addr,u32 len,u8 status)335 void ota_rsip_mask(u32 addr, u32 len, u8 status)
336 {
337 	u32 NewImg2BlkSize = ((len - 1)/4096) + 1;
338 
339 	RSIP_OTF_Mask(1, addr, NewImg2BlkSize, status);
340 	DCache_Invalidate(addr, len);
341 }
342 
343 /**
344   * @brief  receive file_info from server. This operation is patched for the compatibility with ameba.
345   * @param  Recvbuf: point for receiving buffer
346   * @param  len: length of file info
347   * @param  socket: socket handle
348   * @retval 0: receive fail, 1: receive ok
349   */
recv_file_info_from_server(u8 * Recvbuf,u32 len,int socket)350 u32 recv_file_info_from_server(u8 * Recvbuf, u32 len, int socket)
351 {
352 	int read_bytes = 0;
353 	u32 TempLen;
354 	u8 * buf;
355 
356 	/*read 4 Dwords from server, get image header number and header length*/
357 	buf = Recvbuf;
358 	TempLen = len;
359 	while(TempLen > 0) {
360 		read_bytes = lwip_read(socket, buf, TempLen);
361 		if(read_bytes < 0){
362 			printf("\n\r[%s] read socket failed\n", __FUNCTION__);
363 			goto error;
364 		}
365 		if(read_bytes == 0) {
366 			break;
367 		}
368 		TempLen -= read_bytes;
369 		buf += read_bytes;
370 	}
371 
372 	return 1;
373 error:
374 	return 0;
375 }
376 
377 /**
378   * @brief	  receive OTA firmware file header from server.
379   * @param  Recvbuf: pointer to buffer for receiving OTA header of firmware file
380   * @param  len: data length to be received from server
381   * @param  pOtaTgtHdr: point to target image OTA  header
382   * @param  socket: socket handle
383   * @retval 0: receive fail, 1: receive ok
384   */
recv_ota_file_hdr(u8 * Recvbuf,u32 * len,update_ota_target_hdr * pOtaTgtHdr,int socket)385 u32 recv_ota_file_hdr(u8 * Recvbuf, u32 * len, update_ota_target_hdr * pOtaTgtHdr, int socket)
386 {
387 	int read_bytes = 0;
388 	u32 TempLen;
389 	u8 * buf;
390 	update_file_hdr * pOtaFileHdr;
391 	update_file_img_hdr * pOtaFileImgHdr;
392 
393 	/*read 4 Dwords from server, get image header number and header length*/
394 	buf = Recvbuf;
395 	TempLen = 16;
396 	while(TempLen > 0) {
397 		read_bytes = lwip_read(socket, buf, TempLen);
398 		if(read_bytes < 0){
399 			printf("\n\r[%s] read socket failed\n", __FUNCTION__);
400 			goto error;
401 		}
402 		if(read_bytes == 0) {
403 			break;
404 		}
405 		TempLen -= read_bytes;
406 		buf += read_bytes;
407 	}
408 
409 	pOtaFileHdr = (update_file_hdr *)Recvbuf;
410 	pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
411 
412 	pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
413 	pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
414 
415 	/*read the remaining Header info*/
416 	buf = Recvbuf + 16;
417 	TempLen =  (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) - 8;
418 	while(TempLen > 0) {
419 		read_bytes = lwip_read(socket, buf, TempLen);
420 		if(read_bytes < 0){
421 			printf("\n\r[%s] read socket failed\n", __FUNCTION__);
422 			goto error;
423 		}
424 		if(read_bytes == 0) {
425 			break;
426 		}
427 		TempLen -= read_bytes;
428 		buf += read_bytes;
429 	}
430 
431 	*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
432 
433 	return 1;
434 error:
435 	return 0;
436 }
437 
438 /**
439   * @brief	  parse firmware file header and get the desired OTA header
440   * @param   buf: point to buffer for receiving OTA header of new firmware
441   * @param   len: data length to be received from server
442   * @param   pOtaTgtHdr:point to target image OTA  header
443   * @param   ImgId: point to image identification strings
444   * @retval 0: receive fail, 1: receive ok
445   */
get_ota_tartget_header(u8 * buf,u32 len,update_ota_target_hdr * pOtaTgtHdr,u8 target_idx)446 u32 get_ota_tartget_header(u8* buf, u32 len, update_ota_target_hdr * pOtaTgtHdr, u8 target_idx)
447 {
448 	update_file_img_hdr * ImgHdr;
449 	update_file_hdr * FileHdr;
450 	u8 * pTempAddr;
451 	u32 i = 0, j = 0;
452 	int index = -1;
453 
454 	/*check if buf and len is valid or not*/
455 	if((len < (sizeof(update_file_img_hdr) + 8)) || (!buf)) {
456 		goto error;
457 	}
458 
459 	FileHdr = (update_file_hdr *)buf;
460 	ImgHdr = (update_file_img_hdr *)(buf + 8);
461 	pTempAddr = buf + 8;
462 
463 	if(len < (FileHdr->HdrNum * ImgHdr->ImgHdrLen + 8)) {
464 		goto error;
465 	}
466 
467 	/*get the target OTA header from the new firmware file header*/
468 	for(i = 0; i < FileHdr->HdrNum; i++) {
469 		index = -1;
470 		pTempAddr = buf + 8 + ImgHdr->ImgHdrLen * i;
471 
472 		if(strncmp("OTA", (const char *)pTempAddr, 3) == 0)
473 			index = 0;
474 		else
475 			goto error;
476 
477 		if(index >= 0) {
478 			_memcpy((u8*)(&pOtaTgtHdr->FileImgHdr[j]), pTempAddr, sizeof(update_file_img_hdr));
479 			pOtaTgtHdr->FileImgHdr[j].FlashAddr = IMG_ADDR[index][target_idx];
480 			j++;
481 		}
482 	}
483 
484 	pOtaTgtHdr->ValidImgCnt = j;
485 
486 	if(j == 0) {
487 		printf("\n\r[%s] no valid image\n", __FUNCTION__);
488 		goto error;
489 	}
490 
491 	return 1;
492 error:
493 	return 0;
494 }
495 
496 /**
497   * @brief	  erase the flash space for new firmware.
498   * @param   addr: new image address
499   * @param   len: new image length
500   * @retval  none
501   */
erase_ota_target_flash(u32 addr,u32 len)502 void erase_ota_target_flash( u32 addr, u32 len)
503 {
504 	u32 sector_cnt;
505 	u32 i;
506 
507 	sector_cnt = ((len - 1)/4096) + 1;
508 
509 	device_mutex_lock(RT_DEV_LOCK_FLASH);
510 	for( i = 0; i < sector_cnt; i++)
511 		FLASH_EraseXIP(EraseSector, addr -SPI_FLASH_BASE + i * 4096);
512 
513 	device_mutex_unlock(RT_DEV_LOCK_FLASH);
514 }
515 
516 /**
517   * @brief	   download new firmware from server and write it to flash.
518   * @param     addr: new image address
519   * @param     socket: socket handle
520   * @param     pOtaTgtHdr: point to target image OTA  header
521   * @param     signature: point to signature strings
522   * @retval   download size of OTA image
523   */
download_new_fw_from_server(int socket,update_ota_target_hdr * pOtaTgtHdr,u8 targetIdx)524 u32 download_new_fw_from_server(int socket, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
525 {
526 	/* To avoid gcc warnings */
527 	( void ) targetIdx;
528 
529 	u8 * alloc;
530 	u8 * buf;
531 	s32 size = 0;
532 	int read_bytes;
533 	int read_bytes_buf;
534 	u32 TempLen;
535 	u32 ImageCnt;
536 	update_dw_info DownloadInfo[MAX_IMG_NUM];
537 
538 	/*initialize the variables used in downloading procedure*/
539 	u32 OtaFg = 0;
540 	u32 IncFg = 0;
541 	s32 RemainBytes;
542 	u32 SigCnt = 0;
543 	u32 TempCnt = 0;
544 	u32 i;
545 	u8 res = _TRUE;
546 	u8 * signature;
547 
548 	/*acllocate buffer for downloading image from server*/
549 	alloc = ota_update_malloc(BUF_SIZE);
550 
551 	buf = alloc;
552 
553 	/*init download information buffer*/
554 	memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
555 
556 	ImageCnt = pOtaTgtHdr->ValidImgCnt;
557 	for(i = 0; i < ImageCnt; i++) {
558 		/* get OTA image and Write New Image to flash, skip the signature,
559 			not write signature first for power down protection*/
560 		DownloadInfo[i].ImgId = OTA_IMAG;
561 		DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
562 		DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
563 		DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
564 	}
565 
566 	/*initialize the reveiving counter*/
567 	TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
568 
569 	/*downloading parse the OTA and RDP image from the data stream sent by server*/
570 	for(i = 0; i < ImageCnt; i++) {
571 
572 		/*the next image length*/
573 		RemainBytes = DownloadInfo[i].ImageLen;
574 		signature = &pOtaTgtHdr->Sign[i][0];
575 
576 		/*download the new firmware from server*/
577 		while(RemainBytes > 0){
578 			buf = alloc;
579 			if(IncFg == 1) {
580 				IncFg = 0;
581 				read_bytes = read_bytes_buf;
582 			} else {
583 				memset(buf, 0, BUF_SIZE);
584 				read_bytes = lwip_read(socket, buf, BUF_SIZE);
585 				if(read_bytes == 0){
586 					break; // Read end
587 				}
588 				if(read_bytes < 0){
589 					//OtaImgSize = -1;
590 					printf("\n\r[%s] Read socket failed", __FUNCTION__);
591 					res = _FALSE;
592 					goto exit;
593 				}
594 				read_bytes_buf = read_bytes;
595 				TempLen += read_bytes;
596 			}
597 
598 			if(TempLen > DownloadInfo[i].ImgOffset) {
599 				if(!OtaFg) {
600 					/*reach the desired image, the first packet process*/
601 					OtaFg = 1;
602 					TempCnt = TempLen -DownloadInfo[i].ImgOffset;
603 					if(TempCnt < 8) {
604 						SigCnt = TempCnt;
605 					} else {
606 						SigCnt = 8;
607 					}
608 
609 					_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
610 
611 					if((SigCnt < 8) || (TempCnt -8 == 0)) {
612 						continue;
613 					}
614 
615 					buf = buf + (read_bytes -TempCnt + 8);
616 					read_bytes = TempCnt -8;
617 				} else {
618 					/*normal packet process*/
619 					if(SigCnt < 8) {
620 						if(read_bytes < (int)(8 -SigCnt)) {
621 							_memcpy(signature + SigCnt, buf, read_bytes);
622 							SigCnt += read_bytes;
623 							continue;
624 						} else {
625 							_memcpy(signature + SigCnt, buf, (8 -SigCnt));
626 							buf = buf + (8 - SigCnt);
627 							read_bytes -= (8 - SigCnt) ;
628 							SigCnt = 8;
629 							if(!read_bytes) {
630 								continue;
631 							}
632 						}
633 					}
634 				}
635 
636 				RemainBytes -= read_bytes;
637 				if(RemainBytes < 0) {
638 					read_bytes = read_bytes -(-RemainBytes);
639 				}
640 
641 				device_mutex_lock(RT_DEV_LOCK_FLASH);
642 				if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
643 					printf("\n\r[%s] Write sector failed", __FUNCTION__);
644 					device_mutex_unlock(RT_DEV_LOCK_FLASH);
645 					res = _FALSE;
646 					goto exit;
647 				}
648 				device_mutex_unlock(RT_DEV_LOCK_FLASH);
649 				size += read_bytes;
650 			}
651 		}
652 
653 		printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
654 		if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
655 			printf("\n\rdownload new firmware failed\n");
656 			goto exit;
657 		}
658 
659 		/*update flag status*/
660 		size = 0;
661 		OtaFg = 0;
662 		IncFg = 1;
663 	}
664 
665 exit:
666 	ota_update_free(alloc);
667 
668 	return res;
669 }
670 
671 /**
672   * @brief	  verify new firmware checksum.
673   * @param  addr: new image address
674   * @param  len: new image length
675   * @param  signature: point to signature strings
676   * @param  pOtaTgtHdr: point to target image OTA  header
677   * @retval 0: verify fail, 1: verify ok
678   */
verify_ota_checksum(update_ota_target_hdr * pOtaTgtHdr)679 u32 verify_ota_checksum(update_ota_target_hdr * pOtaTgtHdr)
680 {
681 	u32 i, index;
682 	u32 flash_checksum=0;
683 	u32 addr, len;
684 	u8 * signature;
685 	u8 * pTempbuf;
686 	int k;
687 	int rlen;
688 	u8 res = _TRUE;
689 
690 	pTempbuf = ota_update_malloc(BUF_SIZE);
691 
692 	for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
693 		flash_checksum = 0;
694 
695 		addr = pOtaTgtHdr->FileImgHdr[index].FlashAddr;
696 		len = pOtaTgtHdr->FileImgHdr[index].ImgLen - 8;
697 		signature = &pOtaTgtHdr->Sign[index][0];
698 
699 		/* read flash data back and calculate checksum */
700 		for(i=0;i<len;i+=BUF_SIZE){
701 			rlen = (len-i)>BUF_SIZE?BUF_SIZE:(len-i);
702 			ota_readstream_user(addr - SPI_FLASH_BASE+i+8, rlen, pTempbuf);
703 
704 			for(k=0;k<rlen;k++)
705 				flash_checksum+=pTempbuf[k];
706 		}
707 		/*add signature's checksum*/
708 		for(i = 0; i < 8; i++) {
709 			flash_checksum += signature[i];
710 		}
711 
712 		if(flash_checksum != pOtaTgtHdr->FileImgHdr[index].Checksum) {
713 			printf("\n\rOTA image(%08x) checksum error!!!\nCalculated checksum 0x%8x, host checksum 0x%8x\n", addr, \
714 			flash_checksum, pOtaTgtHdr->FileImgHdr[index].Checksum);
715 			res = _FALSE;
716 
717 			goto EXIT;
718 		} else {
719 			printf("\n\rOTA image(%08x) checksum ok!!!\n", addr);
720 		}
721 	}
722 
723 EXIT:
724 	ota_update_free(pTempbuf);
725 
726 	return res;
727 }
728 
729 /**
730   * @brief	  update signature.
731   * @param  addr: new image address
732   * @retval 0: change signature fail, 1: change signature ok
733   */
change_ota_signature(update_ota_target_hdr * pOtaTgtHdr,u32 ota_target_index)734 u32 change_ota_signature(update_ota_target_hdr * pOtaTgtHdr, u32 ota_target_index)
735 {
736 	u32 addr;
737 	u8 * signature;
738 	u8 index;
739 	u8 ota_old_index = ota_target_index ^ 1;
740 	u8 empty_sig = 0x0;
741 
742 	device_mutex_lock(RT_DEV_LOCK_FLASH);
743 
744 	for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
745 		addr = pOtaTgtHdr->FileImgHdr[index].FlashAddr;
746 		signature = &pOtaTgtHdr->Sign[index][0];
747 
748 		/*write the signature finally*/
749 		if(FLASH_WriteStream(addr - SPI_FLASH_BASE, 8, signature) < 0){
750 			printf("\n\r[%s] Write sector failed", __FUNCTION__);
751 			device_mutex_unlock(RT_DEV_LOCK_FLASH);
752 			goto error;
753 		}
754 	}
755 
756 	for(index = 0; index < pOtaTgtHdr->ValidImgCnt; index++) {
757 		if(strncmp("OTA", (const char *)pOtaTgtHdr->FileImgHdr[index].ImgId, 3) == 0)
758 			addr = IMG_ADDR[0][ota_old_index];
759 
760 		/*clear the old FW signature finally*/
761 		if(FLASH_WriteStream(addr - SPI_FLASH_BASE, 4, &empty_sig) < 0){
762 			printf("\n\r[%s] Write sector failed", __FUNCTION__);
763 			device_mutex_unlock(RT_DEV_LOCK_FLASH);
764 			goto error;
765 		}
766 	}
767 
768 	device_mutex_unlock(RT_DEV_LOCK_FLASH);
769 	printf("\n\r[%s] Update OTA success!", __FUNCTION__);
770 
771 	return 1;
772 error:
773 	return 0;
774 }
775 
776 #if 0
777 /**
778   * @brief	  OTA upgrade task for single image method.
779   * @param  param: pointer to configuration of server
780   * @retval none
781   */
782 static void ota_update_local_task(void *param)
783 {
784 	int server_socket;
785 	struct sockaddr_in server_addr;
786 	unsigned char *alloc;
787 	update_cfg_local_t *cfg = (update_cfg_local_t *)param;
788 	uint32_t file_info[3];
789 	int ret = -1 ;
790 	uint32_t ota_target_index = OTA_INDEX_2;
791 	update_ota_target_hdr OtaTargetHdr;
792 	u32 RevHdrLen;
793 	u8 i = 0;
794 
795 	memset((u8 *)&OtaTargetHdr, 0, sizeof(update_ota_target_hdr));
796 	printf("\n\r[%s] Update task start\n", __FUNCTION__);
797 
798 	alloc = ota_update_malloc(BUF_SIZE);
799 	if(!alloc){
800 		printf("\n\r[%s] Alloc buffer failed", __FUNCTION__);
801 		goto update_ota_exit;
802 	}
803 
804 	/*-------------------step1: connect to server-------------------*/
805 	server_socket = socket(AF_INET, SOCK_STREAM, 0);
806 	if(server_socket < 0){
807 		printf("\n\r[%s] Create socket failed", __FUNCTION__);
808 		goto update_ota_exit;
809 	}
810 	server_addr.sin_family = AF_INET;
811 	server_addr.sin_addr.s_addr = cfg->ip_addr;
812 	server_addr.sin_port = cfg->port;
813 
814 	if(connect(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
815 		printf("\n\r[%s] socket connect failed", __FUNCTION__);
816 		goto update_ota_exit;
817 	}
818 
819 	DBG_INFO_MSG_OFF(MODULE_FLASH);
820 
821 	/* check OTA index we should update */
822 	if (ota_get_cur_index() == OTA_INDEX_1) {
823 		ota_target_index = OTA_INDEX_2;
824 		printf("\n\r[%s] OTA2 address space will be upgraded", __FUNCTION__);
825 
826 	} else {
827 		ota_target_index = OTA_INDEX_1;
828 		printf("\n\r[%s] OTA1 address space will be upgraded", __FUNCTION__);
829 	}
830 
831 	/* Receive file_info[] from server. Add this for compatibility. This file_info includes the
832 	file_size and checksum information of the total firmware file.	Even though the file_info
833 	is received from server , it won't be used.*/
834 	memset(file_info, 0, sizeof(file_info));
835 	if(!recv_file_info_from_server((u8 *)file_info, sizeof(file_info), server_socket)) {
836 		printf("\n\r[%s] receive file_info failed", __FUNCTION__);
837 		goto update_ota_exit;
838 	}
839 
840 	/*----------------step2: receive firmware file header---------------------*/
841 	if(!recv_ota_file_hdr(alloc, &RevHdrLen, &OtaTargetHdr, server_socket)) {
842 		printf("\n\r[%s] rev firmware header failed", __FUNCTION__);
843 		goto update_ota_exit;
844 	}
845 
846 	/* -----step3: parse firmware file header and get the target OTA image header-----*/
847 	if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
848 		printf("\n\rget OTA header failed\n");
849 		goto update_ota_exit;
850 	}
851 
852 	/* the upgrade space should be masked */
853 	//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
854 
855 	/*-------------------step4: erase flash space for new firmware--------------*/
856 	/*erase flash space new OTA image */
857 	printf("\n\rErase is ongoing...");
858 
859 	for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
860 		erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
861 	}
862 
863 	/*---------step5: download new firmware from server and write it to flash--------*/
864 	//size = download_new_fw_from_server(NewImg2Addr, server_socket, &OtaTargetHdr, signature);
865 	if(download_new_fw_from_server(server_socket, &OtaTargetHdr, ota_target_index) == _FALSE){
866 		goto update_ota_exit;
867 	}
868 
869 	 /*-------------step6: verify checksum and update signature-----------------*/
870 	if(verify_ota_checksum(&OtaTargetHdr)){
871 		if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
872 			printf("\n\rChange signature failed\n");
873 			goto update_ota_exit;
874 		}
875 		ret = 0;
876 	}
877 
878 	/* unmask the upgrade space */
879 	//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, DISABLE);
880 
881 update_ota_exit:
882 	if(alloc)
883 		ota_update_free(alloc);
884 	if(server_socket >= 0)
885 		close(server_socket);
886 	if(param)
887 		ota_update_free(param);
888 
889 	TaskOTA = NULL;
890 	printf("\n\r[%s] Update task exit", __FUNCTION__);
891 
892 	/*-------------step7: OTA upgrade successfully, restart device------------*/
893 	if(!ret){
894 		//printf("\n\r[%s] Ready to reboot", __FUNCTION__);
895 		//ota_platform_reset();
896 		printf("\n\rOTA is finished. Please reset device.", __FUNCTION__);
897 	}
898 	vTaskDelete(NULL);
899 	return;
900 
901 }
902 
903 int update_ota_local(char *ip, int port)
904 {
905 	update_cfg_local_t *pUpdateCfg;
906 
907 	if(TaskOTA){
908 		printf("\n\r[%s] Update task has created.", __FUNCTION__);
909 		return 0;
910 	}
911 	pUpdateCfg = ota_update_malloc(sizeof(update_cfg_local_t));
912 	if(pUpdateCfg == NULL){
913 		printf("\n\r[%s] Alloc update cfg failed", __FUNCTION__);
914 		return -1;
915 	}
916 	pUpdateCfg->ip_addr = inet_addr(ip);
917 	pUpdateCfg->port = ntohs(port);
918 
919 	if(xTaskCreate(ota_update_local_task, "OTA_server", 1024, pUpdateCfg, tskIDLE_PRIORITY + 1, &TaskOTA) != pdPASS){
920 	  	ota_update_free(pUpdateCfg);
921 		printf("\n\r[%s] Create update task failed", __FUNCTION__);
922 	}
923 
924 	return 0;
925 }
926 
927 #endif // #if (SERVER_TYPE == SERVER_LOCAL)
928 #endif
929 #if 0
930 /*  choose to boot from ota2 image or not */
931 void cmd_ota_image(bool cmd)
932 {
933 	/* To avoid gcc warnings */
934 	( void ) cmd;
935 #if 0
936 	if (cmd == 1)
937 		OTA_Change(OTA_INDEX_2);
938 	else
939 		OTA_Change(OTA_INDEX_1);
940 #endif
941 }
942 
943 void cmd_update(int argc, char **argv)
944 {
945 #if (SERVER_TYPE == SERVER_LOCAL)
946 
947 	int port;
948 	if(argc != 3){
949 		printf("\n\r[%s] Usage: update IP PORT", __FUNCTION__);
950 		return;
951 	}
952 	port = atoi(argv[2]);
953 	update_ota_local(argv[1], port);
954 
955 #elif (SERVER_TYPE == SERVER_CLOUD)
956 
957 	printf("OTA demo doesn't support update from cloud server. "
958 	"Please customized OTA process according to the standard of different cloud providers\n");
959 
960 #endif
961 }
962 #endif
963 
964 #if 0
965 #if (defined HTTP_OTA_UPDATE) || (defined HTTPS_OTA_UPDATE)
966 static char *redirect = NULL;
967 static int redirect_len;
968 static u16 redirect_server_port;
969 static char *redirect_server_host = NULL;
970 static char *redirect_resource = NULL;
971 
972 int  parser_url( char *url, char *host, u16 *port, char *resource)
973 {
974 
975 	if(url){
976 		char *http = NULL, *pos = NULL;
977 
978 		http = strstr(url, "http://");
979 		if(http) // remove http
980 			url += strlen("http://");
981 		memset(host, 0, redirect_len);
982 
983 		pos = strstr(url, ":");	// get port
984 		if(pos){
985 			memcpy(host, url, (pos-url));
986 			pos += 1;
987 			*port = atoi(pos);
988 		}else{
989 			pos = strstr(url, "/");
990 			if(pos){
991 				memcpy(host, url, (pos-url));
992 				url = pos;
993 			}
994 			*port = 80;
995 		}
996 		printf("server: %s\n\r", host);
997 		printf("port: %d\n\r", *port);
998 
999 		memset(resource, 0, redirect_len);
1000 		pos = strstr(url, "/");
1001 		if(pos){
1002 			memcpy(resource, pos + 1, strlen(pos + 1));
1003 		}
1004 		printf("resource: %s\n\r", resource);
1005 
1006 		return 0;
1007 	}
1008 	return -1;
1009 }
1010 
1011 
1012 /**
1013   * @brief  parse http response.
1014   * @param  response: the http response got from server
1015   * @param  response_len: The length of http response
1016   * @param  result: The struct that store the useful info from the http response
1017   * @retval  1:only got status code;3:got status code and content length,but not get the full header;4: got all info;-1:failed
1018   */
1019 int parse_http_response(unsigned char *response, unsigned int response_len, http_response_result_t *result) {
1020 	uint32_t i, p, q, m;
1021 	uint32_t header_end = 0;
1022 
1023 	//Get status code
1024 	if(0 == result->parse_status){//didn't get the http response
1025 		uint8_t status[4] = {0};
1026 		i = p = q = m = 0;
1027 		for (; i < response_len; ++i) {
1028 			if (' ' == response[i]) {
1029 				++m;
1030 				if (1 == m) {//after HTTP/1.1
1031 					p = i;
1032 				}
1033 				else if (2 == m) {//after status code
1034 					q = i;
1035 					break;
1036 				}
1037 			}
1038 		}
1039 		if (!p || !q || q-p != 4) {//Didn't get the status code
1040 			return -1;
1041 		}
1042 		memcpy(status, response+p+1, 3);//get the status code
1043 		result->status_code = atoi((char const *)status);
1044 		if(result->status_code == 200)
1045 			result->parse_status = 1;
1046 		else if(result->status_code == 302)
1047 		{
1048 			char *tmp=NULL;
1049 			const char *location1 = "LOCATION";
1050 			const char *location2 = "Location";
1051 			printf("response 302:%s \r\n", response);
1052 
1053 			if((tmp =strstr((char *)response, location1)) ||(tmp=strstr((char *)response, location2)))
1054 			{
1055 				redirect_len = strlen(tmp+10);
1056 				printf("Location len = %d\r\n", redirect_len);
1057 				if(redirect ==NULL)
1058 				{
1059 					redirect = ota_update_malloc(redirect_len);
1060 					if(redirect == NULL)
1061 					{
1062 						return -1;
1063 					}
1064 				}
1065 				memset(redirect, 0, redirect_len);
1066 				memcpy(redirect, tmp+10, strlen(tmp+10));
1067 			}
1068 
1069 			if(redirect_server_host ==NULL)
1070 			{
1071 				redirect_server_host = ota_update_malloc(redirect_len);
1072 				if(redirect_server_host == NULL)
1073 				{
1074 					return -1;
1075 				}
1076 			}
1077 
1078 			if(redirect_resource ==NULL)
1079 			{
1080 				redirect_resource = ota_update_malloc(redirect_len);
1081 				if(redirect_resource == NULL)
1082 				{
1083 					return -1;
1084 				}
1085 			}
1086 
1087 			memset(redirect_server_host, 0, redirect_len);
1088 			memset(redirect_resource, 0, redirect_len);
1089 			if(parser_url(redirect, redirect_server_host, &redirect_server_port , redirect_resource)<0)
1090 			{
1091 				return -1;
1092 			}
1093 			return -1;
1094 		}
1095 		else{
1096 			printf("\n\r[%s] The http response status code is %d", __FUNCTION__, result->status_code);
1097 			return -1;
1098 		}
1099 	}
1100 
1101 	//if didn't receive the full http header
1102 	if(3 == result->parse_status){//didn't get the http response
1103 		p = q = 0;
1104 		for (i = 0; i < response_len; ++i) {
1105 			if (response[i] == '\r' && response[i+1] == '\n' &&
1106 				response[i+2] == '\r' && response[i+3] == '\n') {//the end of header
1107 				header_end = i+4;
1108 				result->parse_status = 4;
1109 				result->header_len = header_end;
1110 				result->body = response + header_end;
1111 				break;
1112 			}
1113 		}
1114 		if (3 == result->parse_status) {//Still didn't receive the full header
1115 			result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
1116 			memset(result->header_bak, 0, strlen((const char*)result->header_bak));
1117 			memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
1118 		}
1119 	}
1120 
1121 	//Get Content-Length
1122 	if(1 == result->parse_status){//didn't get the content length
1123 		const char *content_length_buf1 = "CONTENT-LENGTH";
1124 		const char *content_length_buf2 = "Content-Length";
1125 		const uint32_t content_length_buf_len = strlen((const char*)content_length_buf1);
1126 		p = q = 0;
1127 
1128 		for (i = 0; i < response_len; ++i) {
1129 			if (response[i] == '\r' && response[i+1] == '\n') {
1130 				q = i;//the end of the line
1131 				if (!memcmp(response+p, content_length_buf1, content_length_buf_len) ||
1132 						!memcmp(response+p, content_length_buf2, content_length_buf_len)) {//get the content length
1133 					unsigned int j1 = p+content_length_buf_len, j2 = q-1;
1134 					while ( j1 < q && (*(response+j1) == ':' || *(response+j1) == ' ') ) ++j1;
1135 					while ( j2 > j1 && *(response+j2) == ' ') --j2;
1136 					uint8_t len_buf[12] = {0};
1137 					memcpy(len_buf, response+j1, j2-j1+1);
1138 					result->body_len = atoi((char const *)len_buf);
1139 					result->parse_status = 2;
1140 				}
1141 				p = i+2;
1142 			}
1143 			if (response[i] == '\r' && response[i+1] == '\n' &&
1144 					response[i+2] == '\r' && response[i+3] == '\n') {//Get the end of header
1145 				header_end = i+4;//p is the start of the body
1146 				if(result->parse_status == 2){//get the full header and the content length
1147 					result->parse_status = 4;
1148 					result->header_len = header_end;
1149 					result->body = response + header_end;
1150 				}
1151 				else {//there are no content length in header
1152 					printf("\n\r[%s] No Content-Length in header", __FUNCTION__);
1153 					return -1;
1154 				}
1155 				break;
1156 			}
1157 		}
1158 
1159 		if (1 == result->parse_status) {//didn't get the content length and the full header
1160 			result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
1161 			memset(result->header_bak, 0, strlen((char *)result->header_bak));
1162 			memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
1163 		}
1164 		else if (2 == result->parse_status) {//didn't get the full header but get the content length
1165 			result->parse_status = 3;
1166 			result->header_bak = ota_update_malloc(HEADER_BAK_LEN + 1);
1167 			memset(result->header_bak, 0, strlen((char *)result->header_bak));
1168 			memcpy(result->header_bak, response + response_len - HEADER_BAK_LEN, HEADER_BAK_LEN);
1169 		}
1170 	}
1171 
1172 	return result->parse_status;
1173 }
1174 
1175 
1176 #ifdef HTTP_OTA_UPDATE
1177 
1178 /**
1179   * @brief  connect to the OTA http server.
1180   * @param  server_socket: the socket used
1181   * @param  host: host address of the OTA server
1182   * @param  port: port of the OTA server
1183   * @retval  -1 when connect fail, socket value when connect success
1184   */
1185 int update_ota_http_connect_server(int server_socket, char *host, int port){
1186 	struct sockaddr_in server_addr;
1187 	struct hostent *server;
1188 
1189 	server_socket = socket(AF_INET, SOCK_STREAM, 0);
1190 	if(server_socket < 0){
1191 		printf("\n\r[%s] Create socket failed", __FUNCTION__);
1192 		return -1;
1193 	}
1194 	printf("[%s] Create socket: %d success!\n", __FUNCTION__, server_socket);
1195 	server = gethostbyname(host);
1196 	if(server == NULL){
1197 		printf("[ERROR] Get host ip failed\n");
1198 		return -1;
1199 	}
1200 
1201 	memset(&server_addr,0,sizeof(server_addr));
1202 	server_addr.sin_family = AF_INET;
1203 	server_addr.sin_port = htons(port);
1204 	memcpy((void *)&server_addr.sin_addr,(void *)server->h_addr,4);
1205 
1206 	if (connect(server_socket,(struct sockaddr *)&server_addr, sizeof(server_addr)) < 0){
1207 		printf("\n\r[%s] Socket connect failed", __FUNCTION__);
1208 		return -1;
1209 	 }
1210 
1211 	return server_socket;
1212 }
1213 
1214   /**
1215   * @brief  receive OTA firmware file header from server
1216   * @param  Recvbuf: pointer to buffer for receiving OTA header of firmware file
1217   * @param  writelen:the length already read from server
1218   * @param  len: data length to be received from server
1219   * @param  pOtaTgtHdr: point to target image OTA  header
1220   * @param  socket: socket handler
1221   * @retval  0:failed;1:success
1222   */
1223 u32 recv_ota_file_hdr_http(u8 * Recvbuf, u32 writelen, u32 * len, update_ota_target_hdr * pOtaTgtHdr, int socket)
1224 {
1225 	int read_bytes = 0;
1226 	u32 TempLen;
1227 	u8 * buf;
1228 	update_file_hdr * pOtaFileHdr;
1229 	update_file_img_hdr * pOtaFileImgHdr;
1230 
1231 	buf = Recvbuf + writelen;
1232 	/*receive the remaining OTA firmware file header info if needed*/
1233 	if (writelen < 32) {
1234 		TempLen = 32 - writelen;
1235 		while(TempLen) {
1236 			read_bytes = recv(socket, buf, TempLen, 0);
1237 			if(read_bytes < 0){
1238 				printf("[%s] read socket failed\n", __FUNCTION__);
1239 				goto error;
1240 			}
1241 			if(read_bytes == 0) {
1242 				break;
1243 			}
1244 			TempLen -= read_bytes;
1245 			buf += read_bytes;
1246 		}
1247 	}
1248 
1249 	pOtaFileHdr = (update_file_hdr *)(Recvbuf);
1250 	pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
1251 
1252 	pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
1253 	pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
1254 
1255 	*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
1256 
1257 	return 1;
1258 error:
1259 	return 0;
1260 }
1261 
1262   /**
1263   * @brief  http read socket
1264   * @param  Recvbuf: pointer to buffer for receiving
1265   * @param  socket: socket handler
1266   * @param  buf_len: read data length
1267   * @retval  >0:success;<0:error
1268   */
1269 int http_read_socket( int socket, u8 *recevie_buf, int buf_len )
1270 {
1271 	int bytes_rcvd = -1;
1272 	if( socket < 0 ) {
1273 		printf("[%s], socket is invalid\n", __FUNCTION__);
1274 		return bytes_rcvd;
1275 	}
1276 	memset(recevie_buf, 0, buf_len);
1277 	//DBG_8195A("R\n");
1278 	bytes_rcvd = recv(socket, recevie_buf, buf_len, 0 );
1279 
1280 	if(bytes_rcvd <= 0) {
1281 		printf("[%s], Close HTTP Socket[%d].\n", socket, __FUNCTION__);
1282 		return -2;
1283 	}
1284 	return bytes_rcvd;
1285 }
1286 
1287 /**
1288   * @brief	  download new firmware from http server and write it to flash.
1289   * @param     first_buf: point data already from http server
1290   * @param     firstbuf_len: the length of already read data
1291   * @param     socket: socket handle
1292   * @param     pOtaTgtHdr: point to target image OTA  header
1293   * @param     targetIdx: target OTA index
1294   * @retval   	download size of OTA image
1295   */
1296 u32 download_new_fw_from_server_http(u8* first_buf, unsigned int firstbuf_len, int socket, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
1297 {
1298 	/* To avoid gcc warnings */
1299 	( void ) targetIdx;
1300 
1301 	u8 * alloc;
1302 	u8 * buf;
1303 	s32 size = 0;
1304 	int read_bytes;
1305 	int read_bytes_buf;
1306 	u32 TempLen;
1307 	u32 ImageCnt;
1308 	update_dw_info DownloadInfo[MAX_IMG_NUM];
1309 	/*initialize the variables used in downloading procedure*/
1310 	u32 OtaFg = 0;
1311 	u32 IncFg = 0;
1312 	u32 firstbufFg = 0;
1313 	s32 RemainBytes;
1314 	u32 SigCnt = 0;
1315 	u32 TempCnt = 0;
1316 	u32 i;
1317 	u8 res = _TRUE;
1318 	u8 * signature;
1319 	u32 write_sector = 0;
1320 	u32 next_erase_sector = 0;
1321 
1322 	/*acllocate buffer for downloading image from server*/
1323 	alloc = ota_update_malloc(BUF_SIZE);
1324 
1325 	buf = alloc;
1326 
1327 	/*init download information buffer*/
1328 	memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
1329 
1330 	ImageCnt = pOtaTgtHdr->ValidImgCnt;
1331 	for(i = 0; i < ImageCnt; i++) {
1332 		/* get OTA image and Write New Image to flash, skip the signature,
1333 			not write signature first for power down protection*/
1334 		DownloadInfo[i].ImgId = OTA_IMAG;
1335 		DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
1336 		DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
1337 		DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
1338 	}
1339 
1340 	/*initialize the reveiving counter*/
1341 	TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
1342 
1343 	/*downloading parse the OTA and RDP image from the data stream sent by server*/
1344 	for(i = 0; i < ImageCnt; i++) {
1345 
1346 		/*the next image length*/
1347 		RemainBytes = DownloadInfo[i].ImageLen;
1348 		signature = &pOtaTgtHdr->Sign[i][0];
1349 
1350 		if (i == 0) {
1351 			if (firstbuf_len > DownloadInfo[i].ImgOffset) {
1352 				firstbufFg = 1;
1353 				TempLen += firstbuf_len -DownloadInfo[i].ImgOffset;
1354 			}
1355 		}
1356 
1357 		/*download the new firmware from server*/
1358 		while(RemainBytes > 0){
1359 			buf = alloc;
1360 			if(IncFg == 1) {
1361 				IncFg = 0;
1362 				read_bytes = read_bytes_buf;
1363 			} else if(firstbufFg != 1) {
1364 				read_bytes = http_read_socket(socket, buf, BUF_SIZE);
1365 				if(read_bytes == 0){
1366 					break; // Read end
1367 				}
1368 				if(read_bytes < 0){
1369 					//OtaImgSize = -1;
1370 					printf("\n\r[%s] Read socket failed", __FUNCTION__);
1371 					res = _FALSE;
1372 					goto exit;
1373 				}
1374 				read_bytes_buf = read_bytes;
1375 				TempLen += read_bytes;
1376 			}
1377 
1378 			if(TempLen > DownloadInfo[i].ImgOffset) {
1379 				if(!OtaFg) {
1380 					/*reach the desired image, the first packet process*/
1381 					OtaFg = 1;
1382 					TempCnt = TempLen -DownloadInfo[i].ImgOffset;
1383 					if(TempCnt < 8) {
1384 						SigCnt = TempCnt;
1385 					} else {
1386 						SigCnt = 8;
1387 					}
1388 
1389 					if (firstbufFg == 1)
1390 						_memcpy(signature, first_buf + DownloadInfo[i].ImgOffset, SigCnt);
1391 					else
1392 						_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
1393 
1394 					if((SigCnt < 8) || (TempCnt -8 == 0)) {
1395 						if (firstbufFg == 1) {
1396 							firstbufFg = 0;
1397 						}
1398 						continue;
1399 					}
1400 					if (firstbufFg == 1) {
1401 						buf = first_buf + DownloadInfo[i].ImgOffset + 8;
1402 						firstbufFg = 0;
1403 					} else
1404 						buf = buf + (read_bytes -TempCnt + 8);
1405 					read_bytes = TempCnt -8;
1406 				} else {
1407 					/*normal packet process*/
1408 					if(SigCnt < 8) {
1409 						if(read_bytes < (int)(8 -SigCnt)) {
1410 							_memcpy(signature + SigCnt, buf, read_bytes);
1411 							SigCnt += read_bytes;
1412 							continue;
1413 						} else {
1414 							_memcpy(signature + SigCnt, buf, (8 -SigCnt));
1415 							buf = buf + (8 - SigCnt);
1416 							read_bytes -= (8 - SigCnt) ;
1417 							SigCnt = 8;
1418 							if(!read_bytes) {
1419 								continue;
1420 							}
1421 						}
1422 					}
1423 				}
1424 
1425 				RemainBytes -= read_bytes;
1426 				if(RemainBytes < 0) {
1427 					read_bytes = read_bytes -(-RemainBytes);
1428 				}
1429 #if 1
1430 				/* erase flash */
1431 				write_sector = (DownloadInfo[i].ImageLen - RemainBytes-1+8)/4096;
1432 				if (write_sector >= next_erase_sector){
1433 					//DBG_8195A("E1\n");
1434 					device_mutex_lock(RT_DEV_LOCK_FLASH);
1435 					//DelayMs(30);
1436 					FLASH_EraseXIP(EraseSector, pOtaTgtHdr->FileImgHdr[i].FlashAddr -SPI_FLASH_BASE + write_sector * 4096);
1437 					device_mutex_unlock(RT_DEV_LOCK_FLASH);
1438 					next_erase_sector++;
1439 					//DBG_8195A("E2\n");
1440 				}
1441 				//DBG_8195A("E3\n");
1442 
1443 				device_mutex_lock(RT_DEV_LOCK_FLASH);
1444 				if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
1445 					printf("\n\r[%s] Write sector failed", __FUNCTION__);
1446 					device_mutex_unlock(RT_DEV_LOCK_FLASH);
1447 					res = _FALSE;
1448 					goto exit;
1449 				}
1450 				//DelayMs(2);
1451 				device_mutex_unlock(RT_DEV_LOCK_FLASH);
1452 
1453 #endif
1454 				//DBG_8195A("E4\n");
1455 				size += read_bytes;
1456 			}
1457 		}
1458 
1459 		printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
1460 		if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
1461 			printf("\n\rdownload new firmware failed\n");
1462 			goto exit;
1463 		}
1464 
1465 		/*update flag status*/
1466 		size = 0;
1467 		OtaFg = 0;
1468 		IncFg = 1;
1469 		next_erase_sector = 0;
1470 	}
1471 
1472 exit:
1473 	ota_update_free(alloc);
1474 
1475 	return res;
1476 }
1477 
1478 /**
1479   * @brief	 OTA update through http
1480   * @param     host: host addr of http server
1481   * @param     port: http server port
1482   * @param     resource: resource path
1483   * @retval      -1:fail;0:success
1484   */
1485 
1486 int http_update_ota(char *host, int port, char *resource)
1487 {
1488 	int server_socket = -1;
1489 	unsigned char *alloc=NULL, *request=NULL;
1490 	int alloc_buf_size = BUF_SIZE;
1491 	int read_bytes = 0;
1492 	int ret = -1;
1493 	int writelen = 0;
1494 	u32 RevHdrLen = 0;
1495 	http_response_result_t rsp_result = {0};
1496 	uint32_t ota_target_index = OTA_INDEX_2;
1497 	update_ota_target_hdr OtaTargetHdr;
1498 
1499 restart_http_ota:
1500 	redirect_server_port = 0;
1501 
1502 	alloc = (unsigned char *)ota_update_malloc(alloc_buf_size);
1503 	if(!alloc){
1504 		printf("[%s] Alloc buffer failed\n", __FUNCTION__);
1505 		goto update_ota_exit;
1506 	}
1507 
1508 	/*Connect server */
1509 	server_socket = update_ota_http_connect_server(server_socket, host, port);
1510 	if(server_socket == -1){
1511 		goto update_ota_exit;
1512 	}
1513 		uint32_t idx = 0;
1514 		printf("\n\r");
1515 
1516 		/*send http request*/
1517 		request = (unsigned char *) ota_update_malloc(strlen("GET /") + strlen(resource) + strlen(" HTTP/1.1\r\nHost: ")
1518 			+ strlen(host) + strlen("\r\n\r\n") + 1);
1519 		sprintf((char*)request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", resource, host);
1520 
1521 		ret = write(server_socket, request, strlen((char*)request));
1522 		if(ret < 0){
1523 			printf("[%s] Send HTTP request failed\n", __FUNCTION__);
1524 			goto update_ota_exit;
1525 		}
1526 
1527 		/* parse http response*/
1528 		while (3 >= rsp_result.parse_status){//still read header
1529 			if(0 == rsp_result.parse_status){//didn't get the http response
1530 				memset(alloc, 0, alloc_buf_size);
1531 				read_bytes = read(server_socket, alloc, alloc_buf_size);
1532 				if(read_bytes <= 0){
1533 					printf("[%s] Read socket failed\n", __FUNCTION__);
1534 					goto update_ota_exit;
1535 				}
1536 				idx = read_bytes;
1537 				memset(&rsp_result, 0, sizeof(rsp_result));
1538 				if(parse_http_response(alloc, idx, &rsp_result) == -1){
1539 					goto update_ota_exit;
1540 				}
1541 			} else if ((1 == rsp_result.parse_status) || (3 == rsp_result.parse_status)){//just get the status code
1542 				memset(alloc, 0, alloc_buf_size);
1543 				memcpy(alloc, rsp_result.header_bak, HEADER_BAK_LEN);
1544 				ota_update_free(rsp_result.header_bak);
1545 				rsp_result.header_bak = NULL;
1546 				read_bytes = read(server_socket, alloc + HEADER_BAK_LEN, (alloc_buf_size - HEADER_BAK_LEN));
1547 				if(read_bytes <= 0){
1548 					printf("[%s] Read socket failed\n", __FUNCTION__);
1549 					goto update_ota_exit;
1550 				}
1551 				idx = read_bytes + HEADER_BAK_LEN;
1552 				if (parse_http_response(alloc, read_bytes + HEADER_BAK_LEN, &rsp_result) == -1){
1553 					goto update_ota_exit;
1554 				}
1555 			}
1556 		}
1557 
1558 	if (0 == rsp_result.body_len) {
1559 		printf("[%s] New firmware size = 0 !\n", __FUNCTION__);
1560 		goto update_ota_exit;
1561 	} else {
1562 		printf("[%s] Download new firmware begin, total size : %d\n", __FUNCTION__, rsp_result.body_len);
1563 	}
1564 
1565 	writelen = idx - rsp_result.header_len;
1566 	/* remove http header_len from alloc*/
1567 	memset(alloc, 0, rsp_result.header_len);
1568 	_memcpy(alloc, alloc+rsp_result.header_len, writelen);
1569 	memset(alloc+writelen, 0, rsp_result.header_len);
1570 
1571 	/* check OTA index we should update */
1572 	if (ota_get_cur_index() == OTA_INDEX_1) {
1573 		ota_target_index = OTA_INDEX_2;
1574 		printf("\n\r[%s] OTA2 address space will be upgraded\n", __FUNCTION__);
1575 
1576 	} else {
1577 		ota_target_index = OTA_INDEX_1;
1578 		printf("\n\r[%s] OTA1 address space will be upgraded\n", __FUNCTION__);
1579 	}
1580 
1581 	/*----------------step2: receive firmware file header---------------------*/
1582 	if(!recv_ota_file_hdr_http(alloc, writelen, &RevHdrLen, &OtaTargetHdr, server_socket)) {
1583 		printf("\n\r[%s] rev firmware header failed", __FUNCTION__);
1584 		goto update_ota_exit;
1585 	}
1586 
1587 	/* -----step3: parse firmware file header and get the target OTA image header-----*/
1588 	if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
1589 		printf("\n\rget OTA header failed\n");
1590 		goto update_ota_exit;
1591 	}
1592 
1593 	/* the upgrade space should be masked */
1594 	//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
1595 
1596 	/*-------------------step4: erase flash space for new firmware--------------*/
1597 	/*erase flash space new OTA image */
1598 	//printf("\n\rErase is ongoing...");
1599 	//for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
1600 	//	erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
1601 	//}
1602 
1603 	/*---------step5: download new firmware from server and write it to flash--------*/
1604 	if(download_new_fw_from_server_http(alloc, writelen, server_socket, &OtaTargetHdr, ota_target_index) == _FALSE){
1605 		goto update_ota_exit;
1606 	}
1607 
1608 	 /*-------------step6: verify checksum and update signature-----------------*/
1609 	if(verify_ota_checksum(&OtaTargetHdr)){
1610 		//if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
1611 			//printf("\n\rChange signature failed\n");
1612 			//goto update_ota_exit;
1613 		//}
1614 		//ret = 0;
1615 	}
1616 
1617 update_ota_exit:
1618 	if(alloc)
1619 		ota_update_free(alloc);
1620 	if(request)
1621 		ota_update_free(request);
1622 	if(server_socket >= 0)
1623 		close(server_socket);
1624 
1625 	/* redirect_server_port != 0 means there is redirect URL can be downloaded*/
1626 	if(redirect_server_port != 0){
1627 		host = redirect_server_host;
1628 		resource = redirect_resource;
1629 		port = redirect_server_port;
1630 		printf("OTA redirect host: %s, port: %s, resource: %s\n\r", host, port, resource);
1631 		goto restart_http_ota;
1632 	}
1633 
1634 	ota_update_free(redirect);
1635 	ota_update_free(redirect_server_host);
1636 	ota_update_free(redirect_resource);
1637 
1638 	return ret;
1639 }
1640 #endif
1641 
1642 #ifdef HTTPS_OTA_UPDATE
1643 
1644 static int my_random(void *p_rng, unsigned char *output, size_t output_len)
1645 {
1646 	( void ) p_rng;
1647 	rtw_get_random_bytes(output, output_len);
1648 	return 0;
1649 }
1650 
1651 static void* my_calloc(size_t nelements, size_t elementSize)
1652 {
1653 	size_t size;
1654 	void *ptr = NULL;
1655 
1656 	size = nelements * elementSize;
1657 	ptr = pvPortMalloc(size);
1658 
1659 	if(ptr)
1660 		memset(ptr, 0, size);
1661 
1662 	return ptr;
1663 }
1664 
1665 
1666 static char *https_itoa(int value){
1667 	char *val_str;
1668 	int tmp = value, len = 1;
1669 
1670 	while((tmp /= 10) > 0)
1671 		len ++;
1672 
1673 	val_str = (char *) pvPortMalloc(len + 1);
1674 	sprintf(val_str, "%d", value);
1675 
1676 	return val_str;
1677 }
1678 
1679 
1680   /**
1681   * @brief  receive OTA firmware file header from server
1682   * @param  Recvbuf: pointer to buffer for receiving OTA header of firmware file
1683   * @param  writelen:the length already read from server
1684   * @param  len: data length to be received from server
1685   * @param  pOtaTgtHdr: point to target image OTA  header
1686   * @param  ssl: context for mbedtls
1687   * @retval  0:failed;1:success
1688   */
1689 u32 recv_ota_file_hdr_https(u8 * Recvbuf, u32 writelen, u32 * len, update_ota_target_hdr * pOtaTgtHdr, mbedtls_ssl_context *ssl)
1690 {
1691 	int read_bytes = 0;
1692 	u32 TempLen;
1693 	u8 * buf;
1694 	update_file_hdr * pOtaFileHdr;
1695 	update_file_img_hdr * pOtaFileImgHdr;
1696 
1697 	buf = Recvbuf + writelen;
1698 	/*receive the remaining OTA firmware file header info if needed*/
1699 	if (writelen < 32) {
1700 		TempLen = 32 - writelen;
1701 		while(TempLen) {
1702 			read_bytes = mbedtls_ssl_read(ssl, buf, TempLen);
1703 			if(read_bytes < 0){
1704 				printf("[%s] read socket failed [%d]\n", __FUNCTION__, read_bytes);
1705 				goto error;
1706 			}
1707 			if(read_bytes == 0) {
1708 				break;
1709 			}
1710 			TempLen -= read_bytes;
1711 			buf += read_bytes;
1712 		}
1713 	}
1714 
1715 	pOtaFileHdr = (update_file_hdr *)(Recvbuf);
1716 	pOtaFileImgHdr = (update_file_img_hdr *)(Recvbuf + 8);
1717 
1718 	pOtaTgtHdr->FileHdr.FwVer = pOtaFileHdr->FwVer;
1719 	pOtaTgtHdr->FileHdr.HdrNum = pOtaFileHdr->HdrNum;
1720 
1721 	*len = (pOtaFileHdr->HdrNum * pOtaFileImgHdr->ImgHdrLen) + 8;
1722 
1723 	return 1;
1724 error:
1725 	return 0;
1726 }
1727 
1728 
1729   /**
1730   * @brief  https read socket
1731   * @param  Recvbuf: pointer to buffer for receiving
1732   * @param  ssl: context for mbedtls
1733   * @param  buf_len: read data length
1734   * @retval  >0:success;<0:error
1735   */
1736 int https_read_socket( mbedtls_ssl_context *ssl, u8 *recevie_buf, int buf_len )
1737 {
1738 	int bytes_rcvd = -1;
1739 
1740 	memset(recevie_buf, 0, buf_len);
1741 
1742 	bytes_rcvd = mbedtls_ssl_read(ssl, recevie_buf, buf_len );
1743 
1744 	if(bytes_rcvd <= 0) {
1745 		printf("[%s], ssl read failed [%d]\n",  __FUNCTION__, bytes_rcvd);
1746 		return -2;
1747 	}
1748 	return bytes_rcvd;
1749 }
1750 
1751 
1752 
1753 /**
1754   * @brief	  download new firmware from https server and write it to flash.
1755   * @param     first_buf: point data already from https server
1756   * @param     firstbuf_len: the length of already read data
1757   * @param     ssl: context for mbedtls
1758   * @param     pOtaTgtHdr: point to target image OTA  header
1759   * @param     targetIdx: target OTA index
1760   * @retval   	download size of OTA image
1761   */
1762 u32 download_new_fw_from_server_https(u8* first_buf, unsigned int firstbuf_len, mbedtls_ssl_context *ssl, update_ota_target_hdr * pOtaTgtHdr, u8 targetIdx)
1763 {
1764 	/* To avoid gcc warnings */
1765 	( void ) targetIdx;
1766 
1767 	u8 * alloc;
1768 	u8 * buf;
1769 	s32 size = 0;
1770 	int read_bytes;
1771 	int read_bytes_buf;
1772 	u32 TempLen;
1773 	u32 ImageCnt;
1774 	update_dw_info DownloadInfo[MAX_IMG_NUM];
1775 	/*initialize the variables used in downloading procedure*/
1776 	u32 OtaFg = 0;
1777 	u32 IncFg = 0;
1778 	u32 firstbufFg = 0;
1779 	s32 RemainBytes;
1780 	u32 SigCnt = 0;
1781 	u32 TempCnt = 0;
1782 	u32 i;
1783 	u8 res = _TRUE;
1784 	u8 * signature;
1785 	u32 write_sector = 0;
1786 	u32 next_erase_sector = 0;
1787 
1788 	/*acllocate buffer for downloading image from server*/
1789 	alloc = ota_update_malloc(BUF_SIZE);
1790 
1791 	buf = alloc;
1792 
1793 	/*init download information buffer*/
1794 	memset((u8 *)DownloadInfo, 0, MAX_IMG_NUM*sizeof(update_dw_info));
1795 
1796 	ImageCnt = pOtaTgtHdr->ValidImgCnt;
1797 	for(i = 0; i < ImageCnt; i++) {
1798 		/* get OTA image and Write New Image to flash, skip the signature,
1799 			not write signature first for power down protection*/
1800 		DownloadInfo[i].ImgId = OTA_IMAG;
1801 		DownloadInfo[i].FlashAddr = pOtaTgtHdr->FileImgHdr[i].FlashAddr - SPI_FLASH_BASE + 8;
1802 		DownloadInfo[i].ImageLen = pOtaTgtHdr->FileImgHdr[i].ImgLen - 8; /*skip the signature*/
1803 		DownloadInfo[i].ImgOffset = pOtaTgtHdr->FileImgHdr[i].Offset;
1804 	}
1805 
1806 	/*initialize the reveiving counter*/
1807 	TempLen = (pOtaTgtHdr->FileHdr.HdrNum * pOtaTgtHdr->FileImgHdr[0].ImgHdrLen) + sizeof(update_file_hdr);
1808 
1809 	/*downloading parse the OTA and RDP image from the data stream sent by server*/
1810 	for(i = 0; i < ImageCnt; i++) {
1811 
1812 		/*the next image length*/
1813 		RemainBytes = DownloadInfo[i].ImageLen;
1814 		signature = &pOtaTgtHdr->Sign[i][0];
1815 
1816 		if (i == 0) {
1817 			if (firstbuf_len > DownloadInfo[i].ImgOffset) {
1818 				firstbufFg = 1;
1819 				TempLen += firstbuf_len -DownloadInfo[i].ImgOffset;
1820 			}
1821 		}
1822 
1823 		/*download the new firmware from server*/
1824 		while(RemainBytes > 0){
1825 			buf = alloc;
1826 			if(IncFg == 1) {
1827 				IncFg = 0;
1828 				read_bytes = read_bytes_buf;
1829 			} else if(firstbufFg != 1) {
1830 				read_bytes = https_read_socket(ssl, buf, BUF_SIZE);
1831 				if(read_bytes == 0){
1832 					break; // Read end
1833 				}
1834 				if(read_bytes < 0){
1835 					//OtaImgSize = -1;
1836 					printf("\n\r[%s] Read socket failed", __FUNCTION__);
1837 					res = _FALSE;
1838 					goto exit;
1839 				}
1840 				read_bytes_buf = read_bytes;
1841 				TempLen += read_bytes;
1842 			}
1843 
1844 			if(TempLen > DownloadInfo[i].ImgOffset) {
1845 				if(!OtaFg) {
1846 					/*reach the desired image, the first packet process*/
1847 					OtaFg = 1;
1848 					TempCnt = TempLen -DownloadInfo[i].ImgOffset;
1849 					if(TempCnt < 8) {
1850 						SigCnt = TempCnt;
1851 					} else {
1852 						SigCnt = 8;
1853 					}
1854 
1855 					if (firstbufFg == 1)
1856 						_memcpy(signature, first_buf + DownloadInfo[i].ImgOffset, SigCnt);
1857 					else
1858 						_memcpy(signature, buf + read_bytes -TempCnt, SigCnt);
1859 
1860 					if((SigCnt < 8) || (TempCnt -8 == 0)) {
1861 						if (firstbufFg == 1) {
1862 							firstbufFg = 0;
1863 						}
1864 						continue;
1865 					}
1866 					if (firstbufFg == 1) {
1867 						buf = first_buf + DownloadInfo[i].ImgOffset + 8;
1868 						firstbufFg = 0;
1869 					} else
1870 						buf = buf + (read_bytes -TempCnt + 8);
1871 					read_bytes = TempCnt -8;
1872 				} else {
1873 					/*normal packet process*/
1874 					if(SigCnt < 8) {
1875 						if(read_bytes < (int)(8 -SigCnt)) {
1876 							_memcpy(signature + SigCnt, buf, read_bytes);
1877 							SigCnt += read_bytes;
1878 							continue;
1879 						} else {
1880 							_memcpy(signature + SigCnt, buf, (8 -SigCnt));
1881 							buf = buf + (8 - SigCnt);
1882 							read_bytes -= (8 - SigCnt) ;
1883 							SigCnt = 8;
1884 							if(!read_bytes) {
1885 								continue;
1886 							}
1887 						}
1888 					}
1889 				}
1890 
1891 				RemainBytes -= read_bytes;
1892 				if(RemainBytes < 0) {
1893 					read_bytes = read_bytes -(-RemainBytes);
1894 				}
1895 
1896 				/* erase flash */
1897 				write_sector = (DownloadInfo[i].ImageLen - RemainBytes-1+8)/4096;
1898 				if (write_sector >= next_erase_sector){
1899 					device_mutex_lock(RT_DEV_LOCK_FLASH);
1900 					FLASH_EraseXIP(EraseSector, pOtaTgtHdr->FileImgHdr[i].FlashAddr -SPI_FLASH_BASE + write_sector * 4096);
1901 					device_mutex_unlock(RT_DEV_LOCK_FLASH);
1902 					next_erase_sector++;
1903 				}
1904 
1905 				device_mutex_lock(RT_DEV_LOCK_FLASH);
1906 				if(ota_writestream_user(DownloadInfo[i].FlashAddr + size, read_bytes, buf) < 0){
1907 					printf("\n\r[%s] Write sector failed", __FUNCTION__);
1908 					device_mutex_unlock(RT_DEV_LOCK_FLASH);
1909 					res = _FALSE;
1910 					goto exit;
1911 				}
1912 				device_mutex_unlock(RT_DEV_LOCK_FLASH);
1913 				size += read_bytes;
1914 			}
1915 		}
1916 
1917 		printf("\n\rUpdate file size: %d bytes, start addr:%08x", size + 8, pOtaTgtHdr->FileImgHdr[i].FlashAddr);
1918 		if((u32)size != (pOtaTgtHdr->FileImgHdr[i].ImgLen - 8)) {
1919 			printf("\n\rdownload new firmware failed\n");
1920 			goto exit;
1921 		}
1922 
1923 		/*update flag status*/
1924 		size = 0;
1925 		OtaFg = 0;
1926 		IncFg = 1;
1927 		next_erase_sector = 0;
1928 	}
1929 
1930 exit:
1931 	ota_update_free(alloc);
1932 
1933 	return res;
1934 }
1935 
1936 
1937 
1938 /**
1939   * @brief	 OTA update through https
1940   * @param     host: host addr of https server
1941   * @param     port: https server port
1942   * @param     resource: resource path
1943   * @retval      -1:fail;0:success
1944   */
1945 int https_update_ota(char *host, int port, char *resource)
1946 {
1947 	unsigned char *alloc=NULL, *request=NULL;
1948 	int alloc_buf_size = BUF_SIZE;
1949 	int read_bytes = 0;
1950 	int ret = -1;
1951 	int writelen = 0;
1952 	u32 RevHdrLen = 0;
1953 	http_response_result_t rsp_result = {0};
1954 	uint32_t ota_target_index = OTA_INDEX_2;
1955 	update_ota_target_hdr OtaTargetHdr;
1956 
1957 	mbedtls_net_context server_fd;
1958 	mbedtls_ssl_context ssl;
1959 	mbedtls_ssl_config conf;
1960 
1961 restart_https_ota:
1962 	redirect_server_port = 0;
1963 
1964 	alloc = (unsigned char *)ota_update_malloc(alloc_buf_size);
1965 	if(!alloc){
1966 		printf("[%s] Alloc buffer failed\n", __FUNCTION__);
1967 		goto update_ota_exit;
1968 	}
1969 
1970 	/*connect https server*/
1971 	mbedtls_platform_set_calloc_free(my_calloc, vPortFree);
1972 
1973 	mbedtls_net_init(&server_fd);
1974 	mbedtls_ssl_init(&ssl);
1975 	mbedtls_ssl_config_init(&conf);
1976 
1977 	char *port_str = https_itoa (port);
1978 	if((ret = mbedtls_net_connect(&server_fd, host, port_str, MBEDTLS_NET_PROTO_TCP)) != 0) {
1979 		printf("ERROR: mbedtls_net_connect ret(%d)\n", ret);
1980 		goto update_ota_exit;
1981 	}
1982 
1983 	mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
1984 	if((ret = mbedtls_ssl_config_defaults(&conf,
1985 			MBEDTLS_SSL_IS_CLIENT,
1986 			MBEDTLS_SSL_TRANSPORT_STREAM,
1987 			MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1988 
1989 		printf("ERRPR: mbedtls_ssl_config_defaults ret(%d)\n", ret);
1990 		goto update_ota_exit;
1991 	}
1992 
1993 	mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE);
1994 	mbedtls_ssl_conf_rng(&conf, my_random, NULL);
1995 
1996 	if((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
1997 		printf("ERRPR: mbedtls_ssl_setup ret(%d)\n", ret);
1998 		goto update_ota_exit;
1999 	}
2000 
2001 	if((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
2002 		printf("ERROR: mbedtls_ssl_handshake ret(-0x%x)", -ret);
2003 		goto update_ota_exit;
2004 	}
2005 
2006 	printf("SSL ciphersuite %s\n", mbedtls_ssl_get_ciphersuite(&ssl));
2007 
2008 	/*send https request*/
2009 	uint32_t idx = 0;
2010 	request = (unsigned char *) ota_update_malloc(strlen("GET /") + strlen(resource) + strlen(" HTTP/1.1\r\nHost: ")
2011 		+ strlen(host) + strlen("\r\n\r\n") + 1);
2012 	sprintf((char*)request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", resource, host);
2013 	ret = mbedtls_ssl_write(&ssl, request, strlen((char*)request));
2014 	if(ret < 0){
2015 		printf("[%s] Send HTTPS request failed\n", __FUNCTION__);
2016 		goto update_ota_exit;
2017 	}
2018 
2019 	/* parse https response*/
2020 	while (3 >= rsp_result.parse_status){//still read header
2021 		if(0 == rsp_result.parse_status){//didn't get the http response
2022 			memset(alloc, 0, alloc_buf_size);
2023 			read_bytes = mbedtls_ssl_read(&ssl, alloc, alloc_buf_size);
2024 			if(read_bytes <= 0){
2025 				printf("[%s] Read socket failed\n", __FUNCTION__);
2026 				goto update_ota_exit;
2027 			}
2028 			idx = read_bytes;
2029 			memset(&rsp_result, 0, sizeof(rsp_result));
2030 			if(parse_http_response(alloc, idx, &rsp_result) == -1){
2031 				goto update_ota_exit;
2032 			}
2033 		} else if ((1 == rsp_result.parse_status) || (3 == rsp_result.parse_status)){//just get the status code
2034 			memset(alloc, 0, alloc_buf_size);
2035 			memcpy(alloc, rsp_result.header_bak, HEADER_BAK_LEN);
2036 			ota_update_free(rsp_result.header_bak);
2037 			rsp_result.header_bak = NULL;
2038 			read_bytes = mbedtls_ssl_read(&ssl, alloc + HEADER_BAK_LEN, (alloc_buf_size - HEADER_BAK_LEN));
2039 			if(read_bytes <= 0){
2040 				printf("[%s] Read socket failed\n", __FUNCTION__);
2041 				goto update_ota_exit;
2042 			}
2043 			idx = read_bytes + HEADER_BAK_LEN;
2044 			if (parse_http_response(alloc, read_bytes + HEADER_BAK_LEN, &rsp_result) == -1){
2045 				goto update_ota_exit;
2046 			}
2047 		}
2048 	}
2049 
2050 	if (0 == rsp_result.body_len) {
2051 		printf("[%s] New firmware size = 0 !\n", __FUNCTION__);
2052 		goto update_ota_exit;
2053 	} else {
2054 		printf("[%s] Download new firmware begin, total size : %d\n", __FUNCTION__, rsp_result.body_len);
2055 	}
2056 
2057 	writelen = idx - rsp_result.header_len;
2058 	/* remove https header_len from alloc*/
2059 	memset(alloc, 0, rsp_result.header_len);
2060 	_memcpy(alloc, alloc+rsp_result.header_len, writelen);
2061 	memset(alloc+writelen, 0, rsp_result.header_len);
2062 
2063 	/* check OTA index we should update */
2064 	if (ota_get_cur_index() == OTA_INDEX_1) {
2065 		ota_target_index = OTA_INDEX_2;
2066 		printf("\n\r[%s] OTA2 address space will be upgraded \n", __FUNCTION__);
2067 
2068 	} else {
2069 		ota_target_index = OTA_INDEX_1;
2070 		printf("\n\r[%s] OTA1 address space will be upgraded \n", __FUNCTION__);
2071 	}
2072 
2073 	/*----------------step2: receive firmware file header---------------------*/
2074 	if(!recv_ota_file_hdr_https(alloc, writelen, &RevHdrLen, &OtaTargetHdr, &ssl)) {
2075 		printf("\n\r[%s] recv firmware header failed", __FUNCTION__);
2076 		goto update_ota_exit;
2077 	}
2078 
2079 	/* -----step3: parse firmware file header and get the target OTA image header-----*/
2080 	if(!get_ota_tartget_header(alloc, RevHdrLen, &OtaTargetHdr, ota_target_index)) {
2081 		printf("\n\rget OTA header failed\n");
2082 		goto update_ota_exit;
2083 	}
2084 
2085 	/* the upgrade space should be masked */
2086 	//ota_rsip_mask(NewImg2Addr, OtaTargetHdr.FileImgHdr.ImgLen, ENABLE);
2087 
2088 	/*-------------------step4: erase flash space for new firmware--------------*/
2089 	/*erase flash space new OTA image */
2090 	//printf("\n\rErase is ongoing...");
2091 	//for(i = 0; i < OtaTargetHdr.ValidImgCnt; i++) {
2092 	//	erase_ota_target_flash(OtaTargetHdr.FileImgHdr[i].FlashAddr, OtaTargetHdr.FileImgHdr[i].ImgLen);
2093 	//}
2094 
2095 	/*---------step5: download new firmware from server and write it to flash--------*/
2096 	if(download_new_fw_from_server_https(alloc, writelen, &ssl, &OtaTargetHdr, ota_target_index) == _FALSE){
2097 		goto update_ota_exit;
2098 	}
2099 
2100 	 /*-------------step6: verify checksum and update signature-----------------*/
2101 	if(verify_ota_checksum(&OtaTargetHdr)){
2102 		if(!change_ota_signature(&OtaTargetHdr, ota_target_index)) {
2103 			printf("\n\rChange signature failed\n");
2104 			goto update_ota_exit;
2105 		}
2106 		ret = 0;
2107 	}
2108 
2109 update_ota_exit:
2110 	if(alloc)
2111 		ota_update_free(alloc);
2112 	if(request)
2113 		ota_update_free(request);
2114 
2115 	mbedtls_net_free(&server_fd);
2116 	mbedtls_ssl_free(&ssl);
2117 	mbedtls_ssl_config_free(&conf);
2118 
2119 	/* redirect_server_port != 0 means there is redirect URL can be downloaded*/
2120 	if(redirect_server_port != 0){
2121 		host = redirect_server_host;
2122 		resource = redirect_resource;
2123 		port = redirect_server_port;
2124 		printf("OTA redirect host: %s, port: %d, resource: %s\n\r", host, port, resource);
2125 		goto restart_https_ota;
2126 	}
2127 
2128 	ota_update_free(redirect);
2129 	ota_update_free(redirect_server_host);
2130 	ota_update_free(redirect_resource);
2131 
2132 	return ret;
2133 }
2134 
2135 #endif
2136 #endif
2137 #endif
2138