http_server.c 100 KB

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