httpserver.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. #include "httpserver.h"
  2. #include "lwip/def.h"
  3. #include "lwip/tcp.h"
  4. #include "fsdata.c"
  5. #include "main.h"
  6. #include "flash_if.h"
  7. #include "common_config.h"
  8. #include "conf.h"
  9. #include "settings_api.h"
  10. #include "crc.h"
  11. #include "board.h"
  12. #include "netconf.h"
  13. #ifdef SLAVEBRD_ENABLE
  14. #include "stm32sprog.h"
  15. #endif
  16. #ifdef LCD_ENABLE
  17. #include "lcd.h"
  18. #endif
  19. #include "led.h"
  20. #include "systick.h"
  21. #include <string.h>
  22. #include "tinystdio.h"
  23. #undef DBG
  24. #define DBG if(0)
  25. /* Uncomment this macro to compleately skip any flash read/write operations/
  26. USE THIS ONLY FOR DEBUG AND TESTING PURPOSES!
  27. NEVER UNKOMMENT FOR RELEASE BUILDS! */
  28. // #define DUMMY_PROG
  29. #ifdef DUMMY_PROG
  30. /* Disable main fw flash read/write operations */
  31. #define FLASH_If_Write(X, ...)
  32. #define FLASH_If_Erase(X, ...)
  33. #define CRC_Read() 0x00
  34. #define CRC_Calculate(X, ...) 0x00
  35. /* Disable daughter fw flash read/write operations */
  36. #define stmProg(X, ...)
  37. #define stmRebootForFlash(X, ...)
  38. #define stmConnect(X, ...) ok
  39. #define stmGetDevParams(X, ...) ok
  40. #define stmEraseFW(X, ...) ok
  41. #define stmReadFlashCrc() 0x00
  42. #define stmCalcFlashCrc(X, ...) 0x00
  43. #endif /* DUMMY_PROG*/
  44. #define FILENAME_MAX_LEN 30
  45. #define BOUNDARY_MAX_LEN 70
  46. #define BLOCK_PROG_TIMEOUT 20000
  47. #define COOKIES_MAX_LEN 64
  48. #define COOKIES_SET_ATTEMPTS 2
  49. #define BD_CONNECT_RETRY 3
  50. /* Max HTTP file name length including "/" */
  51. #define HTTP_FNAME_LEN 32
  52. /* Max HTTP Etag field length */
  53. #define MAX_ETAG_LEN 48
  54. #define DB_FW_SIZE DB_CPU_FLASH_END_ADDRESS - DB_CPU_FLASH_FIRST_PAGE_ADDRESS + 1
  55. #define HTTP_RET_UPLOAD_ERROR() do {\
  56. memset(sendBuf, 0, 32);\
  57. strcpy(sendBuf, HTTP_200_OK);\
  58. strcat(sendBuf, "0");\
  59. hs->file = sendBuf;\
  60. hs->left = strlen(sendBuf);\
  61. send_data(pcb, hs);\
  62. tcp_sent(pcb, http_sent);\
  63. htmlpage = UploadErrorPage;\
  64. SET_FWINVALID_FLAG();\
  65. } while(0)
  66. #define HTTP_RET_UPLOAD_ERROR_NO_FLASH_ERASE() do {\
  67. memset(sendBuf, 0, 32);\
  68. strcpy(sendBuf, HTTP_200_OK);\
  69. strcat(sendBuf, "0");\
  70. hs->file = sendBuf;\
  71. hs->left = strlen(sendBuf);\
  72. send_data(pcb, hs);\
  73. tcp_sent(pcb, http_sent);\
  74. htmlpage = UploadErrorPage;\
  75. } while(0)
  76. static char sendBuf[512];
  77. static char tempBuf[HW_REV_OFFSET + HW_REV_LEN];
  78. extern bool fDoneReset;
  79. extern bool fUpload;
  80. extern bool fInvalidFw;
  81. char lcdbuf[32] = {0};
  82. static vu32 DataFlag = 0;
  83. static vu32 BoundaryFlag = 0;
  84. static vu32 size = 0;
  85. static __IO uint32_t FlashWriteAddress;
  86. static u32 TotalReceived = 0;
  87. static char LeftBytesTab[4];
  88. static u8 LeftBytes = 0;
  89. static uint32_t BrowserFlag = 0;
  90. static uint32_t ContentOffset = 0;
  91. static __IO uint32_t TotalData = 0;
  92. static uint32_t FwDestSize = 0;
  93. static bool fEraseFlash = true;
  94. uint8_t update_timeout = UPDATE_TIMEOUT;
  95. struct http_state
  96. {
  97. char *file;
  98. u32_t left;
  99. };
  100. typedef enum {
  101. fw_unknown,
  102. fw_main_board,
  103. fw_daughter_board
  104. } fw_type_t;
  105. static fw_type_t fw_type = fw_unknown;
  106. htmlpageState htmlpage;
  107. /* Content Length */
  108. static const char Content_Length[17] = {
  109. 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20,
  110. };
  111. static const char If_None_Match[] = "If-None-Match: ";
  112. static const char Etag[] = "ETag: ";
  113. const char HTTP_200_OK[] = "HTTP/1.1 200 OK\r\n\r\n";
  114. const char HTTP_304_NOT_MODIFIED[] = "HTTP/1.1 304 Not Modified\r\n\r\n";
  115. const char HTTP_200_OK_TEXT_HTML[] = "HTTP/1.1 200 OK\r\nContent-Type:text/html";
  116. const char Redirect_Head[] = "<!DOCTYPE html><html lang=""><head><meta charset=\"UTF-8\"><meta http-equiv=\"refresh\" ";
  117. const char Msg_Body[] = "<body style=\"background-color:#E8EBF1;\">\
  118. <p style=\"height:300px;line-height:300px;font-family:Arial,Helvetica,sans-serif;text-align:center;color:#333;\">";
  119. uint16_t printLen = 0;
  120. char printBuf[1500];
  121. uint32_t oldAdd = USER_FLASH_FIRST_PAGE_ADDRESS;
  122. uint32_t deltaAdd = 0;
  123. #ifdef SLAVEBRD_ENABLE
  124. uint32_t stm32addr = DB_CPU_FLASH_FIRST_PAGE_ADDRESS;
  125. static void IAP_HTTP_stmProg(char *data, uint32_t len);
  126. bool IAP_HTTP_stmConnect(void);
  127. #endif
  128. static uint32_t Parse_Content_Length(char *data, uint32_t len);
  129. void Parse_IfNonMatch(char *data, uint32_t len, char *value);
  130. static uint32_t Parse_Header(char *data, uint32_t len, const char *field, uint32_t flen, char *value);
  131. static bool Parse_Filename(const char *data, uint32_t len, fw_type_t *fw_type, uint32_t *fw_size);
  132. char *Parce_Boundary(const char *data, uint32_t len, char *dst, uint8_t dstlen);
  133. static void IAP_HTTP_writedata(char *data, uint32_t len);
  134. void ProgTimeout_Handler();
  135. /* file must be allocated by caller and will be filled in by the function. */
  136. static int fs_open(char *name, struct fs_file *file);
  137. bool send_file(char *filename, char *pnonmatch, struct tcp_pcb *pcb, struct http_state *hs, struct fs_file *file);
  138. void send_index_page(struct tcp_pcb *pcb, struct http_state *hs, struct pbuf *p, bool upload);
  139. static void PeriodicHandle(uint8_t progress);
  140. /* Get Cookie parameter value */
  141. bool GetCookieValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen);
  142. /* Check if Cookie is set or not */
  143. bool CookieIsSet(char *inStr, uint16_t inLen, char *paramName);
  144. // Implements the GNU function memmem much faster (2x) than the standard memmem
  145. char *memmemory(char *haystack, int hlen, char *needle, int nlen)
  146. {
  147. if (nlen > hlen) return 0;
  148. int i = 0, j = 0;
  149. switch (nlen) { // we have a few specialized compares for certain needle sizes
  150. case 0: // no needle? just give the haystack
  151. return haystack;
  152. case 1: // just use memchr for 1-byte needle
  153. return memchr(haystack, needle[0], hlen);
  154. case 2: // use 16-bit compares for 2-byte needles
  155. for (i = 0; i < hlen - nlen + 1; i++) {
  156. if (*(uint16_t *)(haystack + i) == *(uint16_t *)needle) {
  157. return haystack + i;
  158. }
  159. }
  160. break;
  161. case 4: // use 32-bit compares for 4-byte needles
  162. for (i = 0; i < hlen - nlen + 1; i++) {
  163. if (*(uint32_t *)(haystack + i) == *(uint32_t *)needle) {
  164. return haystack + i;
  165. }
  166. }
  167. break;
  168. /* actually slower on my 32-bit machine
  169. case 8: // use 64-bit compares for 8-byte needles
  170. for (i=0; i<hlen-nlen+1; i++) {
  171. if (*(uint64_t*)(haystack+i)==*(uint64_t*)needle) {
  172. return haystack+i;
  173. }
  174. }
  175. break;
  176. */
  177. default: // generic compare for any other needle size
  178. // walk i through the haystack, matching j as long as needle[j] matches haystack[i]
  179. for (i = 0; i < hlen; i++) {
  180. if (haystack[i] == needle[j]) {
  181. if (j == nlen - 1) { // end of needle and it all matched? win.
  182. return haystack + i - j;
  183. } else { // keep advancing j (and i, implicitly)
  184. j++;
  185. }
  186. } else { // no match, rewind i the length of the failed match (j), and reset j
  187. i -= j;
  188. j = 0;
  189. }
  190. }
  191. }
  192. return NULL;
  193. }
  194. /**
  195. * @brief callback function for handling connection errors
  196. * @param arg: pointer to an argument to be passed to callback function
  197. * @param err: LwIP error code
  198. * @retval none
  199. */
  200. static void conn_err(void *arg, err_t err)
  201. {
  202. struct http_state *hs;
  203. (void)err;
  204. hs = arg;
  205. mem_free(hs);
  206. }
  207. /**
  208. * @brief closes tcp connection
  209. * @param pcb: pointer to a tcp_pcb struct
  210. * @param hs: pointer to a http_state struct
  211. * @retval
  212. */
  213. static void close_conn(struct tcp_pcb *pcb, struct http_state *hs)
  214. {
  215. tcp_arg(pcb, NULL);
  216. tcp_sent(pcb, NULL);
  217. tcp_recv(pcb, NULL);
  218. mem_free(hs);
  219. tcp_close(pcb);
  220. }
  221. /**
  222. * @brief sends data found in member "file" of a http_state struct
  223. * @param pcb: pointer to a tcp_pcb struct
  224. * @param hs: pointer to a http_state struct
  225. * @retval none
  226. */
  227. static void send_data(struct tcp_pcb *pcb, struct http_state *hs)
  228. {
  229. err_t err;
  230. u16_t len;
  231. /* We cannot send more data than space available in the send
  232. buffer */
  233. if (tcp_sndbuf(pcb) < hs->left) {
  234. len = tcp_sndbuf(pcb);
  235. } else {
  236. len = hs->left;
  237. }
  238. err = tcp_write(pcb, hs->file, len, 0);
  239. if (err == ERR_OK) {
  240. hs->file += len;
  241. hs->left -= len;
  242. }
  243. }
  244. /**
  245. * @brief tcp poll callback function
  246. * @param arg: pointer to an argument to be passed to callback function
  247. * @param pcb: pointer on tcp_pcb structure
  248. * @retval err_t
  249. */
  250. static err_t http_poll(void *arg, struct tcp_pcb *pcb)
  251. {
  252. if (arg == NULL) {
  253. tcp_close(pcb);
  254. } else {
  255. send_data(pcb, (struct http_state *)arg);
  256. }
  257. return ERR_OK;
  258. }
  259. /**
  260. * @brief callback function called after a successfull TCP data packet transmission
  261. * @param arg: pointer to an argument to be passed to callback function
  262. * @param pcb: pointer on tcp_pcb structure
  263. * @param len
  264. * @retval err : LwIP error code
  265. */
  266. static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len)
  267. {
  268. struct http_state *hs;
  269. hs = arg;
  270. (void)len;
  271. if (hs->left > 0) {
  272. send_data(pcb, hs);
  273. } else {
  274. close_conn(pcb, hs);
  275. if (htmlpage == UploadDonePage) {
  276. #ifndef DUMMY_PROG
  277. fDoneReset = true;
  278. fUpload = false;
  279. #endif
  280. } else if (htmlpage == UploadErrorPage) {
  281. /* Don't reboot if update was failed, just reload main page */
  282. fUpload = false;
  283. }
  284. }
  285. return ERR_OK;
  286. }
  287. /**
  288. * @brief callback function for handling TCP HTTP traffic
  289. * @param arg: pointer to an argument structure to be passed to callback function
  290. * @param pcb: pointer to a tcp_pcb structure
  291. * @param p: pointer to a packet buffer
  292. * @param err: LwIP error code
  293. * @retval err
  294. */
  295. /* goback.cgi - возврат в основную прошивку */
  296. /* upload.cgi - загрузка новой прошивки */
  297. static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
  298. {
  299. int32_t i, len = 0;
  300. static uint32_t temp_len = 0;
  301. uint32_t DataOffset, CrcRead = 0, CrcCalc = 0;
  302. char *data, *ptr;
  303. struct fs_file file = {0, 0};
  304. struct http_state *hs;
  305. static bool hw_validated = false;
  306. char fname[HTTP_FNAME_LEN];
  307. uint8_t fname_len;
  308. static struct tcp_pcb *upload_pcb = NULL;
  309. static cookie_attempt = 0;
  310. hs = arg;
  311. if (err == ERR_OK && p != NULL) {
  312. /* Inform TCP that we have taken the data */
  313. tcp_recved(pcb, p->tot_len);
  314. if (hs->file == NULL) {
  315. data = p->payload;
  316. len = p->tot_len;
  317. printLen = p->tot_len > 500 ? 500 : p->tot_len;
  318. memcpy(printBuf, p->payload, printLen);
  319. // DBG printf("\r\n[%d] %s...\r\n", p->tot_len, printBuf);
  320. // DBG printf("pcb: %p (%p)\r\n", pcb, upload_pcb);
  321. /* process HTTP GET requests */
  322. if (strncmp(data, "GET /", 5) == 0 && pcb != upload_pcb) {
  323. /* Возврат в основную прошивку. Сбрасываем флаг loadmode,
  324. * сохраняем настройки и перезагружаемся */
  325. if (strncmp(data, "GET /goback.cgi", 15) == 0) {
  326. /* Check if we realy can go back. Return to IAP if fw update was failed */
  327. if (!fInvalidFw) {
  328. /* Set loadMode = 0 */
  329. RTC_WriteBackupRegister(RTC_BKP_DR1, 0);
  330. } else {
  331. /* Set loadMode = 1 */
  332. RTC_WriteBackupRegister(RTC_BKP_DR1, 1);
  333. }
  334. #ifdef SLAVEBRD_ENABLE
  335. /* Reboot daughter board */
  336. stmReboot();
  337. #endif
  338. /* Self reboot */
  339. NVIC_SystemReset();
  340. }
  341. /* Статус обновления и таймаут до перезагрузки */
  342. else if (strncmp(data, "GET /status.cgi", 15) == 0) {
  343. memset(sendBuf, 0, sizeof(sendBuf));
  344. /* Headers для поддержки saffari */
  345. sprintf(sendBuf, "HTTP/1.1 200 OK\r\nContent-Type:text/json\r\n\r\n");
  346. char buf[32];
  347. uint8_t update_state = 0;
  348. if (upload_pcb != NULL && fw_type == fw_unknown) {
  349. update_state = 1;
  350. } else if (upload_pcb != NULL && fw_type == fw_daughter_board) {
  351. update_state = 2;
  352. } else if (upload_pcb != NULL && fw_type == fw_main_board) {
  353. update_state = 3;
  354. } else {
  355. update_state = 0;
  356. }
  357. strcat(sendBuf, "{");
  358. sprintf(buf, "\"upload\":\"%u\",", (unsigned int)update_state);
  359. strcat(sendBuf, buf);
  360. sprintf(buf, "\"progress\":\"%u\",", (unsigned int)(TotalReceived * 100 / size));
  361. strcat(sendBuf, buf);
  362. sprintf(buf, "\"wrtmr\":\"%u\",", timer_GetCountdown(&ProgTimeout_Handler) / 1000);
  363. strcat(sendBuf, buf);
  364. sprintf(buf, "\"updtmr\":\"%u\",", update_timeout);
  365. strcat(sendBuf, buf);
  366. #ifdef SLAVEBRD_ENABLE
  367. sprintf(buf, "\"file1\":\"%s\",", DAUGHTER_FW_NAME);
  368. strcat(sendBuf, buf);
  369. #endif
  370. sprintf(buf, "\"file2\":\"%s\",", MAIN_FW_NAME);
  371. strcat(sendBuf, buf);
  372. /* sprintf(buf, "\"rev\":\"%s\",", REVISION);
  373. strcat(sendBuf, buf); */
  374. sprintf(buf, "\"invalidfw\":%s", fInvalidFw ? "true" : "false");
  375. strcat(sendBuf, buf);
  376. strcat(sendBuf, "}");
  377. hs->file = sendBuf;
  378. hs->left = strlen(sendBuf);
  379. pbuf_free(p);
  380. send_data(pcb, hs);
  381. tcp_sent(pcb, http_sent);
  382. }
  383. else if ((strncmp(data, "GET /upload.html", 16) == 0) &&
  384. (!CookieIsSet(p->payload, p->tot_len, "file1=") ||
  385. !CookieIsSet(p->payload, p->tot_len, "file2="))) {
  386. if (cookie_attempt < COOKIES_SET_ATTEMPTS) {
  387. /* Cookies not found. Try to set. */
  388. send_index_page(pcb, hs, p, upload_pcb != NULL);
  389. cookie_attempt++;
  390. } else {
  391. cookie_attempt = 0;
  392. /* Send Cookie set error message */
  393. strcpy(sendBuf, HTTP_200_OK_TEXT_HTML);
  394. strcat(sendBuf, "\r\n\r\n");
  395. strcat(sendBuf, Redirect_Head);
  396. strcat(sendBuf, "</head>");
  397. strcat(sendBuf, Msg_Body);
  398. strcat(sendBuf, "Включите файлы cookie в браузере и попробуйте <a href=\"index.html\">еще раз.</a></p></body></html>\r\n\r\n");
  399. hs->file = sendBuf;
  400. hs->left = strlen(sendBuf);
  401. pbuf_free(p);
  402. send_data(pcb, hs);
  403. tcp_sent(pcb, http_sent);
  404. }
  405. }
  406. /* Check common GET request */
  407. else if (GetFileName(data, fname, &fname_len)) {
  408. char nonmatch[MAX_ETAG_LEN];
  409. char *pnonmatch = NULL;
  410. /* Parce If-Non_Match value */
  411. uint8_t nonmatch_len = Parse_Header(data, p->tot_len, If_None_Match, 15, nonmatch);
  412. if (nonmatch_len < MAX_ETAG_LEN && nonmatch_len > 0) {
  413. printf("If_None_Match: %s\r\n", nonmatch);
  414. pnonmatch = nonmatch;
  415. }
  416. if (send_file(fname, pnonmatch, pcb, hs, &file)) {
  417. pbuf_free(p);
  418. } else {
  419. send_index_page(pcb, hs, p, upload_pcb != NULL);
  420. }
  421. }
  422. /* Send default index page */
  423. else {
  424. send_index_page(pcb, hs, p, upload_pcb != NULL);
  425. }
  426. }
  427. /* Process POST request for file upload and incoming data packets after POST request */
  428. /* Tested MTU sizes: 400 - 1500. Sizes < 400 not supported currently. */
  429. else if ((strncmp(data, "POST /upload.cgi", 16) == 0 && upload_pcb == NULL) ||
  430. (DataFlag >= 1 && pcb == upload_pcb)) {
  431. static char boundary[BOUNDARY_MAX_LEN];
  432. static char boundary_part[BOUNDARY_MAX_LEN];
  433. static char *pbound = NULL;
  434. fUpload = true;
  435. DataOffset = 0;
  436. #ifndef DUMMY_PROG
  437. DBG printf("\r\n[%u] ______\r\n", (unsigned int)len);
  438. #endif
  439. /* POST Packet received */
  440. if (DataFlag == 0) {
  441. BrowserFlag = 0;
  442. TotalReceived = 0;
  443. BoundaryFlag = 0;
  444. temp_len = 0;
  445. upload_pcb = pcb;
  446. hw_validated = false;
  447. fw_type = fw_unknown;
  448. /* Reset block receive and prog timeout */
  449. timer_Restart(&ProgTimeout_Handler);
  450. /* Parse packet for Content-length field */
  451. size = Parse_Content_Length(data, p->tot_len);
  452. DBG printf("Content_Length: %u\r\n", (unsigned int)size);
  453. /* Parse packet for the boundary field */
  454. pbound = Parce_Boundary(data, p->tot_len, boundary, sizeof(boundary));
  455. DBG printf("boundary: %s\r\n", pbound ? boundary : "header not found");
  456. /* Find the boundary */
  457. if (pbound != NULL) {
  458. for (i = 0; i < len; i++) {
  459. if (strncmp((char *)(data + i), boundary, strlen(boundary)) == 0) {
  460. ContentOffset = i;
  461. BoundaryFlag = 1;
  462. DBG printf("boundary found\r\n");
  463. /* Parse packet for "\r\n\r\n" field */
  464. for (int32_t j = 0; j < len; j++) {
  465. if (strncmp((char *)(data + i + j), "\r\n\r\n", 4) == 0) {
  466. DataOffset = i + j + 4;
  467. break;
  468. }
  469. }
  470. }
  471. }
  472. }
  473. /* TODO Handle partially received boundary */
  474. if (BoundaryFlag) {
  475. TotalReceived = len - ContentOffset;
  476. }
  477. DBG {
  478. printf("Boundary: %s\r\n", BoundaryFlag ? "yes" : "no");
  479. printf("ContentOffset: %u\r\n", (unsigned int)ContentOffset);
  480. printf("DataOffset: %u\r\n", (unsigned int)DataOffset);
  481. printf("TotalReceived: %u/%u\r\n", (unsigned int)TotalReceived, (unsigned int)size);
  482. }
  483. if (fw_type == fw_unknown) {
  484. Parse_Filename(data, len, &fw_type, &FwDestSize);
  485. }
  486. /* No data in the first POST packet */
  487. if (DataOffset == 0) {
  488. DataFlag++;
  489. BrowserFlag = 1;
  490. pbuf_free(p);
  491. return ERR_OK;
  492. }
  493. }
  494. if (((DataFlag == 1) && (BrowserFlag == 1)) || ((DataFlag == 0) && (BrowserFlag == 0))) {
  495. if ((DataFlag == 0) && (BrowserFlag == 0)) {
  496. DataFlag++;
  497. } else if ((DataFlag == 1) && (BrowserFlag == 1)) {
  498. /* Find the boundary */
  499. for (i = 0; i < len; i++) {
  500. if (pbound != NULL) {
  501. if (strncmp((char *)(data + i), boundary, strlen(boundary)) == 0 || BoundaryFlag == 1) {
  502. /* Parse packet for "\r\n\r\n" field */
  503. for (int32_t j = 0; j < len; j++) {
  504. if (strncmp((char *)(data + i + j), "\r\n\r\n", 4) == 0) {
  505. DataOffset = i + j + 4;
  506. break;
  507. }
  508. }
  509. break;
  510. }
  511. }
  512. }
  513. /* TODO Handle partially received boundary */
  514. TotalReceived += len;
  515. DataFlag++;
  516. }
  517. if (fw_type == fw_unknown) {
  518. Parse_Filename(data, len, &fw_type, &FwDestSize);
  519. }
  520. DBG {
  521. printf("ContentOffset: %u\r\n", (unsigned int)ContentOffset);
  522. printf("DataOffset: %u\r\n", (unsigned int)DataOffset);
  523. printf("TotalReceived: %u/%u\r\n", (unsigned int)TotalReceived, (unsigned int)size);
  524. }
  525. /* Get next packet */
  526. if (!DataOffset) {
  527. DataFlag--;
  528. pbuf_free(p);
  529. return ERR_OK;
  530. }
  531. if (fw_type == fw_unknown) {
  532. htmlpage = FileUploadPage;
  533. /* No filename, in this case reload upload page */
  534. fs_open("/index.html", &file);
  535. hs->file = file.data;
  536. hs->left = file.len;
  537. pbuf_free(p);
  538. send_data(pcb, hs);
  539. tcp_sent(pcb, http_sent);
  540. DataFlag = 0;
  541. upload_pcb = NULL;
  542. printf("Error: Unknown firmware\r\n");
  543. #ifdef LCD_ENABLE
  544. LCD_PrintAligned(7, alignCENTER, "Ошибка!");
  545. #endif
  546. return ERR_OK;
  547. }
  548. TotalData = 0;
  549. }
  550. /* DataFlag >1 => the packet is data only */
  551. else {
  552. TotalReceived += len;
  553. }
  554. ptr = (char *)(data + DataOffset);
  555. len -= DataOffset;
  556. /* Update total data received counter */
  557. TotalData += len;
  558. #ifndef DUMMY_PROG
  559. DBG printf("TotalData: +%u %u/%u\r\n", (unsigned int)len,
  560. (unsigned int)TotalData, (unsigned int)FwDestSize);
  561. DBG printf("%u/%u\r\n", (unsigned int)TotalReceived, (unsigned int)size);
  562. #endif
  563. /* Check if last data packet */
  564. if (TotalReceived == size) {
  565. /* Check if boundary was splited into two packets. Get second part. */
  566. /* Data transfer sequence should end with "\r\n" + boundary + "--\rn" (6 extra bytes) */
  567. if ((pbound) && (p->tot_len <= strlen(boundary) + 6)) {
  568. /* No data in packet */
  569. TotalData = TotalData - len;
  570. len = 0;
  571. } else {
  572. char *bptr = memmemory(data, p->tot_len, boundary, strlen(boundary));
  573. // DBG printf("boundary: %s\r\n", boundary);
  574. if (bptr != NULL) {
  575. /* Substruct length of "\r\n" - 2 bytes */
  576. uint32_t last_len = bptr - data - 2;
  577. TotalData = TotalData - len + last_len;
  578. len = last_len;
  579. } else {
  580. printf("Boundary not found\r\n");
  581. }
  582. }
  583. }
  584. /* Not the last data packet */
  585. else if (TotalReceived < size) {
  586. /* Check if boundary was splited into two packets. Get first part. */
  587. /* Data transfer sequence should end with "\r\n" + boundary + "--\rn" (6 extra bytes) */
  588. if ((pbound) && (size - TotalReceived < strlen(boundary) + 6)) {
  589. uint16_t tail_len = size - TotalReceived;
  590. uint16_t boundary_len = strlen(boundary) + 6;
  591. /* Find "\r\n" or "\r" depending on a current packet length */
  592. uint8_t marker_len = (tail_len - boundary_len >= 2) ? 2 : 1;
  593. char *ptr = memmemory(data + p->tot_len - boundary_len, boundary_len,
  594. marker_len == 2 ? "\r\n" : "\r", marker_len);
  595. if (ptr != NULL) {
  596. DBG {
  597. /* Boundary first part is not actually used, just for debug output */
  598. uint32_t buflen = len - (uint32_t)(ptr + marker_len - data);
  599. printf("buflen: %u\r\n", (unsigned int)buflen);
  600. if (buflen > BOUNDARY_MAX_LEN) buflen = BOUNDARY_MAX_LEN;
  601. memcpy(boundary_part, ptr + marker_len, buflen);
  602. printf("boundary part: %s\r\n", boundary_part);
  603. }
  604. uint32_t last_len = ptr - data;
  605. TotalData = TotalData - len + last_len;
  606. len = last_len;
  607. } else {
  608. DBG printf("Boundary part not found!\r\n");
  609. }
  610. }
  611. /* Validate uploaded binary */
  612. if ((TotalData >= HW_REV_OFFSET + HW_REV_LEN) && (!hw_validated)) {
  613. char rev[HW_REV_LEN];
  614. if (fw_type == fw_main_board) {
  615. strncpy(rev, HW_REV, HW_REV_LEN);
  616. }
  617. #ifdef SLAVEBRD_ENABLE
  618. else if (fw_type == fw_daughter_board) {
  619. strncpy(rev, HW_REV_UPPER, HW_REV_LEN);
  620. }
  621. #endif
  622. else {
  623. strncpy(rev, "-", HW_REV_LEN);
  624. }
  625. char bin_rev[HW_REV_LEN];
  626. memset(bin_rev, 0, sizeof(bin_rev));
  627. uint32_t first_len = temp_len > HW_REV_OFFSET ? temp_len - HW_REV_OFFSET : 0;
  628. /* Copy 1st part (if not empty) */
  629. memcpy(bin_rev, tempBuf + HW_REV_OFFSET, first_len);
  630. /* Copy 2nd part */
  631. memcpy(bin_rev + first_len, ptr + HW_REV_OFFSET - (temp_len - first_len), HW_REV_LEN - first_len);
  632. if (strncmp(bin_rev, rev, HW_REV_LEN) != 0) {
  633. printf("HW version (%s) mismatch: found %s\r\n", rev, bin_rev);
  634. printf("Update aborted!\r\n");
  635. #ifdef LCD_ENABLE
  636. LCD_PrintAligned(7, alignCENTER, "Ошибка!");
  637. #endif
  638. DataFlag = 0;
  639. upload_pcb = NULL;
  640. HTTP_RET_UPLOAD_ERROR_NO_FLASH_ERASE();
  641. pbuf_free(p);
  642. return ERR_OK;
  643. } else {
  644. printf("HW version (%s) validated\r\n", bin_rev);
  645. hw_validated = true;
  646. printf("State: Erasing...\r\n");
  647. SET_FWINVALID_FLAG();
  648. #ifdef LCD_ENABLE
  649. LCD_ClearRow(7);
  650. #ifdef SLAVEBRD_ENABLE
  651. sprintf(lcdbuf, "Очистка %d/2 ", fw_type == fw_main_board ? 2 : 1);
  652. LCD_PrintAligned(5, alignCENTER, lcdbuf);
  653. #else
  654. LCD_PrintAligned(5, alignCENTER, "Очистка...");
  655. #endif
  656. #endif
  657. switch (fw_type) {
  658. case fw_main_board:
  659. /* Erase flash */
  660. if (fEraseFlash) {
  661. FLASH_If_Erase(USER_FLASH_FIRST_PAGE_ADDRESS);
  662. fEraseFlash = false;
  663. }
  664. /* Init flash */
  665. FLASH_If_Init();
  666. FlashWriteAddress = USER_FLASH_FIRST_PAGE_ADDRESS;
  667. break;
  668. #ifdef SLAVEBRD_ENABLE
  669. case fw_daughter_board:
  670. stm32addr = DB_CPU_FLASH_FIRST_PAGE_ADDRESS;
  671. uint8_t retries = 0;
  672. /* Try to connect to stm32 */
  673. while ((!IAP_HTTP_stmConnect()) && (retries++ < (BD_CONNECT_RETRY - 1))) {
  674. ;
  675. }
  676. /* Error if no device found */
  677. if (retries >= BD_CONNECT_RETRY) {
  678. #ifdef LCD_ENABLE
  679. LCD_PrintAligned(7, alignCENTER, "Ошибка!");
  680. #endif
  681. DataFlag = 0;
  682. upload_pcb = NULL;
  683. HTTP_RET_UPLOAD_ERROR();
  684. pbuf_free(p);
  685. return ERR_OK;
  686. }
  687. break;
  688. #endif
  689. default:
  690. break;
  691. }
  692. #ifdef LCD_ENABLE
  693. LCD_ClearRow(7);
  694. #ifdef SLAVEBRD_ENABLE
  695. sprintf(lcdbuf, "Запись %d/2", fw_type == fw_main_board ? 2 : 1);
  696. LCD_PrintAligned(5, alignCENTER, lcdbuf);
  697. #else
  698. LCD_PrintAligned(5, alignCENTER, "Запись...");
  699. #endif
  700. #endif
  701. /*indicate start of flash programming */
  702. printf("\r\nState: Programming..\r\n");
  703. }
  704. }
  705. }
  706. if (hw_validated) {
  707. /* Check fw data size overflow */
  708. if (TotalData > FwDestSize) {
  709. printf("FW binary size mismatch. Aborting update..\r\n");
  710. printf("FW dest size %u was %u\r\n", (unsigned int)FwDestSize, (unsigned int)TotalData);
  711. HTTP_RET_UPLOAD_ERROR_NO_FLASH_ERASE();
  712. } else {
  713. static uint8_t progress = 0;
  714. if (progress != TotalReceived * 100 / size) {
  715. progress = TotalReceived * 100 / size;
  716. #ifndef DUMMY_PROG
  717. printf("Writing: %u%%\r\n", (unsigned int)progress);
  718. #ifdef LCD_ENABLE
  719. LCD_PrintBar(7, (unsigned int)(100 * TotalReceived / size));
  720. #endif
  721. #endif
  722. }
  723. /* Reset block prog timeout */
  724. timer_Restart(&ProgTimeout_Handler);
  725. /* Write data in flash */
  726. if (len) {
  727. switch (fw_type) {
  728. case fw_main_board:
  729. if (temp_len) {
  730. IAP_HTTP_writedata(tempBuf, temp_len);
  731. temp_len = 0;
  732. }
  733. IAP_HTTP_writedata(ptr, len);
  734. break;
  735. #ifdef SLAVEBRD_ENABLE
  736. case fw_daughter_board:
  737. if (temp_len) {
  738. IAP_HTTP_stmProg(tempBuf, temp_len);
  739. temp_len = 0;
  740. }
  741. IAP_HTTP_stmProg(ptr, len);
  742. break;
  743. #endif
  744. default:
  745. break;
  746. }
  747. }
  748. }
  749. } else {
  750. /* Save first part */
  751. memcpy(tempBuf + temp_len, ptr, len);
  752. temp_len += len;
  753. DBG printf("Stashed: %u\r\n", (unsigned int)temp_len);
  754. }
  755. if (TotalReceived == size) {
  756. /* Stop block receive timer */
  757. timer_Stop(&ProgTimeout_Handler);
  758. DataFlag = 0;
  759. upload_pcb = NULL;
  760. printf("State: Verifying..\r\n");
  761. #ifdef LCD_ENABLE
  762. LCD_ClearRow(7);
  763. #ifdef SLAVEBRD_ENABLE
  764. sprintf(lcdbuf, "Проверка CRC %d/2", fw_type == fw_main_board ? 2 : 1);
  765. LCD_PrintAligned(5, alignCENTER, lcdbuf);
  766. #else
  767. LCD_PrintAligned(5, alignCENTER, "Проверка CRC...");
  768. #endif
  769. #endif
  770. switch (fw_type) {
  771. case fw_main_board:
  772. CrcRead = CRC_Read();
  773. CrcCalc = CRC_Calculate(&PeriodicHandle);
  774. break;
  775. #ifdef SLAVEBRD_ENABLE
  776. case fw_daughter_board:
  777. CrcRead = stmReadFlashCrc();
  778. CrcCalc = stmCalcFlashCrc(&PeriodicHandle);
  779. break;
  780. #endif
  781. default:
  782. break;
  783. }
  784. printf("State: Prog Finished\r\n\r\n");
  785. printf("Tot bytes received: %u bytes\r\n", (unsigned int)TotalData);
  786. printf("CRC read: 0x%X\r\n", (unsigned int)CrcRead);
  787. printf("CRC calcucated: 0x%X\r\n", (unsigned int)CrcCalc);
  788. /* Check CRC */
  789. if (CrcRead == CrcCalc) {
  790. printf("CRC check: Pass\r\n");
  791. /* Reset block receive and prog timeout */
  792. timer_Restart(&ProgTimeout_Handler);
  793. memset(sendBuf, 0, 32);
  794. strcpy(sendBuf, HTTP_200_OK);
  795. strcat(sendBuf, "1");
  796. hs->file = sendBuf;
  797. hs->left = strlen(sendBuf);
  798. send_data(pcb, hs);
  799. tcp_sent(pcb, http_sent);
  800. #ifdef LCD_ENABLE
  801. LCD_PrintAligned(7, alignCENTER, "Успешно!");
  802. #endif
  803. switch (fw_type) {
  804. case fw_main_board:
  805. /* Run main FW */
  806. htmlpage = UploadDonePage;
  807. break;
  808. #ifdef SLAVEBRD_ENABLE
  809. case fw_daughter_board:
  810. timer_ChangeFrequency(&LED_Blinky_Green, 250);
  811. /* Nothing to do */
  812. break;
  813. #endif
  814. default:
  815. break;
  816. }
  817. } else {
  818. #ifdef LCD_ENABLE
  819. LCD_PrintAligned(7, alignCENTER, "Ошибка!");
  820. #endif
  821. switch (fw_type) {
  822. case fw_main_board:
  823. /* Erase flash */
  824. /* That's a way not to boot wrong FW next time if update was failed */
  825. FLASH_If_Erase(USER_FLASH_FIRST_PAGE_ADDRESS);
  826. fEraseFlash = false;
  827. break;
  828. #ifdef SLAVEBRD_ENABLE
  829. case fw_daughter_board:
  830. /* We can boot device if upper board update was failed. */
  831. break;
  832. #endif
  833. default:
  834. break;
  835. }
  836. printf("CRC check: Fail\r\n");
  837. HTTP_RET_UPLOAD_ERROR();
  838. }
  839. }
  840. pbuf_free(p);
  841. } else {
  842. /* Bad HTTP requests */
  843. printf("Bad HTTP request\r\n");
  844. pbuf_free(p);
  845. close_conn(pcb, hs);
  846. }
  847. } else {
  848. pbuf_free(p);
  849. close_conn(pcb, hs);
  850. }
  851. } else if (err == ERR_OK && p == NULL) {
  852. /* Received empty frame */
  853. printf("Received empty frame\r\n");
  854. close_conn(pcb, hs);
  855. }
  856. return ERR_OK;
  857. }
  858. /**
  859. * @brief callback function on TCP connection setup ( on port 80)
  860. * @param arg: pointer to an argument structure to be passed to callback function
  861. * @param pcb: pointer to a tcp_pcb structure
  862. * &param err: Lwip stack error code
  863. * @retval err
  864. */
  865. static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err)
  866. {
  867. struct http_state *hs;
  868. (void)err;
  869. (void)arg;
  870. /* Allocate memory for the structure that holds the state of the connection */
  871. hs = mem_malloc(sizeof(struct http_state));
  872. if (hs == NULL) {
  873. return ERR_MEM;
  874. }
  875. /* Initialize the structure. */
  876. hs->file = NULL;
  877. hs->left = 0;
  878. /* Tell TCP that this is the structure we wish to be passed for our
  879. callbacks. */
  880. tcp_arg(pcb, hs);
  881. /* Tell TCP that we wish to be informed of incoming data by a call
  882. to the http_recv() function. */
  883. tcp_recv(pcb, http_recv);
  884. tcp_err(pcb, conn_err);
  885. tcp_poll(pcb, http_poll, 10);
  886. return ERR_OK;
  887. }
  888. /**
  889. * @brief intialize HTTP webserver
  890. * @param none
  891. * @retval none
  892. */
  893. void IAP_httpd_init(void)
  894. {
  895. struct tcp_pcb *pcb;
  896. /*create new pcb*/
  897. pcb = tcp_new();
  898. /* bind HTTP traffic to pcb */
  899. tcp_bind(pcb, IP_ADDR_ANY, 80);
  900. /* start listening on port 80 */
  901. pcb = tcp_listen(pcb);
  902. /* define callback function for TCP connection setup */
  903. tcp_accept(pcb, http_accept);
  904. /* Set block receive and prog timeout */
  905. timer_AddFunction(BLOCK_PROG_TIMEOUT, &ProgTimeout_Handler);
  906. timer_Stop(&ProgTimeout_Handler);
  907. }
  908. /**
  909. * @brief Opens a file defined in fsdata.c ROM filesystem
  910. * @param name : pointer to a file name
  911. * @param file : pointer to a fs_file structure
  912. * @retval 1 if success, 0 if fail
  913. */
  914. static int fs_open(char *name, struct fs_file *file)
  915. {
  916. struct fsdata_file_noconst *f;
  917. for (f = (struct fsdata_file_noconst *)FS_ROOT; f != NULL; f = (struct fsdata_file_noconst *)f->next) {
  918. if (!strcmp(name, f->name)) {
  919. file->data = f->data;
  920. file->len = f->len;
  921. return 1;
  922. }
  923. }
  924. return 0;
  925. }
  926. /**
  927. * @brief sends file from flash FS
  928. * @param filename: pointer to the file name to send
  929. * @param pnonmatch: pointer to the If-Non_Match value
  930. * @param pcb: pointer to a tcp_pcb struct
  931. * @param hs: pointer to a http_state struct
  932. * @param file: pointer to a fs_file struct
  933. * @retval
  934. */
  935. bool send_file(char *filename, char *pnonmatch, struct tcp_pcb *pcb, struct http_state *hs, struct fs_file *file)
  936. {
  937. int res = 0;
  938. char etag[MAX_ETAG_LEN];
  939. char *petag = NULL;
  940. res = fs_open(filename, file);
  941. if (res == 0) {
  942. return false;
  943. }
  944. /* Find Etag value */
  945. uint8_t etag_len = Parse_Header(file->data, file->len, Etag, 6, etag);
  946. if (etag_len < MAX_ETAG_LEN && etag_len > 0) {
  947. printf("Etag: %s\r\n", etag);
  948. petag = etag;
  949. }
  950. /* Compare Etag and If-Non-Match fields */
  951. if (pnonmatch && petag && (strcmp(pnonmatch, petag) == 0)) {
  952. /* Send 304 code */
  953. sprintf(sendBuf, HTTP_304_NOT_MODIFIED);
  954. printf(sendBuf);
  955. hs->file = sendBuf;
  956. hs->left = strlen(sendBuf);
  957. } else {
  958. /* Send file */
  959. printf("%s\r\n\r\n", filename);
  960. hs->file = file->data;
  961. hs->left = file->len;
  962. }
  963. send_data(pcb, hs);
  964. tcp_sent(pcb, http_sent);
  965. return true;
  966. }
  967. /**
  968. * @brief
  969. * @retval None
  970. */
  971. void send_index_page(struct tcp_pcb *pcb, struct http_state *hs, struct pbuf *p, bool upload)
  972. {
  973. char buf[32];
  974. /* Send cookie */
  975. strcpy(sendBuf, "HTTP/1.1 200 OK\r\nContent-Type:text/html\r\n");
  976. strcat(sendBuf, "Set-Cookie: upload=");
  977. sprintf(buf, "%d", (unsigned char)upload);
  978. strcat(sendBuf, buf);
  979. strcat(sendBuf, "\r\nSet-Cookie: wrtmr=");
  980. sprintf(buf, "%d", timer_GetCountdown(&ProgTimeout_Handler) / 1000);
  981. strcat(sendBuf, buf);
  982. strcat(sendBuf, "\r\nSet-Cookie: updtmr=");
  983. sprintf(buf, "%d", update_timeout);
  984. strcat(sendBuf, buf);
  985. strcat(sendBuf, "\r\nSet-Cookie: file1=");
  986. #ifdef SLAVEBRD_ENABLE
  987. strcat(sendBuf, DAUGHTER_FW_NAME);
  988. #else
  989. strcat(sendBuf, "NONE");
  990. #endif
  991. strcat(sendBuf, "\r\nSet-Cookie: file2=");
  992. char file_name_buf[40];
  993. memset(file_name_buf, 0, sizeof(file_name_buf));
  994. strcpy(file_name_buf, MAIN_FW_NAME);
  995. if(strcmp(file_name_buf, "NONE") != 0){
  996. strcat(sendBuf, MAIN_FW_NAME);
  997. } else {
  998. strcat(sendBuf, " ");
  999. }
  1000. strcat(sendBuf,
  1001. "\r\n\r\n<!DOCTYPE html><html lang="
  1002. "><head><meta \
  1003. http-equiv=\"refresh\" content=\"0;url=/upload.html\"/></head></html>\r\n\r\n");
  1004. htmlpage = LoginPage;
  1005. hs->file = sendBuf;
  1006. hs->left = strlen(sendBuf);
  1007. pbuf_free(p);
  1008. send_data(pcb, hs);
  1009. tcp_sent(pcb, http_sent);
  1010. }
  1011. /**
  1012. * @brief Extract the Content_Length data from HTML data
  1013. * @param data : pointer on receive packet buffer
  1014. * @param len : buffer length
  1015. * @retval size : Content_length in numeric format
  1016. */
  1017. static uint32_t Parse_Content_Length(char *data, uint32_t len)
  1018. {
  1019. uint32_t i = 0, size = 0, S = 1;
  1020. int32_t j = 0;
  1021. char sizestring[6], *ptr;
  1022. uint32_t ContentLengthOffset = 0;
  1023. /* find Content-Length data in packet buffer */
  1024. for (i = 0; i < len; i++) {
  1025. if (strncmp((char *)(data + i), Content_Length, 16) == 0) {
  1026. ContentLengthOffset = i + 16;
  1027. break;
  1028. }
  1029. }
  1030. /* read Content-Length value */
  1031. if (ContentLengthOffset) {
  1032. i = 0;
  1033. ptr = (char *)(data + ContentLengthOffset);
  1034. while (*(ptr + i) != 0x0d && (i < len - ContentLengthOffset)) {
  1035. sizestring[i] = *(ptr + i);
  1036. i++;
  1037. ContentLengthOffset++;
  1038. }
  1039. if (i > 0) {
  1040. /* transform string data into numeric format */
  1041. for (j = i - 1; j >= 0; j--) {
  1042. size += (sizestring[j] - 0x30) * S;
  1043. S = S * 10;
  1044. }
  1045. }
  1046. }
  1047. return size;
  1048. }
  1049. /**
  1050. * @brief Extract the custom field data from HTML data
  1051. * @param data : pointer on receive packet buffer
  1052. * @param len : buffer length
  1053. * @param field : field name
  1054. * @param flen : field name length
  1055. * @retval value : pointer for field data
  1056. */
  1057. static uint32_t Parse_Header(char *data, uint32_t len, const char *field, uint32_t flen, char *value)
  1058. {
  1059. uint32_t i = 0, size = 0;
  1060. char *ptr;
  1061. uint32_t Offset = 0;
  1062. /* Find field name in data buffer */
  1063. for (i = 0; i < len; i++) {
  1064. if (strncmp((char *)(data + i), field, flen) == 0) {
  1065. Offset = i + flen;
  1066. break;
  1067. }
  1068. }
  1069. /* Copy Field value */
  1070. if (Offset) {
  1071. i = 0;
  1072. ptr = (char *)(data + Offset);
  1073. while (*(ptr + i) != 0x0d && (i < len - Offset)) {
  1074. value[i] = *(ptr + i);
  1075. i++;
  1076. }
  1077. value[i] = '\0';
  1078. size = i;
  1079. }
  1080. return size;
  1081. }
  1082. /**
  1083. * @brief
  1084. * @retval None
  1085. */
  1086. char *Parce_Boundary(const char *data, uint32_t len, char *dst, uint8_t dstlen)
  1087. {
  1088. char *ptr = NULL;
  1089. char *boundary = NULL;
  1090. uint8_t i = 0;
  1091. for (uint32_t j = 0; j < len; j++) {
  1092. if (strncmp((char *)(data + j), "boundary=", 9) == 0) {
  1093. boundary = (char *)data + j + 9;
  1094. break;
  1095. }
  1096. }
  1097. if (!boundary) return NULL;
  1098. *dst++ = '-';
  1099. *dst++ = '-';
  1100. ptr = boundary;
  1101. while ((*ptr != 0x0d) && (i < dstlen - 4)) {
  1102. *dst++ = *ptr++;
  1103. i++;
  1104. }
  1105. //*dst++ = '-';
  1106. //*dst++ = '-';
  1107. *dst = '\0';
  1108. if (i > 0)
  1109. return boundary;
  1110. else
  1111. return NULL;
  1112. }
  1113. static bool Parse_Filename(const char *data, uint32_t len, fw_type_t *fw_type, uint32_t *fw_size)
  1114. {
  1115. /* Parse packet for the filename field */
  1116. uint32_t FilenameOffset = 0;
  1117. char filename[FILENAME_MAX_LEN];
  1118. char file_name_buf[40];
  1119. memset(file_name_buf, 0, sizeof(file_name_buf));
  1120. strcpy(file_name_buf, MAIN_FW_NAME);
  1121. if(strcmp(file_name_buf, "NONE") == 0){
  1122. *fw_type = fw_main_board;
  1123. *fw_size = MAIN_FW_SIZE;
  1124. return true;
  1125. }
  1126. for (uint32_t i = 0; i < len; i++) {
  1127. if (strncmp((char *)(data + i), "filename=", 9) == 0) {
  1128. FilenameOffset = i + 10;
  1129. break;
  1130. }
  1131. }
  1132. if (FilenameOffset) {
  1133. uint32_t i = 0;
  1134. while ((*(data + FilenameOffset + i) != 0x22) &&
  1135. (i < FILENAME_MAX_LEN) &&
  1136. (FilenameOffset + i <= len)) {
  1137. filename[i] = *(data + FilenameOffset + i);
  1138. i++;
  1139. }
  1140. filename[i] = 0x0;
  1141. printf("File: %s\r\n", filename);
  1142. /* Decide which FW is uploaded */
  1143. if (strncmp(filename, MAIN_FW_NAME, 16) == 0) {
  1144. *fw_type = fw_main_board;
  1145. *fw_size = MAIN_FW_SIZE;
  1146. printf("Updating main board FW..\r\n");
  1147. }
  1148. #ifdef SLAVEBRD_ENABLE
  1149. else if (strncmp(filename, DAUGHTER_FW_NAME, 16) == 0) {
  1150. *fw_type = fw_daughter_board;
  1151. *fw_size = DB_FW_SIZE;
  1152. printf("Updating daughter FW..\r\n");
  1153. }
  1154. #endif
  1155. else {
  1156. *fw_type = fw_unknown;
  1157. }
  1158. return true;
  1159. }
  1160. return false;
  1161. }
  1162. /**
  1163. * @brief
  1164. * @retval None
  1165. */
  1166. bool GetFileName(char *inStr, char *fileName, uint8_t *fileNameLen)
  1167. {
  1168. char *beginValue = NULL;
  1169. char *endValue = NULL;
  1170. int len = 0;
  1171. char *strPtr = NULL;
  1172. strPtr = strstr(inStr, "GET");
  1173. if (strPtr == NULL) {
  1174. strPtr = strstr(inStr, "POST");
  1175. }
  1176. if (strPtr == NULL) {
  1177. *fileNameLen = 0;
  1178. return false;
  1179. } else {
  1180. beginValue = strpbrk(strPtr, "/");
  1181. endValue = strpbrk(beginValue, " ");
  1182. if (endValue == NULL) {
  1183. *fileNameLen = 0;
  1184. return false;
  1185. }
  1186. len = endValue - beginValue;
  1187. if (len < HTTP_FNAME_LEN) {
  1188. strncpy(fileName, beginValue, len);
  1189. *fileNameLen = len;
  1190. fileName[len] = '\0';
  1191. return true;
  1192. } else {
  1193. return false;
  1194. }
  1195. }
  1196. }
  1197. /**
  1198. * @brief writes received data in flash
  1199. * @param ptr: data pointer
  1200. * @param len: data length
  1201. * @retval none
  1202. */
  1203. void IAP_HTTP_writedata(char *ptr, uint32_t len)
  1204. {
  1205. uint32_t count, i = 0, j = 0;
  1206. /* check if any left bytes from previous packet transfer*/
  1207. /* if it is the case do a concat with new data to create a 32-bit word */
  1208. if (LeftBytes) {
  1209. while (LeftBytes <= 3) {
  1210. if (len > (j + 1)) {
  1211. LeftBytesTab[LeftBytes++] = *(ptr + j);
  1212. } else {
  1213. LeftBytesTab[LeftBytes++] = 0xFF;
  1214. }
  1215. j++;
  1216. }
  1217. FLASH_If_Write(&FlashWriteAddress, (u32 *)(LeftBytesTab), 1);
  1218. LeftBytes = 0;
  1219. /* update data pointer */
  1220. ptr = (char *)(ptr + j);
  1221. len = len - j;
  1222. }
  1223. /* write received bytes into flash */
  1224. count = len / 4;
  1225. /* check if remaining bytes < 4 */
  1226. i = len % 4;
  1227. if (i > 0) {
  1228. if (TotalReceived != size) {
  1229. /* store bytes in LeftBytesTab */
  1230. LeftBytes = 0;
  1231. for (; i > 0; i--)
  1232. LeftBytesTab[LeftBytes++] = *(char *)(ptr + len - i);
  1233. } else
  1234. count++;
  1235. }
  1236. FLASH_If_Write(&FlashWriteAddress, (u32 *)ptr, count);
  1237. }
  1238. uint32_t ReturnFlashWriteAddress(void)
  1239. {
  1240. return FlashWriteAddress;
  1241. }
  1242. #ifdef SLAVEBRD_ENABLE
  1243. /**
  1244. * @brief Connect stm32
  1245. */
  1246. bool IAP_HTTP_stmConnect(void)
  1247. {
  1248. bool ok = true;
  1249. stmRebootForFlash();
  1250. /* Connect */
  1251. ok = stmConnect();
  1252. if (!ok) {
  1253. printf("Error: device not detected.\n");
  1254. return false;
  1255. } else
  1256. printf("Device connected\n");
  1257. /* Get params */
  1258. ok = stmGetDevParams();
  1259. if (!ok) {
  1260. printf("Error: Device not supported.\n");
  1261. return false;
  1262. }
  1263. /* Erase */
  1264. printf("Erasing.. ");
  1265. ok = stmEraseFW();
  1266. if (ok)
  1267. printf("OK\n");
  1268. else {
  1269. printf("Erase error!\n");
  1270. return false;
  1271. }
  1272. stm32addr = DB_CPU_FLASH_FIRST_PAGE_ADDRESS;
  1273. return true;
  1274. }
  1275. /**
  1276. * @brief Prog received data to connected stm32 on uart
  1277. * @param ptr: data pointer
  1278. * @param len: data length
  1279. * @retval none
  1280. */
  1281. void IAP_HTTP_stmProg(char *ptr, uint32_t len)
  1282. {
  1283. uint32_t count, i, j = 0;
  1284. /* check if any left bytes from previous packet transfer*/
  1285. /* if it is the case do a concat with new data to create a 32-bit word */
  1286. if (LeftBytes) {
  1287. while (LeftBytes <= 3) {
  1288. if (len > (j + 1)) {
  1289. LeftBytesTab[LeftBytes++] = *(ptr + j);
  1290. } else {
  1291. LeftBytesTab[LeftBytes++] = 0xFF;
  1292. }
  1293. j++;
  1294. }
  1295. stmProg(&stm32addr, (uint8_t *)(LeftBytesTab), 4);
  1296. LeftBytes = 0;
  1297. /* update data pointer */
  1298. ptr = (char *)(ptr + j);
  1299. len = len - j;
  1300. }
  1301. /* write received bytes into flash */
  1302. count = len / 4;
  1303. /* check if remaining bytes < 4 */
  1304. i = len % 4;
  1305. if (i > 0) {
  1306. if (TotalReceived != size) {
  1307. /* store bytes in LeftBytesTab */
  1308. LeftBytes = 0;
  1309. for (; i > 0; i--) {
  1310. LeftBytesTab[LeftBytes++] = *(char *)(ptr + len - i);
  1311. }
  1312. } else {
  1313. count++;
  1314. }
  1315. }
  1316. stmProg(&stm32addr, (uint8_t *)ptr, count * 4);
  1317. }
  1318. #endif
  1319. void ProgTimeout_Handler()
  1320. {
  1321. /* If connection was broken during update,
  1322. * abort process, erase main board flash and restart IAP */
  1323. printf("Program timeout. Seems that connection was broken. Reboot...\r\n");
  1324. SET_FWINVALID_FLAG();
  1325. #ifdef LCD_ENABLE
  1326. LCD_PrintAligned(5, alignCENTER, "Таймаут обновления");
  1327. LCD_PrintAligned(7, alignCENTER, "Перезагрузка..");
  1328. #endif
  1329. switch (fw_type) {
  1330. case fw_main_board:
  1331. /* Erase flash */
  1332. FLASH_If_Erase(USER_FLASH_FIRST_PAGE_ADDRESS);
  1333. break;
  1334. #ifdef SLAVEBRD_ENABLE
  1335. case fw_daughter_board:
  1336. /*TODO Should we erase upper board here? */
  1337. break;
  1338. #endif
  1339. default:
  1340. break;
  1341. }
  1342. #ifdef SLAVEBRD_ENABLE
  1343. /* Reboot daughter board */
  1344. stmReboot();
  1345. #endif
  1346. /* Self reboot */
  1347. NVIC_SystemReset();
  1348. }
  1349. static void PeriodicHandle(uint8_t progress)
  1350. {
  1351. (void)progress;
  1352. #ifdef LCD_ENABLE
  1353. LCD_PrintBar(7, progress);
  1354. #endif
  1355. /* Handle periodic timers for LwIP */
  1356. LwIP_Periodic_Handle(0);
  1357. }
  1358. /* Get Cookie parameter value */
  1359. bool GetCookieValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1360. {
  1361. char *beginValue = 0;
  1362. char *endValue = 0;
  1363. char *endValueTemp = 0;
  1364. int len = 0;
  1365. char *strPtr = strstr(inStr, paramName);
  1366. if (strPtr != NULL) {
  1367. beginValue = strpbrk(strPtr, "=");
  1368. endValue = strpbrk(strPtr, ";");
  1369. endValueTemp = strpbrk(strPtr, "\r");
  1370. if (endValueTemp != 0 && endValueTemp < endValue) {
  1371. endValue = endValueTemp;
  1372. }
  1373. if (endValue == 0) {
  1374. endValue = strpbrk(strPtr, "\n");
  1375. }
  1376. len = endValue - beginValue - 1;
  1377. *endValue = '0';
  1378. *beginValue = '0';
  1379. if (paramValue && paramLen) {
  1380. strncpy(paramValue, beginValue + 1, len);
  1381. *paramLen = len;
  1382. }
  1383. return true;
  1384. } else {
  1385. return false;
  1386. }
  1387. }
  1388. /* Check if Cookie is set or not */
  1389. bool CookieIsSet(char *inStr, uint16_t inLen, char *paramName)
  1390. {
  1391. static char CookieBuf[COOKIES_MAX_LEN];
  1392. if (!inStr) return false;
  1393. char *CookiePtr = lwip_strnstr(inStr, "Cookie:", inLen);
  1394. if (CookiePtr) {
  1395. char *paramPtr = lwip_strnstr(CookiePtr, paramName, inLen - (inStr - CookiePtr));
  1396. if (paramPtr) {
  1397. strncpy(CookieBuf, paramPtr, sizeof(CookieBuf));
  1398. if (GetCookieValue(CookieBuf, paramName, NULL, NULL)) {
  1399. return true;
  1400. }
  1401. }
  1402. }
  1403. return false;
  1404. }
  1405. /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/