http_server.c 96 KB

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