http_server.c 95 KB

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