http_server.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883
  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. #include "log.h"
  19. #include "hal.h"
  20. #ifdef PRINTF_STDLIB
  21. #include <stdio.h>
  22. #endif
  23. #ifdef PRINTF_CUSTOM
  24. #include "tinystdio.h"
  25. #endif
  26. #include <string.h>
  27. #include <stdlib.h>
  28. #include "FreeRTOS.h"
  29. #include "task.h"
  30. #include "fr_timers.h"
  31. static int fs_open(char *name, struct fs_file *file);
  32. static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len);
  33. static err_t http_sent_history(void *arg, struct tcp_pcb *pcb, u16_t len);
  34. static err_t http_sent_log(void *arg, struct tcp_pcb *pcb, u16_t len);
  35. static void http_sent_log_err(void * arg, err_t err);
  36. static void send_data(struct tcp_pcb *pcb, struct http_state *hs);
  37. static void HTTP_GetUserCookie(uint8_t user_id, char *str, uint8_t *len);
  38. static uint32_t Parse_Content_Length(char *data, uint32_t len);
  39. static void HTTP_SetUserCookie(char *str, uint8_t user_id);
  40. static void HTTP_UpdateUserLoginTime(uint8_t user_id);
  41. static void HTTP_ForceUserLogout(uint8_t user_id);
  42. void LogoutTimerCallback(TimerHandle_t pxTimer);
  43. int HTTP_ChangeUserPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut);
  44. SET_PAGE_t SET_PAGE = SET_PAGE_IDLE;
  45. #define SEND_BUF_MAX_LEN 2000
  46. #define RECIVE_BUF_MAX_LEN 1500
  47. char sendBuf[SEND_BUF_MAX_LEN];
  48. uint16_t sendBufLoadLen = 0;
  49. uint16_t printLen = 0;
  50. //char printBuf[1000];
  51. char receiveBuf[RECIVE_BUF_MAX_LEN];
  52. uint16_t receivedBufLen = 0;
  53. #define MAX_POST_REQ_LEN 256
  54. char post_req_data[MAX_POST_REQ_LEN];
  55. uint32_t post_data_count;
  56. uint32_t log_post_reqn;
  57. /* Logout timeout, 30 minutes */
  58. #define WEB_LOGOUT_TIME configTICK_RATE_HZ*60*30
  59. /* Max user active sessions count */
  60. #define WEB_USER_MAX_SESSION_COUNT 5
  61. typedef struct {
  62. char cookie[MAX_WEB_COOKIE_LEN];
  63. TimerHandle_t LogoutTimer;
  64. } auth_session_t;
  65. struct {
  66. //auth_session_t session[WEB_USER_MAX_SESSION_COUNT];
  67. char cookie[MAX_WEB_COOKIE_LEN];
  68. TimerHandle_t LogoutTimer;
  69. } users[MAX_WEB_USERS];
  70. bool Authenticated = false;
  71. /* Level of currently logged-in user */
  72. uint8_t seclevel = 0xFF;
  73. static uint32_t ContentLengthOffset =0;
  74. static const char Content_Length[17] =
  75. /* Content Length */
  76. {0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67,0x74, 0x68, 0x3a, 0x20, };
  77. const char HTTP_200_OK[] = "HTTP/1.1 200 OK\r\n\r\n";
  78. /* utf-8 marker to support MS Excel */
  79. const char UTF8_BOM[] = {0xEF, 0xBB, 0xBF, 0x00};
  80. unsigned long log_ptr = 0;
  81. unsigned long log_size = 0;
  82. bool fLogTransInprog = false;
  83. /**
  84. * @brief Общая структура настроек
  85. */
  86. extern SETTINGS_t sSettings;
  87. /**
  88. * @brief closes tcp connection
  89. * @param pcb: pointer to a tcp_pcb struct
  90. * @param hs: pointer to a http_state struct
  91. * @retval
  92. */
  93. static void close_conn(struct tcp_pcb *pcb, struct http_state *hs)
  94. {
  95. tcp_arg(pcb, NULL);
  96. tcp_sent(pcb, NULL);
  97. tcp_recv(pcb, NULL);
  98. mem_free(hs);
  99. tcp_close(pcb);
  100. }
  101. /**
  102. * @brief callback function for handling TCP HTTP traffic
  103. * @param arg: pointer to an argument structure to be passed to callback function
  104. * @param pcb: pointer to a tcp_pcb structure
  105. * @param p: pointer to a packet buffer
  106. * @param err: LwIP error code
  107. * @retval err
  108. */
  109. static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
  110. {
  111. char *data;
  112. struct http_state *hs;
  113. char CookieBuf[50];
  114. char *CookiePtr = NULL;
  115. char name[MAX_WEB_COOKIE_LEN];
  116. char id[MAX_WEB_COOKIE_LEN];
  117. uint8_t nameLen = 0, idLen = 0;
  118. struct fs_file file = {0, 0};
  119. hs = arg;
  120. if (err == ERR_OK && p != NULL)
  121. {
  122. tcp_recved(pcb, p->tot_len);
  123. if (hs->file == NULL)
  124. {
  125. data = p->payload;
  126. /*
  127. printLen = p->tot_len;
  128. memcpy(printBuf, p->payload , printLen);
  129. printf(printBuf);
  130. */
  131. receivedBufLen = p->tot_len;
  132. memcpy(receiveBuf, p->payload , receivedBufLen);
  133. receiveBuf[receivedBufLen] = '\0';
  134. // printf("receive %s \r\n", receiveBuf);
  135. /* Get cookie "uname" value */
  136. CookiePtr = strstr(receiveBuf, "uname=");
  137. strncpy(CookieBuf, CookiePtr, 50);
  138. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  139. memset(name, 0, MAX_WEB_COOKIE_LEN);
  140. GetCookieValue(CookieBuf, "uname=", name, &nameLen);
  141. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  142. //printf("********uname= %s\r\n", name);
  143. /* Get cookie "id" value */
  144. CookiePtr = strstr(receiveBuf, "id=");
  145. strncpy(CookieBuf, CookiePtr, 50);
  146. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  147. memset(id, 0, MAX_WEB_COOKIE_LEN);
  148. GetCookieValue(CookieBuf, "id=", id, &idLen);
  149. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  150. //printf("********id= %s\r\n", id);
  151. /* Id of currently logged-in user */
  152. uint8_t user_id;
  153. /* Level of currently logged-in user */
  154. seclevel = 0xFF;
  155. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  156. HTTP_GetUserCookie(user_id, CookieBuf, &idLen);
  157. if (strncmp(id, CookieBuf, idLen) == 0 ) {
  158. GetUserLevelInt(user_id, &seclevel);
  159. Authenticated = true;
  160. break;
  161. }
  162. Authenticated = false;
  163. seclevel = 0xFF;
  164. }
  165. if ( Authenticated == false && sSettings.sRADIUS.Auth_enable == false)
  166. {
  167. HTTP_LOGIN(sendBuf, &sendBufLoadLen);
  168. hs->file = sendBuf;
  169. hs->left = sendBufLoadLen;
  170. send_data(pcb, hs);
  171. tcp_sent(pcb, http_sent);
  172. }
  173. else if ( Authenticated == false )//&& sSettings.sRADIUS.Auth_enable == true
  174. {
  175. if (strncmp(data, "GET /main.css", 13) == 0) // +
  176. {
  177. fs_open("/main.css", &file);
  178. hs->file = file.data;
  179. hs->left = file.len;
  180. send_data(pcb, hs);
  181. tcp_sent(pcb, http_sent);
  182. }
  183. else if (strncmp(data, "GET /rotek.png", 14) == 0) // +
  184. {
  185. fs_open("/rotek.png", &file);
  186. hs->file = file.data;
  187. hs->left = file.len;
  188. send_data(pcb, hs);
  189. tcp_sent(pcb, http_sent);
  190. }
  191. else if (strncmp(data, "GET /favicon.ico", 16) == 0) // ?
  192. {
  193. fs_open("/favicon.ico", &file);
  194. hs->file = file.data;
  195. hs->left = file.len;
  196. send_data(pcb, hs);
  197. tcp_sent(pcb, http_sent);
  198. }
  199. else if (strncmp(data, "GET /role.js", 12) == 0)
  200. {
  201. fs_open("/role.js", &file);
  202. hs->file = file.data;
  203. hs->left = file.len;
  204. send_data(pcb, hs);
  205. tcp_sent(pcb, http_sent);
  206. }
  207. else if ((strncmp(data, "POST /login.cgi", 15) == 0) || (log_post_reqn > 0))
  208. {
  209. uint32_t i, offset = 0, req_data_received = 0;
  210. //printf("request 1: %d\r\n", receivedBufLen);
  211. /* parse packet for Content-length field */
  212. post_data_count = Parse_Content_Length(data, p->tot_len);
  213. //printf("Content-length: %d\r\n", (int)post_data_count);
  214. if (post_data_count < MAX_POST_REQ_LEN) {
  215. memset(post_req_data, 0, MAX_POST_REQ_LEN);
  216. /* parse packet for "\r\n\r\n" */
  217. for (i = 0; i < receivedBufLen; i++)
  218. {
  219. if (strncmp ((char*)(data+i), "\r\n\r\n", 4) == 0)
  220. {
  221. offset = i+4;
  222. //printf("offset: %d\r\n", (int)offset);
  223. break;
  224. }
  225. }
  226. req_data_received = receivedBufLen - offset;
  227. //printf("req data received: %d\r\n", (int)req_data_received);
  228. /* Check if "\r\n\r\n" was found */
  229. if (offset != 0) {
  230. /* if data was splited in two packets */
  231. if (req_data_received < post_data_count) {
  232. /* Copy request data to buffer */
  233. snprintf(post_req_data, req_data_received, "%s", receiveBuf);
  234. //printf("copied: %d\r\n", (int)req_data_received);
  235. post_data_count -= req_data_received;
  236. }
  237. /* if data received completely */
  238. else {
  239. strncat(post_req_data, (char *)(data + offset), post_data_count);
  240. //printf("post_req_data: %s\r\n", post_req_data);
  241. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES) {
  242. hs->file = sendBuf;
  243. hs->left = sendBufLoadLen;
  244. send_data(pcb, hs);
  245. tcp_sent(pcb, http_sent);
  246. }
  247. else {
  248. /* Redirect to login page */
  249. fs_open("/login.html", &file);
  250. hs->file = file.data;
  251. hs->left = file.len;
  252. send_data(pcb, hs);
  253. tcp_sent(pcb, http_sent);
  254. }
  255. /* End reqest */
  256. post_data_count = 0;
  257. log_post_reqn = 0;
  258. }
  259. }
  260. /* request was fragmented before "\r\n\r\n" */
  261. else {
  262. //printf("no data found!\r\n");
  263. /* wait next packet */
  264. log_post_reqn++;
  265. /* wait max 2 requests */
  266. if (log_post_reqn > 1) {
  267. /* Redirect to login page */
  268. fs_open("/login.html", &file);
  269. hs->file = file.data;
  270. hs->left = file.len;
  271. send_data(pcb, hs);
  272. tcp_sent(pcb, http_sent);
  273. /* End reqest */
  274. post_data_count = 0;
  275. log_post_reqn = 0;
  276. }
  277. }
  278. }
  279. else {
  280. printf("Too long POST request!\r\n");
  281. /* Ignore request */
  282. post_data_count = 0;
  283. log_post_reqn = 0;
  284. /* Redirect to login page */
  285. fs_open("/login.html", &file);
  286. hs->file = file.data;
  287. hs->left = file.len;
  288. send_data(pcb, hs);
  289. tcp_sent(pcb, http_sent);
  290. }
  291. }
  292. else if (post_data_count > 0)
  293. {
  294. strncat(post_req_data, data, post_data_count);
  295. //printf("copied: %d\r\n", (int)post_data_count);
  296. //printf("post_req_data: %s\r\n", post_req_data);
  297. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES) {
  298. hs->file = sendBuf;
  299. hs->left = sendBufLoadLen;
  300. send_data(pcb, hs);
  301. tcp_sent(pcb, http_sent);
  302. }
  303. else {
  304. /* Redirect to login page */
  305. fs_open("/login.html", &file);
  306. hs->file = file.data;
  307. hs->left = file.len;
  308. send_data(pcb, hs);
  309. tcp_sent(pcb, http_sent);
  310. }
  311. /* End reqest */
  312. post_data_count = 0;
  313. log_post_reqn = 0;
  314. }
  315. else
  316. {
  317. fs_open("/login.html", &file);
  318. hs->file = file.data;
  319. hs->left = file.len;
  320. send_data(pcb, hs);
  321. tcp_sent(pcb, http_sent);
  322. }
  323. }
  324. else if ( Authenticated == true ) {
  325. if (strncmp(data, "GET /main.css", 13) == 0) // +
  326. {
  327. fs_open("/main.css", &file);
  328. hs->file = file.data;
  329. hs->left = file.len;
  330. send_data(pcb, hs);
  331. tcp_sent(pcb, http_sent);
  332. }
  333. else if (strncmp(data, "GET /rotek.png", 14) == 0) // +
  334. {
  335. fs_open("/rotek.png", &file);
  336. hs->file = file.data;
  337. hs->left = file.len;
  338. send_data(pcb, hs);
  339. tcp_sent(pcb, http_sent);
  340. }
  341. else if (strncmp(data, "GET /favicon.ico", 16) == 0) // ?
  342. {
  343. fs_open("/favicon.ico", &file);
  344. hs->file = file.data;
  345. hs->left = file.len;
  346. send_data(pcb, hs);
  347. tcp_sent(pcb, http_sent);
  348. }
  349. else if (strncmp(data, "GET /main.js", 12) == 0) // +
  350. {
  351. fs_open("/main.js", &file);
  352. hs->file = file.data;
  353. hs->left = file.len;
  354. send_data(pcb, hs);
  355. tcp_sent(pcb, http_sent);
  356. }
  357. else if (strncmp(data, "GET /role.js", 12) == 0)
  358. {
  359. fs_open("/role.js", &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 /settings.html", 18) == 0) // +
  366. {
  367. HTTP_UpdateUserLoginTime(user_id);
  368. if (seclevel == 0){
  369. fs_open("/settings.html", &file);
  370. hs->file = file.data;
  371. hs->left = file.len;
  372. send_data(pcb, hs);
  373. tcp_sent(pcb, http_sent);
  374. }
  375. else {
  376. fs_open("/index.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. }
  383. else if (strncmp(data, "GET /info.html", 14) == 0) // +
  384. {
  385. HTTP_UpdateUserLoginTime(user_id);
  386. fs_open("/info.html", &file);
  387. hs->file = file.data;
  388. hs->left = file.len;
  389. send_data(pcb, hs);
  390. tcp_sent(pcb, http_sent);
  391. }
  392. else if (strncmp(data, "GET /history.html", 17) == 0)
  393. {
  394. HTTP_UpdateUserLoginTime(user_id);
  395. fs_open("/history.html", &file);
  396. hs->file = file.data;
  397. hs->left = file.len;
  398. send_data(pcb, hs);
  399. tcp_sent(pcb, http_sent);
  400. }
  401. else if (strncmp(data, "GET /ups_history.html", 21) == 0)
  402. {
  403. HTTP_UpdateUserLoginTime(user_id);
  404. fs_open("/ups_history.html", &file);
  405. hs->file = file.data;
  406. hs->left = file.len;
  407. send_data(pcb, hs);
  408. tcp_sent(pcb, http_sent);
  409. }
  410. else if (strncmp(data, "GET /getJson.cgi", 16) == 0) // +
  411. {
  412. HTTP_GetParamsPage1(sendBuf);
  413. hs->file = sendBuf;
  414. hs->left = strlen(sendBuf);
  415. send_data(pcb, hs);
  416. tcp_sent(pcb, http_sent);
  417. }
  418. else if (strncmp(data, "GET /settings.cgi", 17) == 0) // +
  419. {
  420. SET_PAGE = SET_PAGE_PAGE2;
  421. if (seclevel == 0) {
  422. if (HTTP_SettingsPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  423. {
  424. hs->file = sendBuf;
  425. hs->left = sendBufLoadLen;
  426. send_data(pcb, hs);
  427. tcp_sent(pcb, http_sent);
  428. }
  429. /*else
  430. {
  431. fs_open("/settings.html", &file);
  432. hs->file = file.data;
  433. hs->left = file.len;
  434. send_data(pcb, hs);
  435. tcp_sent(pcb, http_sent);
  436. }*/
  437. }
  438. }
  439. else if (strncmp(data, "POST /settings.cgi", 18) == 0)
  440. {
  441. //strncat(&receiveBuf, " ", 1);
  442. strncat(receiveBuf, " ", 1);
  443. HTTP_SetSettings(receiveBuf, receivedBufLen);
  444. memset(sendBuf, 0, SEND_BUF_MAX_LEN);
  445. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  446. strcat(sendBuf, "\r\n\r\n");
  447. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/settings.html\"/></head></html>\r\n\r\n");
  448. sendBufLoadLen = strlen(sendBuf);
  449. hs->file = sendBuf;
  450. hs->left = sendBufLoadLen;
  451. send_data(pcb, hs);
  452. tcp_sent(pcb, http_sent);
  453. }
  454. else if (strncmp(data, "GET /info.cgi", 13) == 0) // +
  455. {
  456. if (HTTP_InfoPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  457. {
  458. hs->file = sendBuf;
  459. hs->left = sendBufLoadLen;
  460. send_data(pcb, hs);
  461. tcp_sent(pcb, http_sent);
  462. }
  463. /* else
  464. {
  465. fs_open("/info.html", &file);
  466. hs->file = file.data;
  467. hs->left = file.len;
  468. send_data(pcb, hs);
  469. tcp_sent(pcb, http_sent);
  470. }*/
  471. }
  472. else if (strncmp(data, "POST /info.cgi", 14) == 0)
  473. {
  474. //strncat(&receiveBuf, " ", 1);
  475. strncat(receiveBuf, " ", 1);
  476. HTTP_SetInfo(receiveBuf, receivedBufLen);
  477. memset(sendBuf, 0, SEND_BUF_MAX_LEN);
  478. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  479. strcat(sendBuf, "\r\n\r\n");
  480. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/info.html\"/></head></html>\r\n\r\n");
  481. sendBufLoadLen = strlen(sendBuf);
  482. hs->file = sendBuf;
  483. hs->left = sendBufLoadLen;
  484. send_data(pcb, hs);
  485. tcp_sent(pcb, http_sent);
  486. }
  487. else if (strncmp(data, "GET /history.cgi", 16) == 0)
  488. {
  489. int res;
  490. res = HTTP_HistoryPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  491. if (res == SEND_REQUIRED_FILE)
  492. {
  493. hs->file = sendBuf;
  494. hs->left = sendBufLoadLen;
  495. send_data(pcb, hs);
  496. tcp_sent(pcb, http_sent_history);
  497. tcp_err(pcb, http_sent_log_err);
  498. }
  499. else if (res == SEND_REQUIRED_YES) {
  500. hs->file = sendBuf;
  501. hs->left = sendBufLoadLen;
  502. send_data(pcb, hs);
  503. tcp_sent(pcb, http_sent);
  504. }
  505. }
  506. else if (strncmp(data, "GET /ups_history.cgi", 19) == 0)
  507. {
  508. int res;
  509. res = HTTP_UpsHistoryPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  510. if (res == SEND_REQUIRED_FILE)
  511. {
  512. hs->file = sendBuf;
  513. hs->left = sendBufLoadLen;
  514. send_data(pcb, hs);
  515. tcp_sent(pcb, http_sent_log);
  516. tcp_err(pcb, http_sent_log_err);
  517. }
  518. else if (res == SEND_REQUIRED_YES) {
  519. hs->file = sendBuf;
  520. hs->left = sendBufLoadLen;
  521. send_data(pcb, hs);
  522. tcp_sent(pcb, http_sent);
  523. }
  524. }
  525. /* Тест АКБ ИБП */
  526. else if (strncmp(data, "POST /bat_test.cgi", 18) == 0)
  527. {
  528. HTTP_UPSTest(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  529. hs->file = sendBuf;
  530. hs->left = sendBufLoadLen;
  531. send_data(pcb, hs);
  532. tcp_sent(pcb, http_sent);
  533. }
  534. /* Выключение ИБП */
  535. else if (strncmp(data, "POST /ups_power.cgi", 19) == 0)
  536. {
  537. HTTP_UPSshutdown(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  538. hs->file = sendBuf;
  539. hs->left = sendBufLoadLen;
  540. send_data(pcb, hs);
  541. tcp_sent(pcb, http_sent);
  542. }
  543. /* Сброс настроек и сохранине */
  544. else if (strncmp(data, "GET /reset.cgi", 14) == 0)
  545. {
  546. HTTP_ResetSettings();
  547. HTTP_SaveSettings();
  548. fs_open("/settings.html", &file);
  549. hs->file = file.data;
  550. hs->left = file.len;
  551. send_data(pcb, hs);
  552. tcp_sent(pcb, http_sent);
  553. }
  554. /* Перезагрузка контроллера */
  555. else if (strncmp(data, "GET /reboot.cgi", 15) == 0)
  556. {
  557. HTTP_Reboot();
  558. }
  559. /* Подтверждение новых сетевых настроек */
  560. else if (strncmp(data, "GET /confirm.cgi", 16) == 0)
  561. {
  562. SetWebReinitFlag(false);
  563. SetConfirmWebParamsFlag();
  564. fs_open("/index.html", &file);
  565. hs->file = file.data;
  566. hs->left = file.len;
  567. send_data(pcb, hs);
  568. tcp_sent(pcb, http_sent);
  569. }
  570. /* Проверка пароля, переход в bootloader */
  571. else if (strncmp(data, "GET /fw_update.cgi", 18) == 0)
  572. {
  573. HTTP_ConfirmBootPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  574. hs->file = sendBuf;
  575. hs->left = sendBufLoadLen;
  576. send_data(pcb, hs);
  577. tcp_sent(pcb, http_sent);
  578. }
  579. /* Смена пароля пользователя */
  580. else if (strncmp(data, "POST /changepwd.cgi", 19) == 0)
  581. {
  582. HTTP_ChangeUserPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  583. hs->file = sendBuf;
  584. hs->left = sendBufLoadLen;
  585. send_data(pcb, hs);
  586. tcp_sent(pcb, http_sent);
  587. }
  588. // На производстве
  589. else if (strncmp(data, "GET /setProdate.cgi", 19) == 0)
  590. {
  591. HTTP_Prodate(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  592. hs->file = sendBuf;
  593. hs->left = sendBufLoadLen;
  594. send_data(pcb, hs);
  595. tcp_sent(pcb, http_sent);
  596. }
  597. else
  598. {
  599. HTTP_UpdateUserLoginTime(user_id);
  600. fs_open("/index.html", &file); // +
  601. hs->file = file.data;
  602. hs->left = file.len;
  603. send_data(pcb, hs);
  604. tcp_sent(pcb, http_sent);
  605. }
  606. }
  607. }
  608. pbuf_free(p);
  609. // close_conn(pcb,hs);
  610. }
  611. /* if (err == ERR_OK && p == NULL)
  612. {
  613. close_conn(pcb, hs);
  614. }*/
  615. return ERR_OK;
  616. }
  617. /**
  618. * @brief Error callback for log file transfer
  619. */
  620. static void http_sent_log_err(void * arg, err_t err)
  621. {
  622. (void)err;
  623. (void)arg;
  624. /* Clear file transfer in progress flag */
  625. fLogTransInprog = false;
  626. }
  627. /**
  628. * @brief Sent callback for log file transfer (messages as is, not ordered)
  629. */
  630. static err_t http_sent_log(void *arg, struct tcp_pcb *pcb, u16_t len)
  631. {
  632. struct http_state *hs;
  633. uint32_t nbytes = 0;
  634. static bool start = true;
  635. (void)len;
  636. hs = arg;
  637. if (hs->left > 0)
  638. {
  639. send_data(pcb, hs);
  640. }
  641. else
  642. {
  643. memset(logFileBuf, 0, FILE_BUF_MAX_LEN);
  644. if (log_ptr + FILE_BUF_MAX_LEN_LOG <= log_size) {
  645. nbytes = LOG_GetData(log_ptr, logFileBuf, FILE_BUF_MAX_LEN_LOG, start);
  646. }
  647. else if (log_ptr < log_size) {
  648. nbytes = LOG_GetData(log_ptr, logFileBuf, (log_size - log_ptr), start);
  649. }
  650. else {
  651. nbytes = 0;
  652. }
  653. log_ptr += nbytes;
  654. start = false;
  655. if (nbytes == 0) {
  656. /* File transfer finished. */
  657. start = true;
  658. close_conn(pcb, hs);
  659. /* Clear file transfer in progress flag */
  660. fLogTransInprog = false;
  661. return ERR_OK;
  662. }
  663. hs->file = logFileBuf;
  664. hs->left = nbytes;
  665. send_data(pcb, hs);
  666. tcp_sent(pcb, http_sent_log);
  667. }
  668. return ERR_OK;
  669. }
  670. /**
  671. * @brief Sent callback for log file transfer (messages as is, not ordered)
  672. */
  673. static err_t http_sent_history(void *arg, struct tcp_pcb *pcb, u16_t len)
  674. {
  675. struct http_state *hs;
  676. uint32_t nbytes = 0;
  677. static bool start = true;
  678. (void)len;
  679. hs = arg;
  680. if (hs->left > 0)
  681. {
  682. send_data(pcb, hs);
  683. }
  684. else
  685. {
  686. memset(logFileBuf, 0, FILE_BUF_MAX_LEN);
  687. if (log_ptr + FILE_BUF_MAX_LEN <= log_size) {
  688. nbytes = History_GetData(log_ptr, logFileBuf, FILE_BUF_MAX_LEN, start);
  689. }
  690. else if (log_ptr < log_size) {
  691. nbytes = History_GetData(log_ptr, logFileBuf, (log_size - log_ptr), start);
  692. }
  693. else {
  694. nbytes = 0;
  695. }
  696. log_ptr += nbytes;
  697. start = false;
  698. if (nbytes == 0) {
  699. /* File transfer finished. */
  700. start = true;
  701. close_conn(pcb, hs);
  702. /* Clear file transfer in progress flag */
  703. fLogTransInprog = false;
  704. return ERR_OK;
  705. }
  706. hs->file = logFileBuf;
  707. hs->left = nbytes;
  708. send_data(pcb, hs);
  709. tcp_sent(pcb, http_sent_history);
  710. }
  711. return ERR_OK;
  712. }
  713. /**
  714. * @brief callback function for handling connection errors
  715. * @param arg: pointer to an argument to be passed to callback function
  716. * @param err: LwIP error code
  717. * @retval none
  718. */
  719. static void conn_err(void *arg, err_t err)
  720. {
  721. struct http_state *hs;
  722. hs = arg;
  723. mem_free(hs);
  724. }
  725. /**
  726. * @brief callback function called after a successfull TCP data packet transmission
  727. * @param arg: pointer to an argument to be passed to callback function
  728. * @param pcb: pointer on tcp_pcb structure
  729. * @param len
  730. * @retval err : LwIP error code
  731. */
  732. static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len)
  733. {
  734. struct http_state *hs;
  735. hs = arg;
  736. if (hs->left > 0)
  737. {
  738. send_data(pcb, hs);
  739. }
  740. else
  741. {
  742. close_conn(pcb, hs);
  743. }
  744. return ERR_OK;
  745. }
  746. /**
  747. * @brief sends data found in member "file" of a http_state struct
  748. * @param pcb: pointer to a tcp_pcb struct
  749. * @param hs: pointer to a http_state struct
  750. * @retval none
  751. */
  752. static void send_data(struct tcp_pcb *pcb, struct http_state *hs)
  753. {
  754. err_t err;
  755. u16_t len;
  756. /* We cannot send more data than space available in the send
  757. buffer */
  758. if (tcp_sndbuf(pcb) < hs->left)
  759. {
  760. len = tcp_sndbuf(pcb);
  761. }
  762. else
  763. {
  764. len = hs->left;
  765. }
  766. err = tcp_write(pcb, hs->file, len, 0);
  767. if (err == ERR_OK)
  768. {
  769. hs->file += len;
  770. hs->left -= len;
  771. }
  772. }
  773. /**
  774. * @brief tcp poll callback function
  775. * @param arg: pointer to an argument to be passed to callback function
  776. * @param pcb: pointer on tcp_pcb structure
  777. * @retval err_t
  778. */
  779. static err_t http_poll(void *arg, struct tcp_pcb *pcb)
  780. {
  781. if (arg == NULL)
  782. {
  783. tcp_close(pcb);
  784. }
  785. else
  786. {
  787. send_data(pcb, (struct http_state *)arg);
  788. }
  789. return ERR_OK;
  790. }
  791. /**
  792. * @brief callback function on TCP connection setup ( on port 80)
  793. * @param arg: pointer to an argument structure to be passed to callback function
  794. * @param pcb: pointer to a tcp_pcb structure
  795. * &param err: Lwip stack error code
  796. * @retval err
  797. */
  798. static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err)
  799. {
  800. struct http_state *hs;
  801. /* Allocate memory for the structure that holds the state of the connection */
  802. hs = mem_malloc(sizeof(struct http_state));
  803. if (hs == NULL)
  804. {
  805. return ERR_MEM;
  806. }
  807. /* Initialize the structure. */
  808. hs->file = NULL;
  809. hs->left = 0;
  810. /* Tell TCP that this is the structure we wish to be passed for our
  811. callbacks. */
  812. tcp_arg(pcb, hs);
  813. /* Tell TCP that we wish to be informed of incoming data by a call
  814. to the http_recv() function. */
  815. tcp_recv(pcb, http_recv);
  816. tcp_err(pcb, conn_err);
  817. tcp_poll(pcb, http_poll, 10);
  818. return ERR_OK;
  819. }
  820. /**
  821. * @brief Opens a file defined in fsdata.c ROM filesystem
  822. * @param name : pointer to a file name
  823. * @param file : pointer to a fs_file structure
  824. * @retval 1 if success, 0 if fail
  825. */
  826. static int fs_open(char *name, struct fs_file *file)
  827. {
  828. struct fsdata_file_noconst *f;
  829. for (f = (struct fsdata_file_noconst *)FS_ROOT; f != NULL; f = (struct fsdata_file_noconst *)f->next)
  830. {
  831. if (!strcmp(name, f->name))
  832. {
  833. file->data = f->data;
  834. file->len = f->len;
  835. return 1;
  836. }
  837. }
  838. return 0;
  839. }
  840. /**
  841. * @brief Initialize the HTTP server (start its thread)
  842. * @param none
  843. * @retval None
  844. */
  845. void HTTP_Init()
  846. {
  847. char buf[MAX_WEB_COOKIE_LEN];
  848. uint8_t user_id;
  849. //sys_thread_new("HTTP", http_server_netconn_thread, NULL, 3000, 2);
  850. struct tcp_pcb *pcb;
  851. /*create new pcb*/
  852. pcb = tcp_new();
  853. /* bind HTTP traffic to pcb */
  854. tcp_bind(pcb, IP_ADDR_ANY, 80);
  855. /* start listening on port 80 */
  856. pcb = tcp_listen(pcb);
  857. /* define callback function for TCP connection setup */
  858. tcp_accept(pcb, http_accept);
  859. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  860. /* Flush user cookie by random value */
  861. sprintf(buf, "%X", (unsigned int)GetRandomNumber());
  862. HTTP_SetUserCookie(buf, user_id);
  863. /* Create user logout timers */
  864. users[user_id].LogoutTimer =
  865. xTimerCreate("LogoutTmr", WEB_LOGOUT_TIME, pdFALSE, ( void * ) user_id, LogoutTimerCallback);
  866. }
  867. }
  868. /**
  869. * @brief
  870. * @retval None
  871. */
  872. int HTTP_SettingsPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  873. {
  874. char tempStr[30];
  875. strncpy(tempStr, bufIn, 30);
  876. /* В запросе нет параметров, нужно формировать JSON ответ */
  877. if (strpbrk(tempStr,"?") == 0)
  878. {
  879. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  880. HTTP_GetSettings(bufOut);
  881. //printf(bufOut);
  882. *lenBufOut = strlen(bufOut);
  883. return SEND_REQUIRED_YES;
  884. }
  885. /* В запросе есть параметры, нужно парсить и сохранять настройки */
  886. else
  887. {
  888. //HTTP_SetSettings(bufIn, lenBufIn);
  889. return SEND_REQUIRED_NO;
  890. }
  891. }
  892. /**
  893. * @brief
  894. * @retval None
  895. */
  896. int HTTP_InfoPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  897. {
  898. char tempStr[30];
  899. strncpy(tempStr, bufIn, 30);
  900. /* В запросе нет параметров, нужно формировать JSON ответ */
  901. if (strpbrk(tempStr,"?") == 0)
  902. {
  903. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  904. HTTP_GetInfo(bufOut);
  905. *lenBufOut = strlen(bufOut);
  906. return SEND_REQUIRED_YES;
  907. }
  908. /* В запросе есть параметры, нужно парсить и сохранять настройки */
  909. else
  910. {
  911. //HTTP_SetInfo(bufIn, lenBufIn);
  912. return SEND_REQUIRED_NO;
  913. /*
  914. HTTP_SetSettings(bufIn, lenBufIn);
  915. return SEND_REQUIRED_NO;
  916. */
  917. }
  918. }
  919. int HTTP_HistoryPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  920. {
  921. uint8_t i, valueLen = 0;
  922. char value[20];
  923. uint32_t nbytes = 0;
  924. (void)lenBufIn;
  925. memset(bufOut, 0, FILE_BUF_MAX_LEN);
  926. ClearParamString(bufIn);
  927. memset(value, 0, 20);
  928. GetParamValue(bufIn, "page=", value, &valueLen);
  929. if (strcmp(value, "all") == 0)
  930. {
  931. if (!LOG_IsInit()) {
  932. return SEND_REQUIRED_NO;
  933. }
  934. if (fLogTransInprog == false) {
  935. // Send log as raw data
  936. log_ptr = 0;
  937. log_size = History_GetTotalSTRCount() * STRING_SIZE_HISTORY + sizeof(UTF8_BOM)-1;
  938. sprintf(bufOut, "HTTP/1.1 200 OK\r\nContent-Length:%lu\r\n\r\n%s", log_size, UTF8_BOM);
  939. *lenBufOut = strlen(bufOut);
  940. // Set file transfer in progress flag
  941. fLogTransInprog = true;
  942. return SEND_REQUIRED_FILE;
  943. }
  944. else {
  945. // We send nothing if file transfer already in progress
  946. return SEND_REQUIRED_NO;
  947. }
  948. }
  949. else {
  950. if (!LOG_IsInit()) {
  951. return SEND_REQUIRED_NO;
  952. }
  953. else {
  954. HTTP_GetHistoryPage(bufOut, atoi(value));
  955. *lenBufOut = strlen(bufOut);
  956. return SEND_REQUIRED_YES;
  957. }
  958. }
  959. }
  960. int HTTP_UpsHistoryPage(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  961. {
  962. uint8_t i, valueLen = 0;
  963. char value[20];
  964. uint32_t nbytes = 0;
  965. (void)lenBufIn;
  966. memset(bufOut, 0, FILE_BUF_MAX_LEN);
  967. ClearParamString(bufIn);
  968. memset(value, 0, 20);
  969. GetParamValue(bufIn, "page=", value, &valueLen);
  970. if (strcmp(value, "all") == 0)
  971. {
  972. if (!LOG_IsInit()) {
  973. return SEND_REQUIRED_NO;
  974. }
  975. if (fLogTransInprog == false) {
  976. // Send log as raw data
  977. log_ptr = 0;
  978. log_size = LOG_GetTotalSTRCount() * STRING_SIZE + sizeof(UTF8_BOM)-1;
  979. sprintf(bufOut, "HTTP/1.1 200 OK\r\nContent-Length:%lu\r\n\r\n%s", log_size, UTF8_BOM);
  980. *lenBufOut = strlen(bufOut);
  981. // Set file transfer in progress flag
  982. fLogTransInprog = true;
  983. return SEND_REQUIRED_FILE;
  984. }
  985. else {
  986. // We send nothing if file transfer already in progress
  987. return SEND_REQUIRED_NO;
  988. }
  989. }
  990. else {
  991. if (!LOG_IsInit()) {
  992. return SEND_REQUIRED_NO;
  993. }
  994. else {
  995. HTTP_GetUpsHistoryPage(bufOut, atoi(value));
  996. *lenBufOut = strlen(bufOut);
  997. return SEND_REQUIRED_YES;
  998. }
  999. }
  1000. }
  1001. /**
  1002. * @brief Установка даты производства
  1003. */
  1004. // TODO Убрать заглушку!
  1005. void HTTP_Prodate(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1006. {
  1007. uint8_t valueLen = 0;
  1008. char value[20];
  1009. memset(bufOut, 0, SEND_BUF_MAX_LEN);
  1010. ClearParamString(bufIn);
  1011. memset(value, 0, 20);
  1012. GetParamValue(bufIn, "prodate=", value, &valueLen);
  1013. /*
  1014. printf("Prodate: ");
  1015. printf(value);
  1016. printf("\r\n");
  1017. */
  1018. /* Устанавливаем дату производства */
  1019. SETTINGS_SetProDate(value, valueLen);
  1020. /* Устанавливаем дату следующей профилактики +1 год */
  1021. RTC_SetProfTime(value);
  1022. /* Пока отправляем true */
  1023. strcpy(bufOut, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\n\r\nTrue");
  1024. *lenBufOut = strlen(bufOut);
  1025. // TEST_SetServerFlag();
  1026. }
  1027. /**
  1028. * @brief
  1029. * @retval None
  1030. */
  1031. void HTTP_SetSettings(char *buf, uint16_t lenBuf)
  1032. {
  1033. uint8_t valueLen = 0;
  1034. const uint8_t len = MAX_WEB_PARAM_LEN;
  1035. char value[MAX_WEB_PARAM_LEN];
  1036. char str[MAX_WEB_PARAM_LEN];
  1037. //printf(buf);
  1038. //ClearParamString(buf);
  1039. memset(value, 0, len);
  1040. memset(str, 0, MAX_WEB_PARAM_LEN);
  1041. /* SNMP */
  1042. GetParamValue(buf, "read_community=", value, &valueLen);
  1043. SetReadCommunity(value);
  1044. memset(value, 0, len);
  1045. GetParamValue(buf, "write_community=", value, &valueLen);
  1046. SetWriteCommunity(value);
  1047. memset(value, 0, len);
  1048. GetParamValue(buf, "managerIP=", value, &valueLen);
  1049. SetManagerIp(value);
  1050. memset(value, 0, len);
  1051. GetParamValue(buf, "managerIP2=", value, &valueLen);
  1052. SetManagerIp2(value);
  1053. memset(value, 0, len);
  1054. GetParamValue(buf, "managerIP3=", value, &valueLen);
  1055. SetManagerIp3(value);
  1056. memset(value, 0, len);
  1057. GetParamValue(buf, "managerIP4=", value, &valueLen);
  1058. SetManagerIp4(value);
  1059. memset(value, 0, len);
  1060. GetParamValue(buf, "managerIP5=", value, &valueLen);
  1061. SetManagerIp5(value);
  1062. memset(value, 0, len);
  1063. /* Сетевые параметры */
  1064. GetParamValue(buf, "dhcp=", value, &valueLen);
  1065. SetDhcpStateStr(value);
  1066. if (strncmp(value, "on", 2) != 0) // Если dhcp off устанавливаем параметры
  1067. {
  1068. memset(value, 0, len);
  1069. GetParamValue(buf, "ipaddr=", value, &valueLen);
  1070. SetIPStr(value);
  1071. memset(value, 0, len);
  1072. GetParamValue(buf, "gw=", value, &valueLen);
  1073. SetGatewayStr(value);
  1074. memset(value, 0, len);
  1075. GetParamValue(buf, "mask=", value, &valueLen);
  1076. SetMaskStr(value);
  1077. memset(value, 0, len);
  1078. }
  1079. memset(value, 0, len);
  1080. GetParamValue(&buf[555], "auth=", value, &valueLen);
  1081. SetAuthEnableStateStr(value);
  1082. if (strncmp(value, "on", 2) == 0){
  1083. /* параметры RADIUS*/
  1084. memset(value, 0, len);
  1085. GetParamValue(buf, "rs_enabled=", value, &valueLen);
  1086. SetRDSEnableStateStr(value);
  1087. if (strncmp(value, "on", 2) == 0) // Если raddius off устанавливаем параметры
  1088. {
  1089. memset(value, 0, len);
  1090. GetParamValue(buf, "rs_server=", value, &valueLen);
  1091. SetRDSIpStr(value);
  1092. memset(value, 0, len);
  1093. GetParamValue(buf, "rs_port=", value, &valueLen);
  1094. SetRDSPortStr(value);
  1095. memset(value, 0, len);
  1096. GetParamValue(buf, "rs_pwd=", value, &valueLen);
  1097. SetRDSPasswordkStr(value);
  1098. memset(value, 0, len);
  1099. GetParamValue(buf, "rs_key=", value, &valueLen);
  1100. SetRDSKeyAccesstStr(value);
  1101. memset(value, 0, len);
  1102. }
  1103. }
  1104. memset(value, 0, len);
  1105. // Параметры реле и сухих контактов
  1106. GetParamValue(buf, "di1=", value, &valueLen);
  1107. SetDINTypeActStr(value, 0);
  1108. memset(value, 0, len);
  1109. GetParamValue(buf, "ro1=", value, &valueLen);
  1110. SetROTypeActStr(value, 0);
  1111. memset(value, 0, len);
  1112. GetParamValue(buf, "ro2=", value, &valueLen);
  1113. SetROTypeActStr(value, 1);
  1114. memset(value, 0, len);
  1115. // Параметры даты и времени
  1116. GetParamValue(buf, "ntp=", value, &valueLen);
  1117. SetSntpStateStr(value);
  1118. if (strncmp(value, "1", 1) == 0) // Если ntp on устанавливаем параметры
  1119. {
  1120. memset(value, 0, len);
  1121. GetParamValue(buf, "ntpservip=", value, &valueLen);
  1122. SetSntpServerIpStr(value);
  1123. memset(value, 0, len);
  1124. }
  1125. else if (strncmp(value, "0", 1) == 0){
  1126. GetParamValue(buf, "date=", value, &valueLen);
  1127. SetDateStr(value);
  1128. memset(value, 0, len);
  1129. GetParamValue(buf, "time=", value, &valueLen);
  1130. url_decode(str, sizeof(str), value);
  1131. SetTimeStr(str);
  1132. memset(value, 0, len);
  1133. }
  1134. GetParamValue(buf, "utc=", value, &valueLen);
  1135. SetSntpTimeZoneStr(value);
  1136. memset(value, 0, len);
  1137. /* Если параметры WEB изменились выставляем флаг, сохраняем настройки и перезагружаемся */
  1138. if (GetStateWebReinit() == true)
  1139. {
  1140. SetWebReinitFlag(true);
  1141. HTTP_SaveSettings();
  1142. /* Блокируем управление ключем на тау секунд*/
  1143. //IO_KeyBlockOn();
  1144. vTaskDelay(1010);
  1145. Reboot();
  1146. }
  1147. HTTP_SaveSettings();
  1148. }
  1149. /**
  1150. * @brief
  1151. * @retval None
  1152. */
  1153. void HTTP_SetInfo(char *buf, uint16_t lenBuf)
  1154. {
  1155. uint8_t valueLen = 0;
  1156. const uint8_t len = 110;
  1157. char value[110];
  1158. char str[110];
  1159. // ClearParamString(buf);
  1160. memset(value, 0, len);
  1161. /* Владелец */
  1162. GetParamValue(buf, "owner=", value, &valueLen);
  1163. url_decode(str, sizeof(str), value);
  1164. SetOwner(str);
  1165. memset(value, 0, len);
  1166. /* Владелец */
  1167. GetParamValue(buf, "sysLocation=", value, &valueLen);
  1168. url_decode(str, sizeof(str), value);
  1169. SetLocation(str);
  1170. memset(value, 0, len);
  1171. /* Комментарий */
  1172. GetParamValue(buf, "comment=", value, &valueLen);
  1173. url_decode(str, sizeof(str), value);
  1174. SetComment(str);
  1175. memset(value, 0, len);
  1176. HTTP_SaveSettings();
  1177. }
  1178. /**
  1179. * @brief Запуск/останов теста UPS
  1180. */
  1181. void HTTP_UPSTest(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1182. {
  1183. char *value = 0;
  1184. char *valueLen = 0;
  1185. char tempValue[20];
  1186. char tempValue2[20];
  1187. int8_t res = 0;
  1188. memset(tempValue, 0, 20);
  1189. memset(tempValue2, 0, 20);
  1190. strcpy(bufOut, HTTP_200_OK);
  1191. value = strstr(bufIn, "func");
  1192. valueLen = strpbrk(value, ":");
  1193. strncpy(tempValue, (valueLen+1), (strlen(valueLen)-2));
  1194. if (strcmp(tempValue, "\"stop\"") == 0){
  1195. res = ups_metac_service_pdu(ups_cancel_test);
  1196. if(res == 1 || res == 0){
  1197. strcat(bufOut, "Тест остановлен!");
  1198. log_event_data(LOG_TEST_UPS, "Администратор(Останов)");
  1199. }
  1200. if(res == -1)
  1201. strcat(bufOut, "Тест не удалось остановить!");
  1202. *lenBufOut = strlen(bufOut);
  1203. }
  1204. else if (strcmp(tempValue, "\"discharge\"") == 0){
  1205. res = ups_metac_service_pdu(ups_test_low_bat);
  1206. if(res == 1 || res == 0){
  1207. strcat(bufOut, "Тест запущен!");
  1208. log_event_data(LOG_TEST_UPS, "Администратор (Запущен)");
  1209. }
  1210. if(res == -1)
  1211. strcat(bufOut, "Тест не удалось запустить!");
  1212. *lenBufOut = strlen(bufOut);
  1213. }
  1214. else if (strncmp(tempValue, "\"time\"", 6) == 0){
  1215. valueLen = strpbrk(tempValue, ":");
  1216. strncpy(tempValue2, (valueLen+2), (strlen(valueLen)-2));
  1217. TimeParam = atoi(tempValue2);
  1218. res = ups_metac_service_pdu(ups_test_time);
  1219. if(res == 1 || res == 0){
  1220. strcat(bufOut, "Тест запущен!");
  1221. log_event_data(LOG_TEST_UPS, "Администратор (Запущен)");
  1222. }
  1223. if(res == -1)
  1224. strcat(bufOut, "Тест не удалось запустить!");
  1225. *lenBufOut = strlen(bufOut);
  1226. }
  1227. }
  1228. /**
  1229. * @brief Выклюение UPS
  1230. */
  1231. void HTTP_UPSshutdown(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1232. {
  1233. char *value = 0;
  1234. char *valueLen = 0;
  1235. char *valueLenEnd = 0;
  1236. char tempValue[50];
  1237. char tempValue2[50];
  1238. int8_t res = 0;
  1239. memset(tempValue, 0, 50);
  1240. strcpy(bufOut, HTTP_200_OK);
  1241. value = strstr(bufIn, "func");
  1242. valueLen = strpbrk(value, ":");
  1243. strncpy(tempValue, (valueLen+1), (strlen(valueLen)-2));
  1244. if (strcmp(tempValue, "\"cancel\"") == 0){
  1245. res = ups_metac_service_pdu(ups_cancel_shut_down);
  1246. if(res == 1){
  1247. log_event_data(LOG_SHUTDOWN_UPS, "Администратор(Останов)");
  1248. strcat(bufOut, "Выключение ИБП отменено!");
  1249. }
  1250. else
  1251. strcat(bufOut, "Выключение ИБП не удалось отменить!");
  1252. *lenBufOut = strlen(bufOut);
  1253. }
  1254. else if (strncmp(tempValue, "\"off\"", 5) == 0){
  1255. value = strstr(tempValue, "after");
  1256. valueLen = strpbrk(value, ":");
  1257. valueLenEnd = strpbrk(value, ",");
  1258. memset(tempValue2, 0, 50);
  1259. strncpy(tempValue2, (valueLen+2), (valueLenEnd - valueLen - 2));
  1260. TimeParam = atoi(tempValue2);
  1261. value = strstr(tempValue, "to");
  1262. valueLen = strpbrk(value, ":");
  1263. memset(tempValue2, 0, 50);
  1264. strncpy(tempValue2, (valueLen+2), (strlen(valueLen) - 2));
  1265. TimeParam2 = atoi(tempValue2);
  1266. res = ups_metac_service_pdu(ups_shutdown_restore);
  1267. if(res == 1){
  1268. strcat(bufOut, "Перезагрузка ИБП!");
  1269. log_event_data(LOG_SHUTDOWN_UPS, "Администратор");
  1270. }else
  1271. strcat(bufOut, "Отмена перезагрузки ИБП!");
  1272. *lenBufOut = strlen(bufOut);
  1273. }
  1274. }
  1275. /**
  1276. * @brief Проверка пароля для перехода в режим bootloader
  1277. * @retval None
  1278. */
  1279. void HTTP_ConfirmBootPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1280. {
  1281. char tempStr[50];
  1282. strncpy(tempStr, bufIn, 50);
  1283. char value[20];
  1284. uint8_t valueLen;
  1285. memset(value, 0, 20);
  1286. //if (GetParamValue(tempStr, "password=", value, &valueLen))
  1287. {
  1288. //if (strcmp(BOOTLOADER_PASWORD, value) == 0)
  1289. {
  1290. // *bufOut = '1';
  1291. /* Запускаем задачу отложенной перезагрузки. Контроллер должен успеть
  1292. отправить ответ серверу о статусе пароля */
  1293. HTTP_StartResetTask(true);
  1294. }
  1295. /* else
  1296. *bufOut = '0';*/
  1297. //*lenBufOut = 1;
  1298. }
  1299. }
  1300. /**
  1301. * @brief Проверка пароля для входа в Web
  1302. * @retval None
  1303. */
  1304. int HTTP_ConfirmWebPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1305. {
  1306. char tempStr[50];
  1307. char login[20];
  1308. char password[20];
  1309. uint8_t valueLen, user_id;
  1310. char *strPtr = 0;
  1311. char WebPassword[MAX_WEB_PASSWD_LEN];
  1312. char WebLogin[MAX_WEB_LOGIN_LEN];
  1313. char buf[40];
  1314. memset(login, 0, 20);
  1315. memset(password, 0, 20);
  1316. memset(tempStr, 0, 50);
  1317. /* Get first 50 bytes of string */
  1318. strncpy(tempStr, bufIn, 49);
  1319. /* Add " " to the string in order GetParamValue() can be able to parse the param */
  1320. strcat(tempStr, " ");
  1321. if (GetParamValue(tempStr, "login=", login, &valueLen) &&
  1322. GetParamValue(tempStr, "password=", password, &valueLen))
  1323. {
  1324. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  1325. GetUserLogin(user_id, WebLogin, &valueLen);
  1326. GetUserPassword(user_id, WebPassword, &valueLen);
  1327. /* Check login and password */
  1328. if ((strncmp(WebLogin, login, MAX_WEB_LOGIN_LEN) == 0) &&
  1329. (strncmp(WebPassword, password, MAX_WEB_PASSWD_LEN) == 0)) {
  1330. /* Login and pass are valid */
  1331. /* Check user's login session */
  1332. /* If "user" has logged in */
  1333. if (user_id >= 1) {
  1334. }
  1335. /* TODO replace global flag with user-pass-cookie */
  1336. Authenticated = true;
  1337. /* Generate cookie */
  1338. sprintf(tempStr, "%X", (unsigned int)GetRandomNumber());
  1339. /* Set users cookie */
  1340. HTTP_SetUserCookie(tempStr, user_id);
  1341. HTTP_UpdateUserLoginTime(user_id);
  1342. /* Send login and cookie back */
  1343. strcpy(bufOut, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\nSet-Cookie: uname=");
  1344. strcat(bufOut, WebLogin);
  1345. strcat(bufOut, "\r\nSet-Cookie: id=");
  1346. strcat(bufOut, tempStr);
  1347. sprintf(tempStr, "%d", user_id);
  1348. strcat(bufOut, "\r\nSet-Cookie: role=");
  1349. strcat(bufOut, tempStr);
  1350. strcat(bufOut, "\r\n\r\n");
  1351. strcat(bufOut,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/index.html\"/></head></html>\r\n\r\n");
  1352. *lenBufOut = strlen(bufOut);
  1353. switch (user_id) {
  1354. case 0:
  1355. snprintf(buf, sizeof(buf), "Администратор");
  1356. break;
  1357. case 1:
  1358. snprintf(buf, sizeof(buf), "Пользователь");
  1359. break;
  1360. default:
  1361. snprintf(buf, sizeof(buf), "", login);
  1362. break;
  1363. }
  1364. log_event_data(LOG_LOGIN, buf);
  1365. /* Запускаем задачу-таймер логаута. */
  1366. /* TODO отправить ответ серверу о статусе пароля */
  1367. return SEND_REQUIRED_YES;
  1368. }
  1369. /*
  1370. else {
  1371. continue;
  1372. }
  1373. */
  1374. }
  1375. }
  1376. /* No valid login and pass found */
  1377. /* TODO replace global flag with user-pass-cookie*/
  1378. Authenticated = false;
  1379. /* Wrong login or pass, return */
  1380. return SEND_REQUIRED_NO;
  1381. }
  1382. void HTTP_LOGIN(char *bufOut, uint16_t *lenBufOut)
  1383. {
  1384. char tempStr[50];
  1385. uint8_t valueLen;
  1386. char WebLogin[MAX_WEB_LOGIN_LEN];
  1387. GetUserLogin(ADMIN, WebLogin, &valueLen);
  1388. memset(tempStr, 0, 50);
  1389. /* TODO replace global flag with user-pass-cookie */
  1390. Authenticated = true;
  1391. /* Generate cookie */
  1392. sprintf(tempStr, "%X", (unsigned int)GetRandomNumber());
  1393. /* Set users cookie */
  1394. HTTP_SetUserCookie(tempStr, ADMIN);
  1395. HTTP_UpdateUserLoginTime(ADMIN);
  1396. /* Send login and cookie back */
  1397. strcpy(bufOut, "HTTP/1.0 200 OK\r\nContent-Type:text/html\r\nSet-Cookie: uname=");
  1398. strcat(bufOut, WebLogin);
  1399. strcat(bufOut, "\r\nSet-Cookie: id=");
  1400. strcat(bufOut, tempStr);
  1401. strcat(bufOut, "\r\nSet-Cookie: role=0");
  1402. strcat(bufOut, "\r\nSet-Cookie: auth=0");
  1403. strcat(bufOut, "\r\n\r\n");
  1404. strcat(bufOut,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/index.html\"/></head></html>\r\n\r\n");
  1405. *lenBufOut = strlen(bufOut);
  1406. }
  1407. /**
  1408. * @brief
  1409. * @retval None
  1410. */
  1411. uint8_t GetParamValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1412. {
  1413. char *beginValue = 0;
  1414. char *endValue = 0;
  1415. int len = 0;
  1416. char *strPtr = 0;
  1417. strPtr = strstr(inStr, paramName);
  1418. if (strPtr != 0)
  1419. {
  1420. beginValue = strpbrk(strPtr,"=");
  1421. endValue = strpbrk(strPtr,"&");
  1422. if (endValue == 0)
  1423. endValue = strpbrk(strPtr," ");
  1424. len = endValue - beginValue - 1;
  1425. strncpy(paramValue, beginValue + 1, len);
  1426. *endValue = '0';
  1427. *beginValue = '0';
  1428. *paramLen = len;
  1429. return 1;
  1430. }
  1431. else
  1432. {
  1433. *paramLen = 0;
  1434. return 0;
  1435. }
  1436. }
  1437. /**
  1438. * @brief
  1439. * @retval None
  1440. */
  1441. uint8_t GetCookieValue(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1442. {
  1443. char *beginValue = 0;
  1444. char *endValue = 0;
  1445. int len = 0;
  1446. char *strPtr = 0;
  1447. strPtr = strstr(inStr, paramName);
  1448. if (strPtr != 0)
  1449. {
  1450. beginValue = strpbrk(strPtr,"=");
  1451. endValue = strpbrk(strPtr,";");
  1452. if (endValue == 0)
  1453. endValue = strpbrk(strPtr,"\n");
  1454. len = endValue - beginValue - 1;
  1455. strncpy(paramValue, beginValue + 1, len);
  1456. *endValue = '0';
  1457. *beginValue = '0';
  1458. *paramLen = len;
  1459. return 1;
  1460. }
  1461. else
  1462. {
  1463. *paramLen = 0;
  1464. return 0;
  1465. }
  1466. }
  1467. /**
  1468. * @brief
  1469. * @retval None
  1470. */
  1471. /*
  1472. uint8_t GetParamValueInEnd(char *inStr, char *paramName, char *paramValue, uint8_t *paramLen)
  1473. {
  1474. char *beginValue = 0;
  1475. char *endValue = 0;
  1476. int len = 0;
  1477. char *strPtr = 0;
  1478. strPtr = strstr(inStr, paramName);
  1479. if (strPtr != 0)
  1480. {
  1481. beginValue = strpbrk(strPtr,"=");
  1482. endValue = strpbrk(strPtr," ");
  1483. len = endValue - beginValue - 1;
  1484. strncpy(paramValue, beginValue + 1, len);
  1485. *endValue = '0';
  1486. *beginValue = '0';
  1487. *paramLen = len;
  1488. return 1;
  1489. }
  1490. else
  1491. {
  1492. *paramLen = 0;
  1493. return 0;
  1494. }
  1495. }
  1496. */
  1497. void ClearParamString(char *inBuf)
  1498. {
  1499. uint16_t len;
  1500. char *str;
  1501. str = strstr(inBuf, "HTTP");
  1502. if (str != 0)
  1503. {
  1504. len = str - inBuf;
  1505. memset(str, 0, RECIVE_BUF_MAX_LEN - len - 1);
  1506. }
  1507. }
  1508. /**
  1509. * @brief Чтение Cookie пользователя
  1510. */
  1511. static void HTTP_GetUserCookie(uint8_t user_id, char *str, uint8_t *len)
  1512. {
  1513. sprintf(str, "%s", users[user_id].cookie);
  1514. *len = strlen(str);
  1515. }
  1516. /**
  1517. * @brief Установка Cookie пользователя
  1518. */
  1519. static void HTTP_SetUserCookie(char *str, uint8_t user_id)
  1520. {
  1521. strcpy(users[user_id].cookie, str);
  1522. }
  1523. /**
  1524. * @brief Обновление времени последней активности пользователя
  1525. */
  1526. static void HTTP_UpdateUserLoginTime(uint8_t user_id)
  1527. {
  1528. xTimerStart(users[user_id].LogoutTimer, 0);
  1529. }
  1530. /**
  1531. * @brief Extract the Content_Length data from HTML data
  1532. * @param data : pointer on receive packet buffer
  1533. * @param len : buffer length
  1534. * @retval size : Content_length in numeric format
  1535. */
  1536. static uint32_t Parse_Content_Length(char *data, uint32_t len)
  1537. {
  1538. uint32_t i=0,size=0, S=1;
  1539. int32_t j=0;
  1540. char sizestring[6], *ptr;
  1541. ContentLengthOffset =0;
  1542. /* find Content-Length data in packet buffer */
  1543. for (i=0;i<len;i++)
  1544. {
  1545. if (strncmp ((char*)(data+i), Content_Length, 16)==0)
  1546. {
  1547. ContentLengthOffset = i+16;
  1548. break;
  1549. }
  1550. }
  1551. /* read Content-Length value */
  1552. if (ContentLengthOffset)
  1553. {
  1554. i=0;
  1555. ptr = (char*)(data + ContentLengthOffset);
  1556. while(*(ptr+i)!=0x0d)
  1557. {
  1558. sizestring[i] = *(ptr+i);
  1559. i++;
  1560. ContentLengthOffset++;
  1561. }
  1562. if (i>0)
  1563. {
  1564. /* transform string data into numeric format */
  1565. for(j=i-1;j>=0;j--)
  1566. {
  1567. size += (sizestring[j]-0x30)*S;
  1568. S=S*10;
  1569. }
  1570. }
  1571. }
  1572. return size;
  1573. }
  1574. /**
  1575. * @brief Принудительный логаут пользователя
  1576. */
  1577. static void HTTP_ForceUserLogout(uint8_t user_id)
  1578. {
  1579. char cookie[MAX_WEB_COOKIE_LEN];
  1580. /* Flush user cookie by random value */
  1581. sprintf(cookie, "%X", (unsigned int)GetRandomNumber());
  1582. HTTP_SetUserCookie(cookie, user_id);
  1583. }
  1584. /**
  1585. * @brief >Callback таймера логаута пользователя
  1586. */
  1587. void LogoutTimerCallback(TimerHandle_t pxTimer) {
  1588. uint8_t user_id = (uint8_t)pvTimerGetTimerID( pxTimer );
  1589. if( sSettings.sRADIUS.Auth_enable )
  1590. HTTP_ForceUserLogout(user_id);
  1591. }
  1592. /**
  1593. * @brief Смена пароля пользователя
  1594. * @retval None
  1595. */
  1596. int HTTP_ChangeUserPwd(char *bufIn, char *bufOut, uint16_t lenBufIn, uint16_t *lenBufOut)
  1597. {
  1598. char tempStr[110];
  1599. char value[20];
  1600. char login[20];
  1601. char password[20];
  1602. uint8_t valueLen, valueLen2, user_id;
  1603. char WebLogin[MAX_WEB_LOGIN_LEN];
  1604. (void)lenBufIn;
  1605. memset(login, 0, 20);
  1606. memset(password, 0, 20);
  1607. memset(tempStr, 0, 50);
  1608. memset(value, 0, 20);
  1609. ClearParamString(bufIn);
  1610. strncpy(tempStr, bufIn, 110);
  1611. strcpy(bufOut, HTTP_200_OK);
  1612. if (GetParamValue(tempStr, "username=", login, &valueLen) &&
  1613. GetParamValue(tempStr, "oldpass=", password, &valueLen))
  1614. {
  1615. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++)
  1616. {
  1617. memset(value, 0, 20);
  1618. memset(WebLogin, 0, MAX_WEB_LOGIN_LEN);
  1619. GetUserLogin(user_id, WebLogin, &valueLen);
  1620. GetUserPassword(user_id, value, &valueLen2);
  1621. /* Check login and password */
  1622. if ((strncmp(WebLogin, login, MAX_WEB_LOGIN_LEN) == 0) &&
  1623. (memcmp(password, value, 11) == 0))
  1624. {
  1625. memset(password, 0, 20);
  1626. if (GetParamValue(tempStr, "newpass=", password, &valueLen))
  1627. {
  1628. memcpy(sSettings.sAuth[user_id].password, password, 11);
  1629. HTTP_SaveSettings();
  1630. log_event_data(LOG_PSW_CHANGE, "Администратор");
  1631. strcat(bufOut, "Пароль успешно изменён");
  1632. *lenBufOut = strlen(bufOut);
  1633. return SEND_REQUIRED_YES;
  1634. }
  1635. else {
  1636. strcat(bufOut, "Введены некорректные данные!");
  1637. *lenBufOut = strlen(bufOut);
  1638. return SEND_REQUIRED_YES;
  1639. }
  1640. }
  1641. }
  1642. strcat(bufOut, "Введён неверный пароль!");
  1643. *lenBufOut = strlen(bufOut);
  1644. return SEND_REQUIRED_YES;
  1645. }
  1646. else {
  1647. strcat(bufOut, "Введены некорректные данные!");
  1648. *lenBufOut = strlen(bufOut);
  1649. return SEND_REQUIRED_YES;
  1650. }
  1651. }
  1652. // -----------------------------------------------------------------------------
  1653. //
  1654. //
  1655. // SSL тесты
  1656. //
  1657. //
  1658. // -----------------------------------------------------------------------------
  1659. //#include "stm32f4xx.h"
  1660. #include "rtc.h"
  1661. /* PolarSSL includes */
  1662. #include "polarssl/net.h"
  1663. #include "polarssl/ssl.h"
  1664. #include "polarssl/havege.h"
  1665. #include "polarssl/certs.h"
  1666. #include "polarssl/x509.h"
  1667. /* Private typedef -----------------------------------------------------------*/
  1668. /* Private define ------------------------------------------------------------*/
  1669. #define DEBUG_LEVEL 1 /* Set DEBUG_LEVEL if you want to enable SSL debug
  1670. option, this should be set to 2, 3, 4 or 5 */
  1671. #define HTTP_RESPONSE "<p><p>Successful connection using: %s\r\n"
  1672. /* Format of dynamic web page */
  1673. #define PAGE_START \
  1674. "<html>\
  1675. <head>\
  1676. </head>\
  1677. <BODY onLoad=\"window.setTimeout(&quot;location.href='index.html'&quot;,1000)\" bgcolor=\"#FFFFFF\" text=\"#000000\">\
  1678. <font size=\"4\" color=\"#0000FF\"><b>STM32F407xx : SSL Server Demo not using HW Crypto :<)</font></b></i>\
  1679. <br><br><pre>\r\nPage Hits = "
  1680. #define PAGE_END \
  1681. " \r\n</pre><br><br><hr>\
  1682. <font size=\"3\" color=\"#808080\">All rights reserved ©2017 ROTEK\
  1683. \r\n</font></BODY>\
  1684. </html>"
  1685. /* Private macro -------------------------------------------------------------*/
  1686. /* Private variables ---------------------------------------------------------*/
  1687. /* SSL structures */
  1688. rng_state rngs;
  1689. ssl_context ssl;
  1690. ssl_session ssn;
  1691. x509_cert srvcert;
  1692. rsa_context rsa;
  1693. uint32_t nPageHits = 0;
  1694. /* Private functions ---------------------------------------------------------*/
  1695. /*
  1696. * Computing a "safe" DH-1024 prime can take a very
  1697. * long time, so a precomputed value is provided below.
  1698. * You may run dh_genprime to generate a new value.
  1699. */
  1700. char *my_dhm_P =
  1701. "E4004C1F94182000103D883A448B3F80" \
  1702. "2CE4B44A83301270002C20D0321CFD00" \
  1703. "11CCEF784C26A400F43DFB901BCA7538" \
  1704. "F2C6B176001CF5A0FD16D2C48B1D0C1C" \
  1705. "F6AC8E1DA6BCC3B4E1F96B0564965300" \
  1706. "FFA1D0B601EB2800F489AA512C4B248C" \
  1707. "01F76949A60BB7F00A40B1EAB64BDD48" \
  1708. "E8A700D60B7F1200FA8E77B0A979DABF";
  1709. char *my_dhm_G = "4";
  1710. /*
  1711. * Sorted by order of preference
  1712. */
  1713. int my_ciphersuites[] =
  1714. {
  1715. SSL_EDH_RSA_AES_256_SHA,
  1716. SSL_EDH_RSA_CAMELLIA_256_SHA,
  1717. SSL_EDH_RSA_AES_128_SHA,
  1718. SSL_EDH_RSA_CAMELLIA_128_SHA,
  1719. SSL_EDH_RSA_DES_168_SHA,
  1720. SSL_RSA_AES_256_SHA,
  1721. SSL_RSA_CAMELLIA_256_SHA,
  1722. SSL_RSA_AES_128_SHA,
  1723. SSL_RSA_CAMELLIA_128_SHA,
  1724. SSL_RSA_DES_168_SHA,
  1725. SSL_RSA_RC4_128_SHA,
  1726. SSL_RSA_RC4_128_MD5,
  1727. 0
  1728. };
  1729. void my_debug(void *ctx, int level, const char *str)
  1730. {
  1731. if(level < DEBUG_LEVEL)
  1732. {
  1733. printf("\r%s", str);
  1734. }
  1735. }
  1736. /*
  1737. * These session callbacks use a simple chained list
  1738. * to store and retrieve the session information.
  1739. */
  1740. ssl_session *s_list_1st = NULL;
  1741. ssl_session *cur, *prv;
  1742. static int my_get_session(ssl_context *ssl)
  1743. {
  1744. time_t t = RTC_GetUnixTime(); //time(NULL);
  1745. if(ssl->resume == 0)
  1746. return(1);
  1747. cur = s_list_1st;
  1748. prv = NULL;
  1749. while(cur != NULL)
  1750. {
  1751. prv = cur;
  1752. cur = cur->next;
  1753. if(ssl->timeout != 0 && t - prv->start > ssl->timeout)
  1754. continue;
  1755. if( ssl->session->ciphersuite != prv->ciphersuite ||
  1756. ssl->session->length != prv->length)
  1757. continue;
  1758. if(memcmp( ssl->session->id, prv->id, prv->length ) != 0)
  1759. continue;
  1760. memcpy(ssl->session->master, prv->master, 48);
  1761. return(0);
  1762. }
  1763. return(1);
  1764. }
  1765. static int my_set_session(ssl_context *ssl)
  1766. {
  1767. time_t t = RTC_GetUnixTime(); //time(NULL);
  1768. cur = s_list_1st;
  1769. prv = NULL;
  1770. while(cur != NULL)
  1771. {
  1772. if(ssl->timeout != 0 && t - cur->start > ssl->timeout)
  1773. break; /* expired, reuse this slot */
  1774. if(memcmp( ssl->session->id, cur->id, cur->length ) == 0)
  1775. break; /* client reconnected */
  1776. prv = cur;
  1777. cur = cur->next;
  1778. }
  1779. if(cur == NULL)
  1780. {
  1781. cur = (ssl_session *) malloc(sizeof(ssl_session));
  1782. if(cur == NULL)
  1783. return(1);
  1784. if(prv == NULL)
  1785. s_list_1st = cur;
  1786. else prv->next = cur;
  1787. }
  1788. memcpy(cur, ssl->session, sizeof(ssl_session));
  1789. return(0);
  1790. }
  1791. /**
  1792. * @brief SSL Server task.
  1793. * @param pvParameters not used
  1794. * @retval None
  1795. */
  1796. void ssl_server(void *pvParameters)
  1797. {
  1798. int ret, len;
  1799. int listen_fd;
  1800. int client_fd;
  1801. char buf[1024];
  1802. char CookieBuf[50];
  1803. char *CookiePtr = NULL;
  1804. char name[MAX_WEB_COOKIE_LEN];
  1805. char id[MAX_WEB_COOKIE_LEN];
  1806. uint8_t nameLen = 0, idLen = 0;
  1807. struct fs_file file = {0, 0};
  1808. memset(&srvcert, 0, sizeof(x509_cert));
  1809. // 1. Load the certificates and private RSA key
  1810. //printf("\n\r Loading the server certificates and key...");
  1811. // This demonstration program uses embedded test certificates.
  1812. // Instead, you may want to use x509parse_crtfile() to read the
  1813. // server and CA certificates, as well as x509parse_keyfile().
  1814. ret = x509parse_crt(&srvcert, (unsigned char *) test_srv_crt, strlen(test_srv_crt));
  1815. if(ret != 0)
  1816. {
  1817. //printf(" failed\n ! x509parse_crt returned %d\n\r", ret);
  1818. goto exit;
  1819. }
  1820. ret = x509parse_crt(&srvcert, (unsigned char *) test_ca_crt, strlen(test_ca_crt));
  1821. if(ret != 0)
  1822. {
  1823. //printf(" failed\n ! x509parse_crt returned %d\n\r", ret);
  1824. goto exit;
  1825. }
  1826. rsa_init( &rsa, RSA_PKCS_V15, 0 );
  1827. ret = x509parse_key(&rsa, (unsigned char *) test_srv_key, strlen(test_srv_key), NULL, 0);
  1828. if( ret != 0 )
  1829. {
  1830. //printf(" failed\n ! x509parse_key returned %d\n\r", ret);
  1831. goto exit;
  1832. }
  1833. // 2. Setup the listening TCP socket
  1834. //printf("\n\r Bind to https port ...");
  1835. // Bind the connection to https port : 443
  1836. ret = net_bind(&listen_fd, NULL, 443);
  1837. if(ret != 0)
  1838. {
  1839. //printf(" failed\n ! net_bind returned %d\n\r", ret);
  1840. goto exit;
  1841. }
  1842. //printf(" ok\n\r");
  1843. // 3. Wait until a client connects
  1844. for(;;)
  1845. {
  1846. //printf("\n\r Waiting for a remote connection ...");
  1847. ret = net_accept(listen_fd, &client_fd, NULL);
  1848. if(ret != 0)
  1849. {
  1850. //printf(" failed\n ! net_accept returned %d\n\n", ret);
  1851. goto exit;
  1852. }
  1853. //printf(" ok\n");
  1854. // 4. Initialize the session data
  1855. //printf("\n\r Setting up the RNG and SSL data....");
  1856. // Initialize the SSL context
  1857. ret = ssl_init(&ssl);
  1858. if(ret != 0)
  1859. {
  1860. //printf(" failed\n ! ssl_init returned %d\n\n", ret);
  1861. goto accept;
  1862. }
  1863. //printf(" ok\n");
  1864. // Set the current session as SSL server
  1865. ssl_set_endpoint(&ssl, SSL_IS_SERVER);
  1866. // No certificate verification
  1867. ssl_set_authmode(&ssl, SSL_VERIFY_NONE);
  1868. // Set the random number generator callback function
  1869. ssl_set_rng(&ssl, RandVal, &rngs);
  1870. // Set the debug callback function
  1871. //ssl_set_dbg(&ssl, my_debug, stdout);
  1872. // Set read and write callback functions
  1873. ssl_set_bio(&ssl, net_recv, &client_fd, net_send, &client_fd);
  1874. // Set the session callback functions
  1875. ssl_set_scb(&ssl, my_get_session, my_set_session);
  1876. // The list of ciphersuites to be used in this session
  1877. ssl_set_ciphersuites(&ssl, my_ciphersuites);
  1878. // Set the session resuming flag, timeout and session context
  1879. ssl_set_session(&ssl, 1, 0, &ssn);
  1880. memset(&ssn, 0, sizeof(ssl_session));
  1881. // Set the data required to verify peer certificate
  1882. ssl_set_ca_chain(&ssl, srvcert.next, NULL, NULL);
  1883. // Set own certificate and private key
  1884. ssl_set_own_cert(&ssl, &srvcert, &rsa);
  1885. // Set the Diffie-Hellman public P and G values
  1886. ssl_set_dh_param(&ssl, my_dhm_P, my_dhm_G);
  1887. // 5. Handshake protocol
  1888. //printf("\n\r Performing the SSL/TLS handshake...");
  1889. // Perform the SSL handshake protocol
  1890. while((ret = ssl_handshake(&ssl)) != 0)
  1891. {
  1892. if(ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
  1893. {
  1894. //printf(" failed\n ! ssl_handshake returned %d\n\n", ret);
  1895. goto accept;
  1896. }
  1897. }
  1898. //printf(" ok\n");
  1899. // 6. Read the HTTP Request
  1900. //printf("\n\r <= Read from client :");
  1901. do
  1902. {
  1903. len = sizeof(buf) - 1;
  1904. memset(receiveBuf, 0, RECIVE_BUF_MAX_LEN);
  1905. // Read decrypted application data
  1906. ret = ssl_read(&ssl, (unsigned char*)receiveBuf, receivedBufLen);
  1907. if(ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE)
  1908. continue;
  1909. if(ret <= 0)
  1910. {
  1911. switch(ret)
  1912. {
  1913. case POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY:
  1914. printf("\n\r connection was closed \n");
  1915. break;
  1916. case POLARSSL_ERR_NET_CONN_RESET:
  1917. printf("\n\r connection was reset by peer\n");
  1918. break;
  1919. default:
  1920. printf("\n\r ssl_read returned %d\n", ret);
  1921. break;
  1922. }
  1923. break;
  1924. }
  1925. len = ret;
  1926. // Display the length of read data
  1927. //printf("\n\r Successfully read %d bytes from client \n\r",len);
  1928. }while(0);
  1929. // -------------------------------------------------------------------------
  1930. //receivedBufLen = p->tot_len;
  1931. //memcpy(receiveBuf, p->payload , receivedBufLen);
  1932. receiveBuf[receivedBufLen] = '\0';
  1933. // printf("receive %s \r\n", receiveBuf);
  1934. // Get cookie "uname" value
  1935. CookiePtr = strstr(receiveBuf, "uname=");
  1936. strncpy(CookieBuf, CookiePtr, 50);
  1937. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  1938. memset(name, 0, MAX_WEB_COOKIE_LEN);
  1939. GetCookieValue(CookieBuf, "uname=", name, &nameLen);
  1940. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  1941. //printf("********uname= %s\r\n", name);
  1942. // Get cookie "id" value
  1943. CookiePtr = strstr(receiveBuf, "id=");
  1944. strncpy(CookieBuf, CookiePtr, 50);
  1945. //printf("********CookieBuf1= %s\r\n", CookieBuf);
  1946. memset(id, 0, MAX_WEB_COOKIE_LEN);
  1947. GetCookieValue(CookieBuf, "id=", id, &idLen);
  1948. //printf("********CookieBuf2= %s\r\n", CookieBuf);
  1949. //printf("********id= %s\r\n", id);
  1950. // Id of currently logged-in user
  1951. uint8_t user_id;
  1952. // Level of currently logged-in user
  1953. seclevel = 0xFF;
  1954. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  1955. HTTP_GetUserCookie(user_id, CookieBuf, &idLen);
  1956. if (strncmp(id, CookieBuf, idLen) == 0 ) {
  1957. GetUserLevelInt(user_id, &seclevel);
  1958. Authenticated = true;
  1959. break;
  1960. }
  1961. Authenticated = false;
  1962. seclevel = 0xFF;
  1963. }
  1964. if ( Authenticated == false && sSettings.sRADIUS.Auth_enable == false)
  1965. {
  1966. HTTP_LOGIN(sendBuf, &sendBufLoadLen);
  1967. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  1968. }
  1969. else if ( Authenticated == false )//&& sSettings.sRADIUS.Auth_enable == true
  1970. {
  1971. if (strncmp(receiveBuf, "GET /main.css", 13) == 0) // +
  1972. {
  1973. fs_open("/main.css", &file);
  1974. ssl_sendframes(&ssl, file.data, file.len);
  1975. }
  1976. else if (strncmp(receiveBuf, "GET /rotek.png", 14) == 0) // +
  1977. {
  1978. fs_open("/rotek.png", &file);
  1979. ssl_sendframes(&ssl, file.data, file.len);
  1980. }
  1981. else if (strncmp(receiveBuf, "GET /favicon.ico", 16) == 0) // ?
  1982. {
  1983. fs_open("/favicon.ico", &file);
  1984. ssl_sendframes(&ssl, file.data, file.len);
  1985. }
  1986. else if (strncmp(receiveBuf, "GET /role.js", 12) == 0)
  1987. {
  1988. fs_open("/role.js", &file);
  1989. ssl_sendframes(&ssl, file.data, file.len);
  1990. }
  1991. else if ((strncmp(receiveBuf, "POST /login.cgi", 15) == 0) || (log_post_reqn > 0))
  1992. {
  1993. uint32_t i, offset = 0, req_data_received = 0;
  1994. post_data_count = Parse_Content_Length(receiveBuf, receivedBufLen);
  1995. if (post_data_count < MAX_POST_REQ_LEN)
  1996. {
  1997. memset(post_req_data, 0, MAX_POST_REQ_LEN);
  1998. for (i = 0; i < receivedBufLen; i++)
  1999. {
  2000. if (strncmp ((char*)(receiveBuf+i), "\r\n\r\n", 4) == 0)
  2001. {
  2002. offset = i+4;
  2003. break;
  2004. }
  2005. }
  2006. req_data_received = receivedBufLen - offset;
  2007. if (offset != 0)
  2008. {
  2009. if (req_data_received < post_data_count)
  2010. {
  2011. snprintf(post_req_data, req_data_received, "%s", receiveBuf);
  2012. post_data_count -= req_data_received;
  2013. }
  2014. else
  2015. {
  2016. strncat(post_req_data, (char *)(receiveBuf + offset), post_data_count);
  2017. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES)
  2018. {
  2019. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2020. }
  2021. else
  2022. {
  2023. fs_open("/login.html", &file);
  2024. ssl_sendframes(&ssl, file.data, file.len);
  2025. }
  2026. post_data_count = 0;
  2027. log_post_reqn = 0;
  2028. }
  2029. }
  2030. /* request was fragmented before "\r\n\r\n" */
  2031. else
  2032. {
  2033. log_post_reqn++;
  2034. /* wait max 2 requests */
  2035. if (log_post_reqn > 1)
  2036. {
  2037. /* Redirect to login page */
  2038. fs_open("/login.html", &file);
  2039. ssl_sendframes(&ssl, file.data, file.len);
  2040. /* End reqest */
  2041. post_data_count = 0;
  2042. log_post_reqn = 0;
  2043. }
  2044. }
  2045. }
  2046. else
  2047. {
  2048. printf("Too long POST request!\r\n");
  2049. /* Ignore request */
  2050. post_data_count = 0;
  2051. log_post_reqn = 0;
  2052. /* Redirect to login page */
  2053. fs_open("/login.html", &file);
  2054. ssl_sendframes(&ssl, file.data, file.len);
  2055. }
  2056. }
  2057. else if (post_data_count > 0)
  2058. {
  2059. strncat(post_req_data, receiveBuf, post_data_count);
  2060. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), &sendBufLoadLen) == SEND_REQUIRED_YES)
  2061. {
  2062. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2063. }
  2064. else
  2065. {
  2066. fs_open("/login.html", &file);
  2067. ssl_sendframes(&ssl, file.data, file.len);
  2068. }
  2069. post_data_count = 0;
  2070. log_post_reqn = 0;
  2071. }
  2072. else
  2073. {
  2074. fs_open("/login.html", &file);
  2075. ssl_sendframes(&ssl, file.data, file.len);
  2076. }
  2077. }
  2078. else if ( Authenticated == true )
  2079. {
  2080. if (strncmp(receiveBuf, "GET /main.css", 13) == 0) // +
  2081. {
  2082. fs_open("/main.css", &file);
  2083. ssl_sendframes(&ssl, file.data, file.len);
  2084. }
  2085. else if (strncmp(receiveBuf, "GET /rotek.png", 14) == 0) // +
  2086. {
  2087. fs_open("/rotek.png", &file);
  2088. ssl_sendframes(&ssl, file.data, file.len);
  2089. }
  2090. else if (strncmp(receiveBuf, "GET /favicon.ico", 16) == 0) // ?
  2091. {
  2092. fs_open("/favicon.ico", &file);
  2093. ssl_sendframes(&ssl, file.data, file.len);
  2094. }
  2095. else if (strncmp(receiveBuf, "GET /main.js", 12) == 0) // +
  2096. {
  2097. fs_open("/main.js", &file);
  2098. ssl_sendframes(&ssl, file.data, file.len);
  2099. }
  2100. else if (strncmp(receiveBuf, "GET /role.js", 12) == 0)
  2101. {
  2102. fs_open("/role.js", &file);
  2103. ssl_sendframes(&ssl, file.data, file.len);
  2104. }
  2105. else if (strncmp(receiveBuf, "GET /settings.html", 18) == 0) // +
  2106. {
  2107. HTTP_UpdateUserLoginTime(user_id);
  2108. if (seclevel == 0)
  2109. {
  2110. fs_open("/settings.html", &file);
  2111. ssl_sendframes(&ssl, file.data, file.len);
  2112. }
  2113. else
  2114. {
  2115. fs_open("/index.html", &file);
  2116. ssl_sendframes(&ssl, file.data, file.len);
  2117. }
  2118. }
  2119. else if (strncmp(receiveBuf, "GET /info.html", 14) == 0) // +
  2120. {
  2121. HTTP_UpdateUserLoginTime(user_id);
  2122. fs_open("/info.html", &file);
  2123. ssl_sendframes(&ssl, file.data, file.len);
  2124. }
  2125. else if (strncmp(receiveBuf, "GET /history.html", 17) == 0)
  2126. {
  2127. HTTP_UpdateUserLoginTime(user_id);
  2128. fs_open("/history.html", &file);
  2129. ssl_sendframes(&ssl, file.data, file.len);
  2130. }
  2131. else if (strncmp(receiveBuf, "GET /ups_history.html", 21) == 0)
  2132. {
  2133. HTTP_UpdateUserLoginTime(user_id);
  2134. fs_open("/ups_history.html", &file);
  2135. ssl_sendframes(&ssl, file.data, file.len);
  2136. }
  2137. else if (strncmp(receiveBuf, "GET /getJson.cgi", 16) == 0) // +
  2138. {
  2139. HTTP_GetParamsPage1(sendBuf);
  2140. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2141. }
  2142. else if (strncmp(receiveBuf, "GET /settings.cgi", 17) == 0) // +
  2143. {
  2144. SET_PAGE = SET_PAGE_PAGE2;
  2145. if (seclevel == 0)
  2146. {
  2147. if (HTTP_SettingsPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  2148. {
  2149. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2150. }
  2151. }
  2152. }
  2153. else if (strncmp(receiveBuf, "POST /settings.cgi", 18) == 0)
  2154. {
  2155. strncat(receiveBuf, " ", 1);
  2156. HTTP_SetSettings(receiveBuf, receivedBufLen);
  2157. memset(sendBuf, 0, SEND_BUF_MAX_LEN);
  2158. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  2159. strcat(sendBuf, "\r\n\r\n");
  2160. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/settings.html\"/></head></html>\r\n\r\n");
  2161. sendBufLoadLen = strlen(sendBuf);
  2162. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2163. }
  2164. else if (strncmp(receiveBuf, "GET /info.cgi", 13) == 0) // +
  2165. {
  2166. if (HTTP_InfoPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  2167. {
  2168. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2169. }
  2170. }
  2171. else if (strncmp(receiveBuf, "POST /info.cgi", 14) == 0)
  2172. {
  2173. strncat(receiveBuf, " ", 1);
  2174. HTTP_SetInfo(receiveBuf, receivedBufLen);
  2175. memset(sendBuf, 0, SEND_BUF_MAX_LEN);
  2176. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  2177. strcat(sendBuf, "\r\n\r\n");
  2178. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/info.html\"/></head></html>\r\n\r\n");
  2179. sendBufLoadLen = strlen(sendBuf);
  2180. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2181. }
  2182. else if (strncmp(receiveBuf, "GET /history.cgi", 16) == 0)
  2183. {
  2184. int res;
  2185. res = HTTP_HistoryPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2186. if (res == SEND_REQUIRED_FILE)
  2187. {
  2188. hs->file = sendBuf;
  2189. hs->left = sendBufLoadLen;
  2190. send_data(pcb, hs);
  2191. tcp_sent(pcb, http_sent_history);
  2192. tcp_err(pcb, http_sent_log_err);
  2193. }
  2194. else if (res == SEND_REQUIRED_YES)
  2195. {
  2196. hs->file = sendBuf;
  2197. hs->left = sendBufLoadLen;
  2198. send_data(pcb, hs);
  2199. tcp_sent(pcb, http_sent);
  2200. }
  2201. }
  2202. else if (strncmp(receiveBuf, "GET /ups_history.cgi", 19) == 0)
  2203. {
  2204. int res;
  2205. res = HTTP_UpsHistoryPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2206. if (res == SEND_REQUIRED_FILE)
  2207. {
  2208. hs->file = sendBuf;
  2209. hs->left = sendBufLoadLen;
  2210. send_data(pcb, hs);
  2211. tcp_sent(pcb, http_sent_log);
  2212. tcp_err(pcb, http_sent_log_err);
  2213. }
  2214. else if (res == SEND_REQUIRED_YES)
  2215. {
  2216. hs->file = sendBuf;
  2217. hs->left = sendBufLoadLen;
  2218. send_data(pcb, hs);
  2219. tcp_sent(pcb, http_sent);
  2220. }
  2221. }
  2222. /* Тест АКБ ИБП */
  2223. else if (strncmp(receiveBuf, "POST /bat_test.cgi", 18) == 0)
  2224. {
  2225. HTTP_UPSTest(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2226. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2227. }
  2228. /* Выключение ИБП */
  2229. else if (strncmp(receiveBuf, "POST /ups_power.cgi", 19) == 0)
  2230. {
  2231. HTTP_UPSshutdown(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2232. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2233. }
  2234. /* Сброс настроек и сохранине */
  2235. else if (strncmp(receiveBuf, "GET /reset.cgi", 14) == 0)
  2236. {
  2237. HTTP_ResetSettings();
  2238. HTTP_SaveSettings();
  2239. fs_open("/settings.html", &file);
  2240. ssl_sendframes(&ssl, file.data, file.len);
  2241. }
  2242. /* Перезагрузка контроллера */
  2243. else if (strncmp(receiveBuf, "GET /reboot.cgi", 15) == 0)
  2244. {
  2245. HTTP_Reboot();
  2246. }
  2247. /* Подтверждение новых сетевых настроек */
  2248. else if (strncmp(receiveBuf, "GET /confirm.cgi", 16) == 0)
  2249. {
  2250. SetWebReinitFlag(false);
  2251. SetConfirmWebParamsFlag();
  2252. fs_open("/index.html", &file);
  2253. ssl_sendframes(&ssl, file.data, file.len);
  2254. }
  2255. /* Проверка пароля, переход в bootloader */
  2256. else if (strncmp(receiveBuf, "GET /fw_update.cgi", 18) == 0)
  2257. {
  2258. HTTP_ConfirmBootPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2259. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2260. }
  2261. /* Смена пароля пользователя */
  2262. else if (strncmp(receiveBuf, "POST /changepwd.cgi", 19) == 0)
  2263. {
  2264. HTTP_ChangeUserPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2265. ssl_sendframes(&ssl, file.data, file.len);
  2266. }
  2267. // На производстве
  2268. else if (strncmp(receiveBuf, "GET /setProdate.cgi", 19) == 0)
  2269. {
  2270. HTTP_Prodate(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2271. ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2272. }
  2273. else
  2274. {
  2275. HTTP_UpdateUserLoginTime(user_id);
  2276. fs_open("/index.html", &file); // +
  2277. ssl_sendframes(&ssl, file.data, file.len);
  2278. }
  2279. }
  2280. //}
  2281. /*
  2282. if (strncmp(buf, "GET /main.css", 13) == 0) // +
  2283. {
  2284. fs_open("/main.css", &file);
  2285. ssl_sendframes(&ssl, file.data, file.len);
  2286. }
  2287. else if (strncmp(buf, "GET /rotek.png", 14) == 0) // +
  2288. {
  2289. fs_open("/rotek.png", &file);
  2290. ssl_sendframes(&ssl, file.data, file.len);
  2291. }
  2292. else if (strncmp(buf, "GET /favicon.ico", 16) == 0) // ?
  2293. {
  2294. fs_open("/favicon.ico", &file);
  2295. ssl_sendframes(&ssl, file.data, file.len);
  2296. }
  2297. else if (strncmp(buf, "GET /main.js", 12) == 0) // +
  2298. {
  2299. fs_open("/main.js", &file);
  2300. ssl_sendframes(&ssl, file.data, file.len);
  2301. }
  2302. else if (strncmp(buf, "GET /getJson.cgi", 16) == 0) // +
  2303. {
  2304. HTTP_GetParamsPage1(sendBuf);
  2305. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2306. }
  2307. else if (strncmp(buf, "GET /settings.html", 18) == 0) // +
  2308. {
  2309. fs_open("/settings.html", &file);
  2310. ssl_sendframes(&ssl, file.data, file.len);
  2311. }
  2312. else if (strncmp(buf, "GET /info.html", 14) == 0) // +
  2313. {
  2314. fs_open("/info.html", &file);
  2315. ssl_sendframes(&ssl, file.data, file.len);
  2316. }
  2317. else if (strncmp(buf, "GET /getJson.cgi", 16) == 0) // +
  2318. {
  2319. HTTP_GetParamsPage1(sendBuf);
  2320. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2321. }
  2322. else if (strncmp(buf, "GET /settings.cgi", 17) == 0) // +
  2323. {
  2324. SET_PAGE = SET_PAGE_PAGE2;
  2325. if (HTTP_SettingsPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  2326. {
  2327. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2328. }
  2329. else
  2330. {
  2331. fs_open("/settings.html", &file);
  2332. ssl_sendframes(&ssl, file.data, file.len);
  2333. }
  2334. }
  2335. else if (strncmp(buf, "GET /info.cgi", 13) == 0) // +
  2336. {
  2337. if (HTTP_InfoPage(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen) == SEND_REQUIRED_YES)
  2338. {
  2339. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2340. }
  2341. else
  2342. {
  2343. fs_open("/info.html", &file);
  2344. ssl_sendframes(&ssl, file.data, file.len);
  2345. }
  2346. }
  2347. // Сброс настроек и сохранине
  2348. else if (strncmp(buf, "GET /reset.cgi", 14) == 0)
  2349. {
  2350. HTTP_ResetSettings();
  2351. HTTP_SaveSettings();
  2352. fs_open("/settings.html", &file);
  2353. ssl_sendframes(&ssl, file.data, file.len);
  2354. }
  2355. // Перезагрузка контроллера
  2356. else if (strncmp(buf, "GET /reboot.cgi", 15) == 0)
  2357. {
  2358. HTTP_Reboot();
  2359. }
  2360. // Подтверждение новых сетевых настроек
  2361. else if (strncmp(buf, "GET /confirm.cgi", 16) == 0)
  2362. {
  2363. SetWebReinitFlag(false);
  2364. SetConfirmWebParamsFlag();
  2365. fs_open("/index.html", &file);
  2366. ssl_sendframes(&ssl, file.data, file.len);
  2367. }
  2368. // Проверка пароля, переход в bootloader
  2369. else if (strncmp(buf, "POST /checkpwd.cgi", 18) == 0)
  2370. {
  2371. HTTP_ConfirmBootPwd(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2372. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2373. }
  2374. // На производстве
  2375. else if (strncmp(buf, "GET /setProdate.cgi", 19) == 0)
  2376. {
  2377. HTTP_Prodate(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2378. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2379. }
  2380. // На производстве
  2381. else if (strncmp(buf, "GET /progon.cgi", 15) == 0)
  2382. {
  2383. HTTP_Progon(receiveBuf, sendBuf, receivedBufLen, &sendBufLoadLen);
  2384. ssl_sendframes(&ssl, sendBuf, strlen(sendBuf));
  2385. }
  2386. else
  2387. {
  2388. fs_open("/index.html", &file);
  2389. ssl_sendframes(&ssl, file.data, file.len);
  2390. }
  2391. // -------------------------------------------------------------------------
  2392. */
  2393. // Для теста
  2394. // 7. Write the Response
  2395. //printf("\n\r => Write to client :\n\r");
  2396. // Send the dynamic html page
  2397. //ssl_DynPage(&ssl);
  2398. // Close the connection
  2399. ssl_close_notify(&ssl);
  2400. goto accept;
  2401. exit:
  2402. // Close and delete the current session data: certificate, RSA key and SSL session
  2403. x509_free(&srvcert);
  2404. rsa_free(&rsa);
  2405. cur = s_list_1st;
  2406. while(cur != NULL)
  2407. {
  2408. prv = cur;
  2409. cur = cur->next;
  2410. memset(prv, 0, sizeof(ssl_session));
  2411. free(prv);
  2412. }
  2413. memset(&ssl, 0, sizeof(ssl_context));
  2414. accept:
  2415. // Wait 200s until next retry
  2416. vTaskDelay(200);
  2417. // Close and free the SSL context
  2418. net_close(client_fd);
  2419. ssl_free(&ssl);
  2420. }
  2421. }
  2422. /**
  2423. * @brief Create and send a dynamic Web Page. This page contains the list of
  2424. * running tasks and the number of page hits.
  2425. * @param ssl the SSL context
  2426. * @retval None
  2427. */
  2428. void ssl_DynPage(ssl_context *ssl)
  2429. {
  2430. portCHAR buf[2024];
  2431. portCHAR pagehits[10];
  2432. portCHAR getcipher[100];
  2433. uint32_t len = 0;
  2434. memset(buf, 0, 2024);
  2435. // Update the hit count
  2436. nPageHits++;
  2437. sprintf( pagehits, "%d", nPageHits );
  2438. sprintf( (char *) getcipher, HTTP_RESPONSE, ssl_get_ciphersuite(ssl));
  2439. // Generate the dynamic page
  2440. strcpy(buf, PAGE_START);
  2441. // Page header
  2442. strcat(buf, pagehits);
  2443. strcat((char *) buf, "<br><pre>** The list of tasks and their status **");
  2444. strcat((char *) buf, "<br><pre>---------------------------------------------");
  2445. strcat((char *) buf, "<br>Name State Priority Stack Num" );
  2446. //strcat((char *) buf, "<br>---------------------------------------------");
  2447. strcat((char *) buf, "<br>---------------------------------------------<br>");
  2448. // The list of tasks and their status
  2449. vTaskList((signed char *)buf + strlen(buf));
  2450. strcat((char *) buf, "<br>---------------------------------------------");
  2451. strcat((char *) buf, "<br>B : Blocked, R : Ready, D : Deleted, S : Suspended");
  2452. // The current cipher used
  2453. strcat(buf, getcipher);
  2454. // Page footer
  2455. strcat(buf, PAGE_END);
  2456. // Send the dynamically generated page
  2457. len = ssl_write(ssl, (unsigned char *)buf, strlen(buf));
  2458. // Display the length of application data
  2459. //printf( "\n Successfully write %d bytes to client\n\r", len);
  2460. }
  2461. /**
  2462. * @brief This function is used to send messages with size upper 16k bytes.
  2463. * @param ssl SSL context
  2464. * @param data buffer holding the data
  2465. * @param len how many bytes must be written
  2466. * @retval None
  2467. */
  2468. #define FRAME_SIZE (1000)
  2469. void ssl_sendframes( ssl_context *ssl, char *data, int datalen )
  2470. {
  2471. int index = 0;
  2472. int k = 0;
  2473. int lastframe, nbrframes;
  2474. // Calculate the number of frames
  2475. nbrframes = datalen / FRAME_SIZE;
  2476. // Send nbrframes frames
  2477. while(nbrframes > 0)
  2478. {
  2479. index = k * FRAME_SIZE;
  2480. ssl_write( ssl, (unsigned char *)(data + index), FRAME_SIZE );
  2481. nbrframes--;
  2482. k++;
  2483. }
  2484. // Send the last frame
  2485. index = k * FRAME_SIZE;
  2486. lastframe = datalen % FRAME_SIZE ;
  2487. ssl_write( ssl, (unsigned char *)(data + index), lastframe );
  2488. }
  2489. /**
  2490. * @brief Returns a 32-bit random number.
  2491. * @param arg not used
  2492. * @retval 32-bit random number
  2493. */
  2494. int RandVal(void* arg)
  2495. {
  2496. return (int)GetRandomNumber();
  2497. }