http_server.c 114 KB

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