http_server.c 43 KB

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