http_server.c 114 KB

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