http_server.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. #include "lwip/opt.h"
  2. #include "lwip/arch.h"
  3. #include "lwip/api.h"
  4. #include "lwip/tcp.h"
  5. #include "http_server.h"
  6. #include "web_params_api.h"
  7. #include "parameters.h"
  8. #include "urlcode.h"
  9. #include "trap_params.h"
  10. #include "fsdata.c"
  11. #include "settings_api.h"
  12. #include "netconf.h"
  13. #include "common_config.h"
  14. //#include "testing.h"
  15. #include "rtc.h"
  16. #include "rng.h"
  17. #include "megatec.h"
  18. #ifdef PRINTF_STDLIB
  19. #include <stdio.h>
  20. #endif
  21. #ifdef PRINTF_CUSTOM
  22. #include "tinystdio.h"
  23. #endif
  24. #include <string.h>
  25. #include <stdlib.h>
  26. #include "FreeRTOS.h"
  27. #include "task.h"
  28. #include "timers.h"
  29. static int fs_open(char *name, struct fs_file *file);
  30. static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len);
  31. static void send_data(struct tcp_pcb *pcb, struct http_state *hs);
  32. static void HTTP_GetUserCookie(uint8_t user_id, char *str, uint8_t *len);
  33. static uint32_t Parse_Content_Length(char *data, uint32_t len);
  34. static void HTTP_SetUserCookie(char *str, uint8_t user_id);
  35. static void HTTP_UpdateUserLoginTime(uint8_t user_id);
  36. static void HTTP_ForceUserLogout(uint8_t user_id);
  37. void LogoutTimerCallback(TimerHandle_t pxTimer);
  38. int HTTP_ChangeUserPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut);
  39. SET_PAGE_t SET_PAGE = SET_PAGE_IDLE;
  40. #define SEND_BUF_MAX_LEN 2000
  41. #define RECIVE_BUF_MAX_LEN 1500
  42. char sendBuf[SEND_BUF_MAX_LEN];
  43. uint16_t sendBufLoadLen = 0;
  44. uint16_t printLen = 0;
  45. //char printBuf[1000];
  46. char receiveBuf[RECIVE_BUF_MAX_LEN];
  47. uint16_t receivedBufLen = 0;
  48. #define MAX_POST_REQ_LEN 256
  49. char post_req_data[MAX_POST_REQ_LEN];
  50. uint32_t post_data_count;
  51. uint32_t log_post_reqn;
  52. /* Logout timeout, 30 minutes */
  53. #define WEB_LOGOUT_TIME configTICK_RATE_HZ*60*30
  54. /* Max user active sessions count */
  55. #define WEB_USER_MAX_SESSION_COUNT 5
  56. typedef struct {
  57. char cookie[MAX_WEB_COOKIE_LEN];
  58. TimerHandle_t LogoutTimer;
  59. } auth_session_t;
  60. struct {
  61. //auth_session_t session[WEB_USER_MAX_SESSION_COUNT];
  62. char cookie[MAX_WEB_COOKIE_LEN];
  63. TimerHandle_t LogoutTimer;
  64. } users[MAX_WEB_USERS];
  65. bool Authenticated = false;
  66. /* Level of currently logged-in user */
  67. uint8_t seclevel = 0xFF;
  68. static uint32_t ContentLengthOffset =0;
  69. static const char Content_Length[17] =
  70. /* Content Length */
  71. {0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67,0x74, 0x68, 0x3a, 0x20, };
  72. const char HTTP_200_OK[] = "HTTP/1.1 200 OK\r\n\r\n";
  73. /**
  74. * @brief Общая структура настроек
  75. */
  76. SETTINGS_t sSettings;
  77. /**
  78. * @brief closes tcp connection
  79. * @param pcb: pointer to a tcp_pcb struct
  80. * @param hs: pointer to a http_state struct
  81. * @retval
  82. */
  83. static void close_conn(struct tcp_pcb *pcb, struct http_state *hs)
  84. {
  85. tcp_arg(pcb, NULL);
  86. tcp_sent(pcb, NULL);
  87. tcp_recv(pcb, NULL);
  88. mem_free(hs);
  89. tcp_close(pcb);
  90. }
  91. /**
  92. * @brief callback function for handling TCP HTTP traffic
  93. * @param arg: pointer to an argument structure to be passed to callback function
  94. * @param pcb: pointer to a tcp_pcb structure
  95. * @param p: pointer to a packet buffer
  96. * @param err: LwIP error code
  97. * @retval err
  98. */
  99. static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
  100. {
  101. char *data;
  102. struct http_state *hs;
  103. char CookieBuf[50];
  104. char *CookiePtr = NULL;
  105. char name[MAX_WEB_COOKIE_LEN];
  106. char id[MAX_WEB_COOKIE_LEN];
  107. uint8_t nameLen = 0, idLen = 0;
  108. struct fs_file file = {0, 0};
  109. hs = arg;
  110. if (err == ERR_OK && p != NULL)
  111. {
  112. tcp_recved(pcb, p->tot_len);
  113. if (hs->file == NULL)
  114. {
  115. data = p->payload;
  116. /*
  117. printLen = p->tot_len;
  118. memcpy(printBuf, p->payload , printLen);
  119. printf(printBuf);
  120. */
  121. receivedBufLen = p->tot_len;
  122. memcpy(receiveBuf, p->payload , receivedBufLen);
  123. receiveBuf[receivedBufLen] = '\0';
  124. // printf("receive %s \r\n", receiveBuf);
  125. /* Get cookie "uname" value */
  126. CookiePtr = strstr(receiveBuf, "uname=");
  127. strncpy(CookieBuf, CookiePtr, 50);
  128. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  129. memset(name, 0, MAX_WEB_COOKIE_LEN);
  130. GetCookieValue(CookieBuf, "uname=", name, &nameLen);
  131. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  132. //printf("********uname= %s\r\n", name);
  133. /* Get cookie "id" value */
  134. CookiePtr = strstr(receiveBuf, "id=");
  135. strncpy(CookieBuf, CookiePtr, 50);
  136. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  137. memset(id, 0, MAX_WEB_COOKIE_LEN);
  138. GetCookieValue(CookieBuf, "id=", id, &idLen);
  139. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  140. //printf("********id= %s\r\n", id);
  141. /* Id of currently logged-in user */
  142. uint8_t user_id;
  143. /* Level of currently logged-in user */
  144. seclevel = 0xFF;
  145. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  146. HTTP_GetUserCookie(user_id, CookieBuf, &idLen);
  147. if (strncmp(id, CookieBuf, idLen) == 0 ) {
  148. GetUserLevelInt(user_id, &seclevel);
  149. Authenticated = true;
  150. break;
  151. }
  152. Authenticated = false;
  153. seclevel = 0xFF;
  154. }
  155. if ( Authenticated == false )
  156. {
  157. if (strncmp(data, "GET /main.css", 13) == 0) // +
  158. {
  159. fs_open("/main.css", &file);
  160. hs->file = file.data;
  161. hs->left = file.len;
  162. send_data(pcb, hs);
  163. tcp_sent(pcb, http_sent);
  164. }
  165. else if (strncmp(data, "GET /rotek.png", 14) == 0) // +
  166. {
  167. fs_open("/rotek.png", &file);
  168. hs->file = file.data;
  169. hs->left = file.len;
  170. send_data(pcb, hs);
  171. tcp_sent(pcb, http_sent);
  172. }
  173. else if (strncmp(data, "GET /favicon.ico", 16) == 0) // ?
  174. {
  175. fs_open("/favicon.ico", &file);
  176. hs->file = file.data;
  177. hs->left = file.len;
  178. send_data(pcb, hs);
  179. tcp_sent(pcb, http_sent);
  180. }
  181. else if (strncmp(data, "GET /role.js", 12) == 0)
  182. {
  183. fs_open("/role.js", &file);
  184. hs->file = file.data;
  185. hs->left = file.len;
  186. send_data(pcb, hs);
  187. tcp_sent(pcb, http_sent);
  188. }
  189. else if ((strncmp(data, "POST /login.cgi", 15) == 0) || (log_post_reqn > 0))
  190. {
  191. uint32_t i, offset = 0, req_data_received = 0;
  192. //printf("request 1: %d\r\n", receivedBufLen);
  193. /* parse packet for Content-length field */
  194. post_data_count = Parse_Content_Length(data, p->tot_len);
  195. //printf("Content-length: %d\r\n", (int)post_data_count);
  196. if (post_data_count < MAX_POST_REQ_LEN) {
  197. memset(post_req_data, 0, MAX_POST_REQ_LEN);
  198. /* parse packet for "\r\n\r\n" */
  199. for (i = 0; i < receivedBufLen; i++)
  200. {
  201. if (strncmp ((char*)(data+i), "\r\n\r\n", 4) == 0)
  202. {
  203. offset = i+4;
  204. //printf("offset: %d\r\n", (int)offset);
  205. break;
  206. }
  207. }
  208. req_data_received = receivedBufLen - offset;
  209. //printf("req data received: %d\r\n", (int)req_data_received);
  210. /* Check if "\r\n\r\n" was found */
  211. if (offset != 0) {
  212. /* if data was splited in two packets */
  213. if (req_data_received < post_data_count) {
  214. /* Copy request data to buffer */
  215. snprintf(post_req_data, req_data_received, "%s", receiveBuf);
  216. //printf("copied: %d\r\n", (int)req_data_received);
  217. post_data_count -= req_data_received;
  218. }
  219. /* if data received completely */
  220. else {
  221. strncat(post_req_data, (char *)(data + offset), post_data_count);
  222. //printf("post_req_data: %s\r\n", post_req_data);
  223. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES) {
  224. hs->file = sendBuf;
  225. hs->left = sendBufLoadLen;
  226. send_data(pcb, hs);
  227. tcp_sent(pcb, http_sent);
  228. }
  229. else {
  230. /* Redirect to login page */
  231. fs_open("/login.html", &file);
  232. hs->file = file.data;
  233. hs->left = file.len;
  234. send_data(pcb, hs);
  235. tcp_sent(pcb, http_sent);
  236. }
  237. /* End reqest */
  238. post_data_count = 0;
  239. log_post_reqn = 0;
  240. }
  241. }
  242. /* request was fragmented before "\r\n\r\n" */
  243. else {
  244. //printf("no data found!\r\n");
  245. /* wait next packet */
  246. log_post_reqn++;
  247. /* wait max 2 requests */
  248. if (log_post_reqn > 1) {
  249. /* Redirect to login page */
  250. fs_open("/login.html", &file);
  251. hs->file = file.data;
  252. hs->left = file.len;
  253. send_data(pcb, hs);
  254. tcp_sent(pcb, http_sent);
  255. /* End reqest */
  256. post_data_count = 0;
  257. log_post_reqn = 0;
  258. }
  259. }
  260. }
  261. else {
  262. printf("Too long POST request!\r\n");
  263. /* Ignore request */
  264. post_data_count = 0;
  265. log_post_reqn = 0;
  266. /* Redirect to login page */
  267. fs_open("/login.html", &file);
  268. hs->file = file.data;
  269. hs->left = file.len;
  270. send_data(pcb, hs);
  271. tcp_sent(pcb, http_sent);
  272. }
  273. }
  274. else if (post_data_count > 0)
  275. {
  276. strncat(post_req_data, data, post_data_count);
  277. //printf("copied: %d\r\n", (int)post_data_count);
  278. //printf("post_req_data: %s\r\n", post_req_data);
  279. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES) {
  280. hs->file = sendBuf;
  281. hs->left = sendBufLoadLen;
  282. send_data(pcb, hs);
  283. tcp_sent(pcb, http_sent);
  284. }
  285. else {
  286. /* Redirect to login page */
  287. fs_open("/login.html", &file);
  288. hs->file = file.data;
  289. hs->left = file.len;
  290. send_data(pcb, hs);
  291. tcp_sent(pcb, http_sent);
  292. }
  293. /* End reqest */
  294. post_data_count = 0;
  295. log_post_reqn = 0;
  296. }
  297. else
  298. {
  299. fs_open("/login.html", &file);
  300. hs->file = file.data;
  301. hs->left = file.len;
  302. send_data(pcb, hs);
  303. tcp_sent(pcb, http_sent);
  304. }
  305. }
  306. else if ( Authenticated == true ) {
  307. if (strncmp(data, "GET /main.css", 13) == 0) // +
  308. {
  309. fs_open("/main.css", &file);
  310. hs->file = file.data;
  311. hs->left = file.len;
  312. send_data(pcb, hs);
  313. tcp_sent(pcb, http_sent);
  314. }
  315. else if (strncmp(data, "GET /rotek.png", 14) == 0) // +
  316. {
  317. fs_open("/rotek.png", &file);
  318. hs->file = file.data;
  319. hs->left = file.len;
  320. send_data(pcb, hs);
  321. tcp_sent(pcb, http_sent);
  322. }
  323. else if (strncmp(data, "GET /favicon.ico", 16) == 0) // ?
  324. {
  325. fs_open("/favicon.ico", &file);
  326. hs->file = file.data;
  327. hs->left = file.len;
  328. send_data(pcb, hs);
  329. tcp_sent(pcb, http_sent);
  330. }
  331. else if (strncmp(data, "GET /main.js", 12) == 0) // +
  332. {
  333. fs_open("/main.js", &file);
  334. hs->file = file.data;
  335. hs->left = file.len;
  336. send_data(pcb, hs);
  337. tcp_sent(pcb, http_sent);
  338. }
  339. else if (strncmp(data, "GET /role.js", 12) == 0)
  340. {
  341. fs_open("/role.js", &file);
  342. hs->file = file.data;
  343. hs->left = file.len;
  344. send_data(pcb, hs);
  345. tcp_sent(pcb, http_sent);
  346. }
  347. else if (strncmp(data, "GET /settings.html", 18) == 0) // +
  348. {
  349. HTTP_UpdateUserLoginTime(user_id);
  350. fs_open("/settings.html", &file);
  351. hs->file = file.data;
  352. hs->left = file.len;
  353. send_data(pcb, hs);
  354. tcp_sent(pcb, http_sent);
  355. }
  356. else if (strncmp(data, "GET /info.html", 14) == 0) // +
  357. {
  358. HTTP_UpdateUserLoginTime(user_id);
  359. fs_open("/info.html", &file);
  360. hs->file = file.data;
  361. hs->left = file.len;
  362. send_data(pcb, hs);
  363. tcp_sent(pcb, http_sent);
  364. }
  365. else if (strncmp(data, "GET /getJson.cgi", 16) == 0) // +
  366. {
  367. HTTP_GetParamsPage1(sendBuf);
  368. hs->file = sendBuf;
  369. hs->left = strlen(sendBuf);
  370. send_data(pcb, hs);
  371. tcp_sent(pcb, http_sent);
  372. }
  373. else if (strncmp(data, "GET /settings.cgi", 17) == 0) // +
  374. {
  375. SET_PAGE = SET_PAGE_PAGE2;
  376. if (HTTP_SettingsPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  377. {
  378. hs->file = sendBuf;
  379. hs->left = sendBufLoadLen;
  380. send_data(pcb, hs);
  381. tcp_sent(pcb, http_sent);
  382. }
  383. /*else
  384. {
  385. fs_open("/settings.html", &file);
  386. hs->file = file.data;
  387. hs->left = file.len;
  388. send_data(pcb, hs);
  389. tcp_sent(pcb, http_sent);
  390. }*/
  391. }
  392. else if (strncmp(data, "POST /settings.cgi", 18) == 0)
  393. {
  394. strncat(&receiveBuf, " ", 1);
  395. HTTP_SetSettings(receiveBuf, receivedBufLen);
  396. memset(sendBuf, 0, SEND_BUF_MAX_LEN);
  397. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  398. strcat(sendBuf, "\r\n\r\n");
  399. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/settings.html\"/></head></html>\r\n\r\n");
  400. sendBufLoadLen = strlen(sendBuf);
  401. hs->file = sendBuf;
  402. hs->left = sendBufLoadLen;
  403. send_data(pcb, hs);
  404. tcp_sent(pcb, http_sent);
  405. }
  406. else if (strncmp(data, "GET /info.cgi", 13) == 0) // +
  407. {
  408. if (HTTP_InfoPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  409. {
  410. hs->file = sendBuf;
  411. hs->left = sendBufLoadLen;
  412. send_data(pcb, hs);
  413. tcp_sent(pcb, http_sent);
  414. }
  415. else
  416. {
  417. fs_open("/info.html", &file);
  418. hs->file = file.data;
  419. hs->left = file.len;
  420. send_data(pcb, hs);
  421. tcp_sent(pcb, http_sent);
  422. }
  423. }
  424. /* Тест АКБ ИБП */
  425. else if (strncmp(data, "POST /bat_test.cgi", 18) == 0)
  426. {
  427. HTTP_UPSTest(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  428. hs->file = sendBuf;
  429. hs->left = sendBufLoadLen;
  430. send_data(pcb, hs);
  431. tcp_sent(pcb, http_sent);
  432. }
  433. /* Выключение ИБП */
  434. else if (strncmp(data, "POST /ups_power.cgi", 19) == 0)
  435. {
  436. HTTP_UPSshutdown(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  437. hs->file = sendBuf;
  438. hs->left = sendBufLoadLen;
  439. send_data(pcb, hs);
  440. tcp_sent(pcb, http_sent);
  441. }
  442. /* Сброс настроек и сохранине */
  443. else if (strncmp(data, "GET /reset.cgi", 14) == 0)
  444. {
  445. HTTP_ResetSettings();
  446. HTTP_SaveSettings();
  447. fs_open("/settings.html", &file);
  448. hs->file = file.data;
  449. hs->left = file.len;
  450. send_data(pcb, hs);
  451. tcp_sent(pcb, http_sent);
  452. }
  453. /* Перезагрузка контроллера */
  454. else if (strncmp(data, "GET /reboot.cgi", 15) == 0)
  455. {
  456. HTTP_Reboot();
  457. }
  458. /* Подтверждение новых сетевых настроек */
  459. else if (strncmp(data, "GET /confirm.cgi", 16) == 0)
  460. {
  461. SetWebReinitFlag(false);
  462. SetConfirmWebParamsFlag();
  463. fs_open("/index.html", &file);
  464. hs->file = file.data;
  465. hs->left = file.len;
  466. send_data(pcb, hs);
  467. tcp_sent(pcb, http_sent);
  468. }
  469. /* Проверка пароля, переход в bootloader */
  470. else if (strncmp(data, "POST /fw_update.cgi", 18) == 0)
  471. {
  472. HTTP_ConfirmBootPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  473. hs->file = sendBuf;
  474. hs->left = sendBufLoadLen;
  475. send_data(pcb, hs);
  476. tcp_sent(pcb, http_sent);
  477. }
  478. /* Смена пароля пользователя */
  479. else if (strncmp(data, "POST /changepwd.cgi", 19) == 0)
  480. {
  481. HTTP_ChangeUserPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  482. hs->file = sendBuf;
  483. hs->left = sendBufLoadLen;
  484. send_data(pcb, hs);
  485. tcp_sent(pcb, http_sent);
  486. }
  487. // На производстве
  488. else if (strncmp(data, "GET /setProdate.cgi", 19) == 0)
  489. {
  490. HTTP_Prodate(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  491. hs->file = sendBuf;
  492. hs->left = sendBufLoadLen;
  493. send_data(pcb, hs);
  494. tcp_sent(pcb, http_sent);
  495. }
  496. else
  497. {
  498. HTTP_UpdateUserLoginTime(user_id);
  499. fs_open("/index.html", &file); // +
  500. hs->file = file.data;
  501. hs->left = file.len;
  502. send_data(pcb, hs);
  503. tcp_sent(pcb, http_sent);
  504. }
  505. }
  506. }
  507. pbuf_free(p);
  508. close_conn(pcb,hs);
  509. }
  510. if (err == ERR_OK && p == NULL)
  511. {
  512. close_conn(pcb, hs);
  513. }
  514. return ERR_OK;
  515. }
  516. /**
  517. * @brief callback function for handling connection errors
  518. * @param arg: pointer to an argument to be passed to callback function
  519. * @param err: LwIP error code
  520. * @retval none
  521. */
  522. static void conn_err(void *arg, err_t err)
  523. {
  524. struct http_state *hs;
  525. hs = arg;
  526. mem_free(hs);
  527. }
  528. /**
  529. * @brief callback function called after a successfull TCP data packet transmission
  530. * @param arg: pointer to an argument to be passed to callback function
  531. * @param pcb: pointer on tcp_pcb structure
  532. * @param len
  533. * @retval err : LwIP error code
  534. */
  535. static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len)
  536. {
  537. struct http_state *hs;
  538. hs = arg;
  539. if (hs->left > 0)
  540. {
  541. send_data(pcb, hs);
  542. }
  543. else
  544. {
  545. close_conn(pcb, hs);
  546. }
  547. return ERR_OK;
  548. }
  549. /**
  550. * @brief sends data found in member "file" of a http_state struct
  551. * @param pcb: pointer to a tcp_pcb struct
  552. * @param hs: pointer to a http_state struct
  553. * @retval none
  554. */
  555. static void send_data(struct tcp_pcb *pcb, struct http_state *hs)
  556. {
  557. err_t err;
  558. u16_t len;
  559. /* We cannot send more data than space available in the send
  560. buffer */
  561. if (tcp_sndbuf(pcb) < hs->left)
  562. {
  563. len = tcp_sndbuf(pcb);
  564. }
  565. else
  566. {
  567. len = hs->left;
  568. }
  569. err = tcp_write(pcb, hs->file, len, 0);
  570. if (err == ERR_OK)
  571. {
  572. hs->file += len;
  573. hs->left -= len;
  574. }
  575. }
  576. /**
  577. * @brief tcp poll callback function
  578. * @param arg: pointer to an argument to be passed to callback function
  579. * @param pcb: pointer on tcp_pcb structure
  580. * @retval err_t
  581. */
  582. static err_t http_poll(void *arg, struct tcp_pcb *pcb)
  583. {
  584. if (arg == NULL)
  585. {
  586. tcp_close(pcb);
  587. }
  588. else
  589. {
  590. send_data(pcb, (struct http_state *)arg);
  591. }
  592. return ERR_OK;
  593. }
  594. /**
  595. * @brief callback function on TCP connection setup ( on port 80)
  596. * @param arg: pointer to an argument structure to be passed to callback function
  597. * @param pcb: pointer to a tcp_pcb structure
  598. * &param err: Lwip stack error code
  599. * @retval err
  600. */
  601. static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err)
  602. {
  603. struct http_state *hs;
  604. /* Allocate memory for the structure that holds the state of the connection */
  605. hs = mem_malloc(sizeof(struct http_state));
  606. if (hs == NULL)
  607. {
  608. return ERR_MEM;
  609. }
  610. /* Initialize the structure. */
  611. hs->file = NULL;
  612. hs->left = 0;
  613. /* Tell TCP that this is the structure we wish to be passed for our
  614. callbacks. */
  615. tcp_arg(pcb, hs);
  616. /* Tell TCP that we wish to be informed of incoming data by a call
  617. to the http_recv() function. */
  618. tcp_recv(pcb, http_recv);
  619. tcp_err(pcb, conn_err);
  620. tcp_poll(pcb, http_poll, 10);
  621. return ERR_OK;
  622. }
  623. /**
  624. * @brief Opens a file defined in fsdata.c ROM filesystem
  625. * @param name : pointer to a file name
  626. * @param file : pointer to a fs_file structure
  627. * @retval 1 if success, 0 if fail
  628. */
  629. static int fs_open(char *name, struct fs_file *file)
  630. {
  631. struct fsdata_file_noconst *f;
  632. for (f = (struct fsdata_file_noconst *)FS_ROOT; f != NULL; f = (struct fsdata_file_noconst *)f->next)
  633. {
  634. if (!strcmp(name, f->name))
  635. {
  636. file->data = f->data;
  637. file->len = f->len;
  638. return 1;
  639. }
  640. }
  641. return 0;
  642. }
  643. /**
  644. * @brief Initialize the HTTP server (start its thread)
  645. * @param none
  646. * @retval None
  647. */
  648. void HTTP_Init()
  649. {
  650. char buf[MAX_WEB_COOKIE_LEN];
  651. uint8_t user_id;
  652. //sys_thread_new("HTTP", http_server_netconn_thread, NULL, 3000, 2);
  653. struct tcp_pcb *pcb;
  654. /*create new pcb*/
  655. pcb = tcp_new();
  656. /* bind HTTP traffic to pcb */
  657. tcp_bind(pcb, IP_ADDR_ANY, 80);
  658. /* start listening on port 80 */
  659. pcb = tcp_listen(pcb);
  660. /* define callback function for TCP connection setup */
  661. tcp_accept(pcb, http_accept);
  662. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  663. /* Flush user cookie by random value */
  664. sprintf(buf, "%X", (unsigned int)GetRandomNumber());
  665. HTTP_SetUserCookie(buf, user_id);
  666. /* Create user logout timers */
  667. users[user_id].LogoutTimer =
  668. xTimerCreate("LogoutTmr", WEB_LOGOUT_TIME, pdFALSE, ( void * ) user_id, LogoutTimerCallback);
  669. }
  670. }
  671. /**
  672. * @brief
  673. * @retval None
  674. */
  675. int HTTP_SettingsPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  676. {
  677. char tempStr[30];
  678. strncpy(tempStr, bufIn, 30);
  679. /* В запросе нет параметров, нужно формировать JSON ответ */
  680. if (strpbrk(tempStr,"?") == 0)
  681. {
  682. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  683. HTTP_GetSettings(bufOut);
  684. //printf(bufOut);
  685. *lenBufOut = strlen(bufOut);
  686. return SEND_REQUIRED_YES;
  687. }
  688. /* В запросе есть параметры, нужно парсить и сохранять настройки */
  689. else
  690. {
  691. HTTP_SetSettings(bufIn, lenBufIn);
  692. return SEND_REQUIRED_NO;
  693. }
  694. }
  695. /**
  696. * @brief
  697. * @retval None
  698. */
  699. int HTTP_InfoPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  700. {
  701. char tempStr[30];
  702. strncpy(tempStr, bufIn, 30);
  703. /* В запросе нет параметров, нужно формировать JSON ответ */
  704. if (strpbrk(tempStr,"?") == 0)
  705. {
  706. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  707. HTTP_GetInfo(bufOut);
  708. *lenBufOut = strlen(bufOut);
  709. return SEND_REQUIRED_YES;
  710. }
  711. /* В запросе есть параметры, нужно парсить и сохранять настройки */
  712. else
  713. {
  714. HTTP_SetInfo(bufIn, lenBufIn);
  715. return SEND_REQUIRED_NO;
  716. /*
  717. HTTP_SetSettings(bufIn, lenBufIn);
  718. return SEND_REQUIRED_NO;
  719. */
  720. }
  721. }
  722. /**
  723. * @brief Установка даты производства
  724. */
  725. // TODO Убрать заглушку!
  726. void HTTP_Prodate(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  727. {
  728. uint8_t valueLen = 0;
  729. char value[20];
  730. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  731. ClearParamString(bufIn);
  732. memset(value, 0, 20);
  733. GetParamValue(bufIn, "prodate=", value, &valueLen);
  734. /*
  735. printf("Prodate: ");
  736. printf(value);
  737. printf("\r\n");
  738. */
  739. /* Устанавливаем дату производства */
  740. SETTINGS_SetProDate(value, valueLen);
  741. /* Устанавливаем дату следующей профилактики +1 год */
  742. RTC_SetProfTime(value);
  743. /* Пока отправляем true */
  744. strcpy(bufOut, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\n\r\nTrue");
  745. *lenBufOut = strlen(bufOut);
  746. // TEST_SetServerFlag();
  747. }
  748. /**
  749. * @brief
  750. * @retval None
  751. */
  752. void HTTP_SetSettings(char *buf, uint16_t lenBuf)
  753. {
  754. uint8_t valueLen = 0;
  755. const uint8_t len = MAX_WEB_PARAM_LEN;
  756. char value[MAX_WEB_PARAM_LEN];
  757. char str[MAX_WEB_PARAM_LEN];
  758. //printf(buf);
  759. //ClearParamString(buf);
  760. memset(value, 0, len);
  761. memset(str, 0, MAX_WEB_PARAM_LEN);
  762. /* SNMP */
  763. GetParamValue(buf, "read_community=", value, &valueLen);
  764. SetReadCommunity(value);
  765. memset(value, 0, len);
  766. GetParamValue(buf, "write_community=", value, &valueLen);
  767. SetWriteCommunity(value);
  768. memset(value, 0, len);
  769. GetParamValue(buf, "managerIP=", value, &valueLen);
  770. SetManagerIp(value);
  771. memset(value, 0, len);
  772. GetParamValue(buf, "managerIP2=", value, &valueLen);
  773. SetManagerIp2(value);
  774. memset(value, 0, len);
  775. GetParamValue(buf, "managerIP3=", value, &valueLen);
  776. SetManagerIp3(value);
  777. memset(value, 0, len);
  778. GetParamValue(buf, "managerIP4=", value, &valueLen);
  779. SetManagerIp4(value);
  780. memset(value, 0, len);
  781. GetParamValue(buf, "managerIP5=", value, &valueLen);
  782. SetManagerIp5(value);
  783. memset(value, 0, len);
  784. /* Сетевые параметры */
  785. GetParamValue(buf, "dhcp=", value, &valueLen);
  786. SetDhcpStateStr(value);
  787. if (strncmp(value, "on", 2) != 0) // Если dhcp off устанавливаем параметры
  788. {
  789. memset(value, 0, len);
  790. GetParamValue(buf, "ipaddr=", value, &valueLen);
  791. SetIPStr(value);
  792. memset(value, 0, len);
  793. GetParamValue(buf, "gw=", value, &valueLen);
  794. SetGatewayStr(value);
  795. memset(value, 0, len);
  796. GetParamValue(buf, "mask=", value, &valueLen);
  797. SetMaskStr(value);
  798. memset(value, 0, len);
  799. }
  800. memset(value, 0, len);
  801. /* параметры RADIUS*/
  802. GetParamValue(buf, "rs_enabled=", value, &valueLen);
  803. SetRDSEnableStateStr(value);
  804. memset(value, 0, len);
  805. GetParamValue(buf, "rs_server=", value, &valueLen);
  806. SetRDSIpStr(value);
  807. memset(value, 0, len);
  808. GetParamValue(buf, "rs_port=", value, &valueLen);
  809. SetRDSPortStr(value);
  810. memset(value, 0, len);
  811. GetParamValue(buf, "rs_pwd=", value, &valueLen);
  812. SetRDSPasswordkStr(value);
  813. memset(value, 0, len);
  814. GetParamValue(buf, "rs_key=", value, &valueLen);
  815. SetRDSKeyAccesstStr(value);
  816. memset(value, 0, len);
  817. // Параметры реле и сухих контактов
  818. GetParamValue(buf, "di1=", value, &valueLen);
  819. SetDINTypeActStr(value, 0);
  820. memset(value, 0, len);
  821. GetParamValue(buf, "ro1=", value, &valueLen);
  822. SetROTypeActStr(value, 0);
  823. memset(value, 0, len);
  824. GetParamValue(buf, "ro2=", value, &valueLen);
  825. SetROTypeActStr(value, 1);
  826. memset(value, 0, len);
  827. // Параметры даты и времени
  828. GetParamValue(buf, "ntp=", value, &valueLen);
  829. SetSntpStateStr(value);
  830. if (strncmp(value, "1", 1) == 0) // Если ntp on устанавливаем параметры
  831. {
  832. memset(value, 0, len);
  833. GetParamValue(buf, "ntpservip=", value, &valueLen);
  834. SetSntpServerIpStr(value);
  835. memset(value, 0, len);
  836. }
  837. else if (strncmp(value, "0", 1) == 0){
  838. GetParamValue(buf, "date=", value, &valueLen);
  839. SetDateStr(value);
  840. memset(value, 0, len);
  841. GetParamValue(buf, "time=", value, &valueLen);
  842. url_decode(str, sizeof(str), value);
  843. SetTimeStr(str);
  844. memset(value, 0, len);
  845. }
  846. GetParamValue(buf, "utc=", value, &valueLen);
  847. SetSntpTimeZoneStr(value);
  848. memset(value, 0, len);
  849. /* Если параметры WEB изменились выставляем флаг, сохраняем настройки и перезагружаемся */
  850. if (GetStateWebReinit() == true)
  851. {
  852. SetWebReinitFlag(true);
  853. HTTP_SaveSettings();
  854. /* Блокируем управление ключем на тау секунд*/
  855. //IO_KeyBlockOn();
  856. vTaskDelay(1010);
  857. NVIC_SystemReset();
  858. }
  859. HTTP_SaveSettings();
  860. }
  861. /**
  862. * @brief
  863. * @retval None
  864. */
  865. void HTTP_SetInfo(char *buf, uint16_t lenBuf)
  866. {
  867. uint8_t valueLen = 0;
  868. const uint8_t len = 110;
  869. char value[110];
  870. ClearParamString(buf);
  871. memset(value, 0, len);
  872. /* Владелец */
  873. GetParamValue(buf, "owner=", value, &valueLen);
  874. HTTP_ReplaceSimbol(value, '+', ' ');
  875. SetOwner(value);
  876. memset(value, 0, len);
  877. /* Владелец */
  878. GetParamValue(buf, "sysLocation=", value, &valueLen);
  879. HTTP_ReplaceSimbol(value, '+', ' ');
  880. SetLocation(value);
  881. memset(value, 0, len);
  882. /* Комментарий */
  883. GetParamValue(buf, "comment=", value, &valueLen);
  884. HTTP_ReplaceSimbol(value, '+', ' ');
  885. SetComment(value);
  886. memset(value, 0, len);
  887. HTTP_SaveSettings();
  888. }
  889. /**
  890. * @brief Запуск/останов теста UPS
  891. */
  892. void HTTP_UPSTest(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  893. {
  894. char *value = 0;
  895. char *valueLen = 0;
  896. char tempValue[20];
  897. char tempValue2[20];
  898. int8_t res = 0;
  899. memset(tempValue, 0, 20);
  900. memset(tempValue2, 0, 20);
  901. strcpy(bufOut, HTTP_200_OK);
  902. value = strstr(bufIn, "func");
  903. valueLen = strpbrk(value, ":");
  904. strncpy(tempValue, (valueLen+1), (strlen(valueLen)-2));
  905. if (strcmp(tempValue, "\"stop\"") == 0){
  906. res = ups_metac_service_pdu(ups_cancel_test);
  907. if(res == 1 || res == 0)
  908. strcat(bufOut, "Тест остановлен!");
  909. if(res == -1)
  910. strcat(bufOut, "Тест не удалось остановить!");
  911. *lenBufOut = strlen(bufOut);
  912. }
  913. else if (strcmp(tempValue, "\"discharge\"") == 0){
  914. res = ups_metac_service_pdu(ups_test_low_bat);
  915. if(res == 1 || res == 0)
  916. strcat(bufOut, "Тест запущен!");
  917. if(res == -1)
  918. strcat(bufOut, "Тест не удалось запустить!");
  919. *lenBufOut = strlen(bufOut);
  920. }
  921. else if (strncmp(tempValue, "\"time\"", 6) == 0){
  922. valueLen = strpbrk(tempValue, ":");
  923. strncpy(tempValue2, (valueLen+2), (strlen(valueLen)-2));
  924. TimeParam = atoi(tempValue2);
  925. res = ups_metac_service_pdu(ups_test_time);
  926. if(res == 1 || res == 0)
  927. strcat(bufOut, "Тест запущен!");
  928. if(res == -1)
  929. strcat(bufOut, "Тест не удалось запустить!");
  930. *lenBufOut = strlen(bufOut);
  931. }
  932. }
  933. /**
  934. * @brief Выклюение UPS
  935. */
  936. void HTTP_UPSshutdown(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  937. {
  938. char *value = 0;
  939. char *valueLen = 0;
  940. char *valueLenEnd = 0;
  941. char tempValue[50];
  942. char tempValue2[50];
  943. int8_t res = 0;
  944. memset(tempValue, 0, 50);
  945. strcpy(bufOut, HTTP_200_OK);
  946. value = strstr(bufIn, "func");
  947. valueLen = strpbrk(value, ":");
  948. strncpy(tempValue, (valueLen+1), (strlen(valueLen)-2));
  949. if (strcmp(tempValue, "\"cancel\"") == 0){
  950. res = ups_metac_service_pdu(ups_cancel_shut_down);
  951. if(res == 1 || res == 0)
  952. strcat(bufOut, "Выключение ИБП отменено!");
  953. if(res == -1)
  954. strcat(bufOut, "Выключение ИБП не удалось отменить!");
  955. *lenBufOut = strlen(bufOut);
  956. }
  957. else if (strncmp(tempValue, "\"off\"", 5) == 0){
  958. value = strstr(tempValue, "after");
  959. valueLen = strpbrk(value, ":");
  960. valueLenEnd = strpbrk(value, ",");
  961. memset(tempValue2, 0, 50);
  962. strncpy(tempValue2, (valueLen+2), (valueLenEnd - valueLen - 2));
  963. TimeParam = atoi(tempValue2);
  964. value = strstr(tempValue, "to");
  965. valueLen = strpbrk(value, ":");
  966. memset(tempValue2, 0, 50);
  967. strncpy(tempValue2, (valueLen+2), (strlen(valueLen) - 2));
  968. TimeParam2 = atoi(tempValue2);
  969. res = ups_metac_service_pdu(ups_shutdown_restore);
  970. if(res == 1 || res == 0)
  971. strcat(bufOut, "Перезагрузка ИБП!");
  972. if(res == -1)
  973. strcat(bufOut, "Отмена перезагрузки ИБП!");
  974. *lenBufOut = strlen(bufOut);
  975. }
  976. }
  977. /**
  978. * @brief Проверка пароля для перехода в режим bootloader
  979. * @retval None
  980. */
  981. void HTTP_ConfirmBootPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  982. {
  983. char tempStr[50];
  984. strncpy(tempStr, bufIn, 50);
  985. char value[20];
  986. uint8_t valueLen;
  987. memset(value, 0, 20);
  988. //if (GetParamValue(tempStr, "password=", value, &valueLen))
  989. {
  990. //if (strcmp(BOOTLOADER_PASWORD, value) == 0)
  991. {
  992. // *bufOut = '1';
  993. /* Запускаем задачу отложенной перезагрузки. Контроллер должен успеть
  994. отправить ответ серверу о статусе пароля */
  995. HTTP_StartResetTask(true);
  996. }
  997. /* else
  998. *bufOut = '0';*/
  999. //*lenBufOut = 1;
  1000. }
  1001. }
  1002. /**
  1003. * @brief Проверка пароля для входа в Web
  1004. * @retval None
  1005. */
  1006. int HTTP_ConfirmWebPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1007. {
  1008. char tempStr[50];
  1009. char login[20];
  1010. char password[20];
  1011. uint8_t valueLen, user_id;
  1012. char *strPtr = 0;
  1013. char WebPassword[MAX_WEB_PASSWD_LEN];
  1014. char WebLogin[MAX_WEB_LOGIN_LEN];
  1015. char buf[40];
  1016. memset(login, 0, 20);
  1017. memset(password, 0, 20);
  1018. memset(tempStr, 0, 50);
  1019. /* Get first 50 bytes of string */
  1020. strncpy(tempStr, bufIn, 49);
  1021. /* Add " " to the string in order GetParamValue() can be able to parse the param */
  1022. strcat(tempStr, " ");
  1023. if (GetParamValue(tempStr, "login=", login, &valueLen) &&
  1024. GetParamValue(tempStr, "password=", password, &valueLen))
  1025. {
  1026. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  1027. GetUserLogin(user_id, WebLogin, &valueLen);
  1028. GetUserPassword(user_id, WebPassword, &valueLen);
  1029. /* Check login and password */
  1030. if ((strncmp(WebLogin, login, MAX_WEB_LOGIN_LEN) == 0) &&
  1031. (strncmp(WebPassword, password, MAX_WEB_PASSWD_LEN) == 0)) {
  1032. /* Login and pass are valid */
  1033. /* Check user's login session */
  1034. /* If "user" has logged in */
  1035. if (user_id >= 1) {
  1036. }
  1037. /* TODO replace global flag with user-pass-cookie */
  1038. Authenticated = true;
  1039. /* Generate cookie */
  1040. sprintf(tempStr, "%X", (unsigned int)GetRandomNumber());
  1041. /* Set users cookie */
  1042. HTTP_SetUserCookie(tempStr, user_id);
  1043. HTTP_UpdateUserLoginTime(user_id);
  1044. /* Send login and cookie back */
  1045. strcpy(bufOut, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\nSet-Cookie: uname=");
  1046. strcat(bufOut, WebLogin);
  1047. strcat(bufOut, "\r\nSet-Cookie: id=");
  1048. strcat(bufOut, tempStr);
  1049. sprintf(tempStr, "%d", user_id);
  1050. strcat(bufOut, "\r\nSet-Cookie: role=");
  1051. strcat(bufOut, tempStr);
  1052. strcat(bufOut, "\r\n\r\n");
  1053. strcat(bufOut,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/index.html\"/></head></html>\r\n\r\n");
  1054. *lenBufOut = strlen(bufOut);
  1055. switch (user_id) {
  1056. case 0:
  1057. snprintf(buf, sizeof(buf), "Администратор");
  1058. break;
  1059. case 1:
  1060. snprintf(buf, sizeof(buf), "Пользователь");
  1061. break;
  1062. default:
  1063. snprintf(buf, sizeof(buf), "", login);
  1064. break;
  1065. }
  1066. /* Запускаем задачу-таймер логаута. */
  1067. /* TODO отправить ответ серверу о статусе пароля */
  1068. return SEND_REQUIRED_YES;
  1069. }
  1070. /*
  1071. else {
  1072. continue;
  1073. }
  1074. */
  1075. }
  1076. }
  1077. /* No valid login and pass found */
  1078. /* TODO replace global flag with user-pass-cookie*/
  1079. Authenticated = false;
  1080. /* Wrong login or pass, return */
  1081. return SEND_REQUIRED_NO;
  1082. }
  1083. /**
  1084. * @brief
  1085. * @retval None
  1086. */
  1087. uint8_t GetParamValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1088. {
  1089. char *beginValue = 0;
  1090. char *endValue = 0;
  1091. int len = 0;
  1092. char *strPtr = 0;
  1093. strPtr = strstr(inStr, paramName);
  1094. if (strPtr != 0)
  1095. {
  1096. beginValue = strpbrk(strPtr,"=");
  1097. endValue = strpbrk(strPtr,"&");
  1098. if (endValue == 0)
  1099. endValue = strpbrk(strPtr," ");
  1100. len = endValue - beginValue - 1;
  1101. strncpy(paramValue, beginValue + 1, len);
  1102. *endValue = '0';
  1103. *beginValue = '0';
  1104. *paramLen = len;
  1105. return 1;
  1106. }
  1107. else
  1108. {
  1109. *paramLen = 0;
  1110. return 0;
  1111. }
  1112. }
  1113. /**
  1114. * @brief
  1115. * @retval None
  1116. */
  1117. uint8_t GetCookieValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1118. {
  1119. char *beginValue = 0;
  1120. char *endValue = 0;
  1121. int len = 0;
  1122. char *strPtr = 0;
  1123. strPtr = strstr(inStr, paramName);
  1124. if (strPtr != 0)
  1125. {
  1126. beginValue = strpbrk(strPtr,"=");
  1127. endValue = strpbrk(strPtr,";");
  1128. if (endValue == 0)
  1129. endValue = strpbrk(strPtr,"\n");
  1130. len = endValue - beginValue - 1;
  1131. strncpy(paramValue, beginValue + 1, len);
  1132. *endValue = '0';
  1133. *beginValue = '0';
  1134. *paramLen = len;
  1135. return 1;
  1136. }
  1137. else
  1138. {
  1139. *paramLen = 0;
  1140. return 0;
  1141. }
  1142. }
  1143. /**
  1144. * @brief
  1145. * @retval None
  1146. */
  1147. /*
  1148. uint8_t GetParamValueInEnd(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1149. {
  1150. char *beginValue = 0;
  1151. char *endValue = 0;
  1152. int len = 0;
  1153. char *strPtr = 0;
  1154. strPtr = strstr(inStr, paramName);
  1155. if (strPtr != 0)
  1156. {
  1157. beginValue = strpbrk(strPtr,"=");
  1158. endValue = strpbrk(strPtr," ");
  1159. len = endValue - beginValue - 1;
  1160. strncpy(paramValue, beginValue + 1, len);
  1161. *endValue = '0';
  1162. *beginValue = '0';
  1163. *paramLen = len;
  1164. return 1;
  1165. }
  1166. else
  1167. {
  1168. *paramLen = 0;
  1169. return 0;
  1170. }
  1171. }
  1172. */
  1173. void ClearParamString(char *inBuf)
  1174. {
  1175. uint16_t len;
  1176. char *str;
  1177. str = strstr(inBuf, "HTTP");
  1178. if (str != 0)
  1179. {
  1180. len = str - inBuf;
  1181. memset(str, 0, RECIVE_BUF_MAX_LEN - len - 1);
  1182. }
  1183. }
  1184. /**
  1185. * @brief Замена символа в строке
  1186. * @param *str - входная строка
  1187. * @param sim1 - символ который надо заменить
  1188. * @param sim2 - символ на который надо заменить
  1189. */
  1190. void HTTP_ReplaceSimbol(char *str, char sim1, char sim2)
  1191. {
  1192. uint16_t len = strlen(str);
  1193. for (uint16_t i = 0; i < len; i++)
  1194. {
  1195. if (*str == sim1)
  1196. *str = sim2;
  1197. str++;
  1198. }
  1199. }
  1200. /**
  1201. * @brief Чтение Cookie пользователя
  1202. */
  1203. static void HTTP_GetUserCookie(uint8_t user_id, char *str, uint8_t *len)
  1204. {
  1205. sprintf(str, "%s", users[user_id].cookie);
  1206. *len = strlen(str);
  1207. }
  1208. /**
  1209. * @brief Установка Cookie пользователя
  1210. */
  1211. static void HTTP_SetUserCookie(char *str, uint8_t user_id)
  1212. {
  1213. strcpy(users[user_id].cookie, str);
  1214. }
  1215. /**
  1216. * @brief Обновление времени последней активности пользователя
  1217. */
  1218. static void HTTP_UpdateUserLoginTime(uint8_t user_id)
  1219. {
  1220. xTimerStart(users[user_id].LogoutTimer, 0);
  1221. }
  1222. /**
  1223. * @brief Extract the Content_Length data from HTML data
  1224. * @param data : pointer on receive packet buffer
  1225. * @param len : buffer length
  1226. * @retval size : Content_length in numeric format
  1227. */
  1228. static uint32_t Parse_Content_Length(char *data, uint32_t len)
  1229. {
  1230. uint32_t i=0,size=0, S=1;
  1231. int32_t j=0;
  1232. char sizestring[6], *ptr;
  1233. ContentLengthOffset =0;
  1234. /* find Content-Length data in packet buffer */
  1235. for (i=0;i<len;i++)
  1236. {
  1237. if (strncmp ((char*)(data+i), Content_Length, 16)==0)
  1238. {
  1239. ContentLengthOffset = i+16;
  1240. break;
  1241. }
  1242. }
  1243. /* read Content-Length value */
  1244. if (ContentLengthOffset)
  1245. {
  1246. i=0;
  1247. ptr = (char*)(data + ContentLengthOffset);
  1248. while(*(ptr+i)!=0x0d)
  1249. {
  1250. sizestring[i] = *(ptr+i);
  1251. i++;
  1252. ContentLengthOffset++;
  1253. }
  1254. if (i>0)
  1255. {
  1256. /* transform string data into numeric format */
  1257. for(j=i-1;j>=0;j--)
  1258. {
  1259. size += (sizestring[j]-0x30)*S;
  1260. S=S*10;
  1261. }
  1262. }
  1263. }
  1264. return size;
  1265. }
  1266. /**
  1267. * @brief Принудительный логаут пользователя
  1268. */
  1269. static void HTTP_ForceUserLogout(uint8_t user_id)
  1270. {
  1271. char cookie[MAX_WEB_COOKIE_LEN];
  1272. /* Flush user cookie by random value */
  1273. sprintf(cookie, "%X", (unsigned int)GetRandomNumber());
  1274. HTTP_SetUserCookie(cookie, user_id);
  1275. }
  1276. /**
  1277. * @brief >Callback таймера логаута пользователя
  1278. */
  1279. void LogoutTimerCallback(TimerHandle_t pxTimer) {
  1280. uint8_t user_id = (uint8_t)pvTimerGetTimerID( pxTimer );
  1281. HTTP_ForceUserLogout(user_id);
  1282. }
  1283. /**
  1284. * @brief Смена пароля пользователя
  1285. * @retval None
  1286. */
  1287. int HTTP_ChangeUserPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1288. {
  1289. char tempStr[110];
  1290. char value[20];
  1291. char login[20];
  1292. char password[20];
  1293. uint8_t valueLen, valueLen2, user_id;
  1294. char WebLogin[MAX_WEB_LOGIN_LEN];
  1295. (void)lenBufIn;
  1296. memset(login, 0, 20);
  1297. memset(password, 0, 20);
  1298. memset(tempStr, 0, 50);
  1299. memset(value, 0, 20);
  1300. ClearParamString(bufIn);
  1301. strncpy(tempStr, bufIn, 110);
  1302. strcpy(bufOut, HTTP_200_OK);
  1303. if (GetParamValue(tempStr, "username=", login, &valueLen) &&
  1304. GetParamValue(tempStr, "oldpass=", password, &valueLen))
  1305. {
  1306. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++)
  1307. {
  1308. memset(value, 0, 20);
  1309. memset(WebLogin, 0, MAX_WEB_LOGIN_LEN);
  1310. GetUserLogin(user_id, WebLogin, &valueLen);
  1311. GetUserPassword(user_id, value, &valueLen2);
  1312. /* Check login and password */
  1313. if ((strncmp(WebLogin, login, MAX_WEB_LOGIN_LEN) == 0) &&
  1314. (memcmp(password, value, 11) == 0))
  1315. {
  1316. memset(password, 0, 20);
  1317. if (GetParamValue(tempStr, "newpass=", password, &valueLen))
  1318. {
  1319. memcpy(sSettings.sAuth[user_id].password, password, 11);
  1320. HTTP_SaveSettings();
  1321. strcat(bufOut, "Пароль успешно изменён");
  1322. *lenBufOut = strlen(bufOut);
  1323. return SEND_REQUIRED_YES;
  1324. }
  1325. else {
  1326. strcat(bufOut, "Введены некорректные данные!");
  1327. *lenBufOut = strlen(bufOut);
  1328. return SEND_REQUIRED_YES;
  1329. }
  1330. }
  1331. }
  1332. strcat(bufOut, "Введён неверный пароль!");
  1333. *lenBufOut = strlen(bufOut);
  1334. return SEND_REQUIRED_YES;
  1335. }
  1336. else {
  1337. strcat(bufOut, "Введены некорректные данные!");
  1338. *lenBufOut = strlen(bufOut);
  1339. return SEND_REQUIRED_YES;
  1340. }
  1341. }