http_server.c 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002
  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. char HTTP_RESPONSE[] = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n \
  2440. <h2>mbed TLS Test Server</h2>\r\n \
  2441. <p>Successful connection using: %s</p>\r\n";
  2442. static mbedtls_net_context listen_fd, client_fd;
  2443. static const uint8_t *pers = (uint8_t *)("ssl_server");
  2444. mbedtls_entropy_context entropy;
  2445. mbedtls_ctr_drbg_context ctr_drbg;
  2446. mbedtls_ssl_context ssl;
  2447. mbedtls_ssl_config conf;
  2448. mbedtls_x509_crt srvcert;
  2449. mbedtls_pk_context pkey;
  2450. char CookieBuf[51];
  2451. char *CookiePtr = NULL;
  2452. char name[MAX_WEB_COOKIE_LEN];
  2453. char id[MAX_WEB_COOKIE_LEN];
  2454. uint8_t nameLen = 0, idLen = 0;
  2455. uint8_t user_id; // Id of currently logged-in user
  2456. struct fs_file file = {0, 0};
  2457. //
  2458. void Cockie(void)
  2459. {
  2460. char* endPtr;
  2461. uint32_t len;
  2462. receiveBuf[receivedBufLen] = '\0';
  2463. printf("receive %s \r\n", receiveBuf);
  2464. // Get cookie "uname" value
  2465. memset(CookieBuf, 0, sizeof(CookieBuf));
  2466. CookiePtr = strstr(receiveBuf, "uname=");
  2467. endPtr = strstr(CookiePtr, "\r");
  2468. len = (endPtr - CookiePtr)+2;
  2469. if(len < 50)
  2470. strncpy(CookieBuf, CookiePtr,len);
  2471. else
  2472. strncpy(CookieBuf, CookiePtr, 50);
  2473. /// printf("********CookieBuf1= %s\r\n", CookieBuf);
  2474. memset(name, 0, MAX_WEB_COOKIE_LEN);
  2475. GetCookieValue(CookieBuf, "uname=", name, &nameLen);
  2476. // printf("********CookieBuf2= %s\r\n", CookieBuf);
  2477. // printf("********uname= %s\r\n", name);
  2478. memset(CookieBuf, 0, sizeof(CookieBuf));
  2479. // Get cookie "id" value
  2480. CookiePtr = strstr(receiveBuf, " id=");
  2481. if(len < 50)
  2482. strncpy(CookieBuf, CookiePtr,len);
  2483. else
  2484. strncpy(CookieBuf, CookiePtr, 50);
  2485. // printf("********CookieBuf1= %s\r\n", CookieBuf);
  2486. memset(id, 0, MAX_WEB_COOKIE_LEN);
  2487. GetCookieValue(CookieBuf, "id=", id, &idLen);
  2488. // printf("********ID= %s\r\n", id);
  2489. }
  2490. //
  2491. void getAuthenticatedState(void)
  2492. {
  2493. seclevel = 0xFF;
  2494. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  2495. HTTP_GetUserCookie(user_id, CookieBuf, &idLen);
  2496. if (strncmp(id, CookieBuf, idLen) == 0 ) {
  2497. GetUserLevelInt(user_id, &seclevel);
  2498. Authenticated = true;
  2499. break;
  2500. }
  2501. Authenticated = false;
  2502. seclevel = 0xFF;
  2503. }
  2504. }
  2505. //
  2506. void ssl_server(void *pvParameters)
  2507. {
  2508. SSL_SERVER_STATE ssl_state = SSL_ACCEPT;
  2509. char* sendPtr;
  2510. int ret;
  2511. mbedtls_net_init( &listen_fd );
  2512. mbedtls_net_init( &client_fd );
  2513. mbedtls_ssl_init( &ssl );
  2514. mbedtls_ssl_config_init( &conf );
  2515. mbedtls_x509_crt_init( &srvcert );
  2516. mbedtls_pk_init( &pkey );
  2517. mbedtls_entropy_init( &entropy );
  2518. mbedtls_ctr_drbg_init( &ctr_drbg );
  2519. mbedtls_platform_set_time(&MBEDTLS_GetTime);
  2520. #if defined(MBEDTLS_DEBUG_C)
  2521. mbedtls_debug_set_threshold(DEBUG_LEVEL);
  2522. mbedtls_ssl_conf_dbg(&conf, MBEDTLS_Debug, NULL);
  2523. #endif
  2524. // 1. Load the certificates and private RSA key
  2525. mbedtls_printf( "\r\n . Loading the server cert. and key..." );
  2526. ret = mbedtls_x509_crt_parse( &srvcert, (const unsigned char *) mbedtls_test_srv_crt, mbedtls_test_srv_crt_len );
  2527. if( ret != 0 )
  2528. {
  2529. mbedtls_printf( " failed\r\n ! mbedtls_x509_crt_parse returned %d\r\n", ret );
  2530. ssl_state = SSL_CRITICAL_ERROR;
  2531. }
  2532. ret = mbedtls_pk_parse_key( &pkey, (const unsigned char *) mbedtls_test_srv_key, mbedtls_test_srv_key_len, NULL, 0 );
  2533. if( ret != 0 )
  2534. {
  2535. mbedtls_printf( " failed\r\n ! mbedtls_pk_parse_key returned %d\r\n", ret );
  2536. ssl_state = SSL_CRITICAL_ERROR;
  2537. }
  2538. mbedtls_printf( " ok\r\n" );
  2539. // 2. Setup the listening TCP socket
  2540. mbedtls_printf( " . Bind on https://localhost:443/ ..." );
  2541. if((ret = mbedtls_net_bind(&listen_fd, NULL, "443", MBEDTLS_NET_PROTO_TCP )) != 0)
  2542. {
  2543. mbedtls_printf( " failed\n ! mbedtls_net_bind returned %d\r\n", ret );
  2544. ssl_state = SSL_CRITICAL_ERROR;
  2545. }
  2546. mbedtls_printf( " ok\r\n" );
  2547. // 3. Seed the RNG
  2548. mbedtls_printf( " . Seeding the random number generator..." );
  2549. if((ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) pers, strlen( (char *)pers))) != 0)
  2550. {
  2551. mbedtls_printf( " failed\r\n ! mbedtls_ctr_drbg_seed returned %d\r\n", ret );
  2552. ssl_state = SSL_CRITICAL_ERROR;
  2553. }
  2554. mbedtls_printf( " ok\r\n" );
  2555. // 4. Setup stuff
  2556. mbedtls_printf( " . Setting up the SSL data...." );
  2557. if( ( ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
  2558. {
  2559. mbedtls_printf( " failed\r\n ! mbedtls_ssl_config_defaults returned %d\r\n", ret );
  2560. ssl_state = SSL_CRITICAL_ERROR;
  2561. }
  2562. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  2563. mbedtls_ssl_conf_ca_chain(&conf, srvcert.next, NULL);
  2564. if( ( ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, &pkey ) ) != 0)
  2565. {
  2566. mbedtls_printf( " failed\r\n ! mbedtls_ssl_conf_own_cert returned %d\r\n", ret );
  2567. ssl_state = SSL_CRITICAL_ERROR;
  2568. }
  2569. if( ( ret = mbedtls_ssl_setup( &ssl, &conf ) ) != 0 )
  2570. {
  2571. mbedtls_printf( " failed\r\n ! mbedtls_ssl_setup returned %d\r\n", ret );
  2572. ssl_state = SSL_CRITICAL_ERROR;
  2573. }
  2574. mbedtls_printf( " ok\r\n" );
  2575. for (;;) {
  2576. switch (ssl_state)
  2577. {
  2578. case SSL_ACCEPT :
  2579. //mbedtls_net_free( &client_fd );
  2580. mbedtls_ssl_session_reset( &ssl );
  2581. mbedtls_printf( " . Waiting for a remote connection ...\r\n" );
  2582. if((ret = mbedtls_net_accept(&listen_fd, &client_fd, NULL, 0, NULL)) != 0) {
  2583. mbedtls_printf( " failed\r\n ! mbedtls_net_accept returned %d\r\n", ret );
  2584. ssl_state = SSL_ERROR;
  2585. }
  2586. else {
  2587. //mbedtls_ssl_init(&ssl);
  2588. mbedtls_ssl_set_bio( &ssl, &client_fd, mbedtls_net_send, mbedtls_net_recv, NULL );//mbedtls_net_recv
  2589. mbedtls_printf( " ok\r\n" );
  2590. ssl_state = SSL_HANDSHAKE;
  2591. }
  2592. break;
  2593. case SSL_HANDSHAKE :
  2594. mbedtls_printf( " . Performing the SSL/TLS handshake..." );
  2595. handshakeTime = xTaskGetTickCount();
  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. printf("HANDSHAKE_TIME: %d ms\r\n", xTaskGetTickCount() - handshakeTime);
  2610. ssl_state = SSL_READ;
  2611. }
  2612. break;
  2613. case SSL_READ :
  2614. printf("SSL_READ\r\n");
  2615. if (SSL_ReadRoutine(&ssl, (unsigned char*)receiveBuf) <= 0)
  2616. ssl_state = SSL_ERROR;
  2617. else
  2618. ssl_state = SSL_PROCESSING;
  2619. break;
  2620. case SSL_PROCESSING :
  2621. printf("SSL_PROCESSING\r\n");
  2622. sendPtr = SSL_ProcessingRoutine(&sendBufLoadLen);
  2623. if (sendPtr)
  2624. ssl_state = SSL_WRITE;
  2625. else
  2626. ssl_state = SSL_ACCEPT; // ?
  2627. break;
  2628. case SSL_WRITE :
  2629. printf("SSL_WRITE\r\n");
  2630. SSL_WriteRoutine(&ssl, sendPtr, sendBufLoadLen);
  2631. // if (SSL_WriteRoutine(&ssl, sendPtr, sendBufLoadLen) == SSL_WRITE_OK)
  2632. ssl_state = SSL_CLOSE;
  2633. break;
  2634. case SSL_CLOSE :
  2635. printf("SSL_CLOSE\r\n");
  2636. mbedtls_ssl_close_notify(&ssl);
  2637. mbedtls_net_free(&client_fd);
  2638. //mbedtls_ssl_free( &ssl );
  2639. ssl_state = SSL_ACCEPT;
  2640. break;
  2641. case SSL_ERROR :
  2642. printf("SSL_ERROR\r\n");
  2643. //mbedtls_net_free(&client_fd);
  2644. //mbedtls_ssl_free( &ssl );
  2645. mbedtls_ssl_close_notify(&ssl);
  2646. mbedtls_net_free(&client_fd);
  2647. ssl_state = SSL_ACCEPT;
  2648. break;
  2649. case SSL_CRITICAL_ERROR:
  2650. printf("SSL_CRITICAL_ERROR\r\n");
  2651. mbedtls_x509_crt_free( &srvcert );
  2652. mbedtls_pk_free( &pkey );
  2653. mbedtls_ssl_free( &ssl );
  2654. mbedtls_ssl_config_free( &conf );
  2655. mbedtls_ctr_drbg_free( &ctr_drbg );
  2656. mbedtls_entropy_free( &entropy );
  2657. vTaskDelete(NULL);
  2658. break;
  2659. }
  2660. }
  2661. }
  2662. /**
  2663. * @brief Initialize the HTTPS server (start its thread)
  2664. */
  2665. void HTTPS_Init()
  2666. {
  2667. char buf[MAX_WEB_COOKIE_LEN];
  2668. uint8_t user_id;
  2669. for (user_id = 0; user_id < MAX_WEB_USERS; user_id++) {
  2670. // Flush user cookie by random value
  2671. sprintf(buf, "%X", (unsigned int)GetRandomNumber());
  2672. HTTP_SetUserCookie(buf, user_id);
  2673. // Create user logout timers
  2674. users[user_id].LogoutTimer = xTimerCreate("LogoutTmr", WEB_LOGOUT_TIME, pdFALSE, ( void * ) user_id, LogoutTimerCallback);
  2675. }
  2676. RepeatLoginTimer = xTimerCreate("LoginTmr", REPEAT_LOGIN_TIME, pdFALSE, ( void * ) 0, LoginTimerCallback);
  2677. }
  2678. //
  2679. int SSL_ReadRoutine(mbedtls_ssl_context *ssl, unsigned char* recvBuf)
  2680. {
  2681. int ret;
  2682. mbedtls_printf( " < Read from client:" );
  2683. do
  2684. {
  2685. receivedBufLen = RECIVE_BUF_MAX_LEN - 1;
  2686. memset(recvBuf, 0, RECIVE_BUF_MAX_LEN);
  2687. ret = mbedtls_ssl_read(ssl, receiveBuf, receivedBufLen);
  2688. if( ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE )
  2689. continue;
  2690. if( ret <= 0 )
  2691. {
  2692. switch( ret )
  2693. {
  2694. case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
  2695. mbedtls_printf( " connection was closed gracefully\r\n" );
  2696. break;
  2697. case MBEDTLS_ERR_NET_CONN_RESET:
  2698. mbedtls_printf( " connection was reset by peer\r\n" );
  2699. break;
  2700. default:
  2701. mbedtls_printf( "mbedtls_ssl_read returned -0x%x\r\n", -ret );
  2702. break;
  2703. }
  2704. return ret;
  2705. }
  2706. receivedBufLen = ret;
  2707. //mbedtls_printf( " %d bytes read\r\n%s", len, (char *) receiveBuf );
  2708. //mbedtls_printf( " %d bytes read\r\n", receivedBufLen);
  2709. /* printf("\r\n\r\n");
  2710. printf(receiveBuf);
  2711. printf("\r\n");*/
  2712. } while(0);
  2713. }
  2714. //
  2715. SSL_SERVER_STATE SSL_WriteRoutine(mbedtls_ssl_context *ssl, char *data, int datalen)
  2716. {
  2717. return SSL_SendFrames(ssl, data, datalen);
  2718. }
  2719. //
  2720. char* SSL_ProcessingRoutine(uint16_t* sendLen)
  2721. {
  2722. /**sendLen = strlen(HTTP_RESPONSE);
  2723. return HTTP_RESPONSE;*/
  2724. Cockie();
  2725. getAuthenticatedState();
  2726. if ( Authenticated == false && sSettings.sRADIUS.Auth_enable == false)
  2727. {
  2728. HTTP_LOGIN(sendBuf, sendLen);
  2729. return sendBuf;
  2730. }
  2731. else if (!Authenticated)//&& sSettings.sRADIUS.Auth_enable == true
  2732. {
  2733. return AuthenticatedFalseRoutine(sendLen);
  2734. }
  2735. else
  2736. {
  2737. return AuthenticatedTrueRoutine(sendLen);
  2738. }
  2739. }
  2740. //
  2741. char* AuthenticatedFalseRoutine(uint16_t* sendLen)
  2742. {
  2743. if (strncmp(receiveBuf, "GET /main.css", 13) == 0) // +
  2744. {
  2745. fs_open("/main.css", &file);
  2746. *sendLen = file.len;
  2747. return file.data;
  2748. }
  2749. else if (strncmp(receiveBuf, "GET /rotek.png", 14) == 0) // +
  2750. {
  2751. fs_open("/rotek.png", &file);
  2752. *sendLen = file.len;
  2753. return file.data;
  2754. }
  2755. else if (strncmp(receiveBuf, "GET /favicon.ico", 16) == 0) // ?
  2756. {
  2757. fs_open("/favicon.ico", &file);
  2758. *sendLen = file.len;
  2759. return file.data;
  2760. }
  2761. else if (strncmp(receiveBuf, "GET /role.js", 12) == 0)
  2762. {
  2763. fs_open("/role.js", &file);
  2764. *sendLen = file.len;
  2765. return file.data;
  2766. }
  2767. else if (strncmp(receiveBuf, "POST /login.cgi", 15) == 0)
  2768. {
  2769. uint32_t req_data_received = 0;
  2770. char *offset = 0;
  2771. post_data_count = Parse_Content_Length(receiveBuf, receivedBufLen);
  2772. if (post_data_count < MAX_POST_REQ_LEN)
  2773. {
  2774. memset(post_req_data, 0, MAX_POST_REQ_LEN);
  2775. offset = (strstr(receiveBuf, "\r\n\r\n")) + 4;
  2776. req_data_received = receivedBufLen - (offset - &receiveBuf[0]);
  2777. if (offset != 0)
  2778. {
  2779. if (req_data_received < post_data_count)
  2780. {
  2781. snprintf(post_req_data, req_data_received, "%s", receiveBuf);
  2782. post_data_count -= req_data_received;
  2783. //ssl_server_read();
  2784. SSL_ReadRoutine(&ssl, (unsigned char*)receiveBuf);
  2785. offset = receiveBuf;
  2786. }
  2787. if(strlen(receiveBuf) != 0)
  2788. {
  2789. strncat(post_req_data, offset, post_data_count);
  2790. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), sendLen) == SEND_REQUIRED_YES)
  2791. {
  2792. post_data_count = 0;
  2793. return sendBuf;
  2794. }
  2795. else
  2796. {
  2797. /*if(sSettings.sRADIUS.RDSEnable == true)
  2798. fs_open("/rslogin.html", &file);
  2799. else
  2800. fs_open("/login.html", &file);
  2801. ssl_sendframes(&ssl, file.data, file.len);*/
  2802. //ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2803. post_data_count = 0;
  2804. return sendBuf;
  2805. }
  2806. }
  2807. else
  2808. {
  2809. // Redirect to login page
  2810. if((sSettings.sRADIUS.RDSEnable == true) && (fl_raddius_net_err == false))
  2811. fs_open("/rslogin.html", &file);
  2812. else
  2813. fs_open("/login.html", &file);
  2814. post_data_count = 0;
  2815. *sendLen = file.len;
  2816. return file.data;
  2817. }
  2818. }
  2819. // request was fragmented before "\r\n\r\n"
  2820. else
  2821. {
  2822. // Redirect to login page
  2823. if((sSettings.sRADIUS.RDSEnable == true) && (fl_raddius_net_err == false))
  2824. fs_open("/rslogin.html", &file);
  2825. else
  2826. fs_open("/login.html", &file);
  2827. post_data_count = 0;
  2828. *sendLen = file.len;
  2829. return file.data;
  2830. }
  2831. }
  2832. else
  2833. {
  2834. //printf("Too long POST request!\r\n");
  2835. // Ignore request
  2836. post_data_count = 0;
  2837. // Redirect to login page
  2838. if((sSettings.sRADIUS.RDSEnable == true) && (fl_raddius_net_err == false))
  2839. fs_open("/rslogin.html", &file);
  2840. else
  2841. fs_open("/login.html", &file);
  2842. *sendLen = file.len;
  2843. return file.data;
  2844. }
  2845. }
  2846. else if (post_data_count > 0)
  2847. {
  2848. strncat(post_req_data, receiveBuf, post_data_count);
  2849. post_data_count = 0;
  2850. log_post_reqn = 0;
  2851. if (HTTP_ConfirmWebPwd(post_req_data, sendBuf, strlen(post_req_data), sendLen) == SEND_REQUIRED_YES)
  2852. {
  2853. //ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2854. return sendBuf;
  2855. }
  2856. else
  2857. {
  2858. //ssl_sendframes(&ssl, sendBuf, sendBufLoadLen);
  2859. return sendBuf;
  2860. }
  2861. }
  2862. else
  2863. {
  2864. if((sSettings.sRADIUS.RDSEnable == true) && (fl_raddius_net_err == false))
  2865. fs_open("/rslogin.html", &file);
  2866. else
  2867. fs_open("/login.html", &file);
  2868. *sendLen = file.len;
  2869. return file.data;
  2870. }
  2871. }
  2872. //
  2873. char* AuthenticatedTrueRoutine(uint16_t* sendLen)
  2874. {
  2875. char *DataOffset;
  2876. char *ptr;
  2877. if (strncmp(receiveBuf, "GET /main.css", 13) == 0) // +
  2878. {
  2879. fs_open("/main.css", &file);
  2880. *sendLen = file.len;
  2881. return file.data;
  2882. }
  2883. else if (strncmp(receiveBuf, "GET /rotek.png", 14) == 0) // +
  2884. {
  2885. fs_open("/rotek.png", &file);
  2886. *sendLen = file.len;
  2887. return file.data;
  2888. }
  2889. else if (strncmp(receiveBuf, "GET /favicon.ico", 16) == 0) // ?
  2890. {
  2891. fs_open("/favicon.ico", &file);
  2892. *sendLen = file.len;
  2893. return file.data;
  2894. }
  2895. else if (strncmp(receiveBuf, "GET /main.js", 12) == 0) // +
  2896. {
  2897. fs_open("/main.js", &file);
  2898. *sendLen = file.len;
  2899. return file.data;
  2900. }
  2901. else if (strncmp(receiveBuf, "GET /role.js", 12) == 0)
  2902. {
  2903. fs_open("/role.js", &file);
  2904. *sendLen = file.len;
  2905. return file.data;
  2906. }
  2907. else if (strncmp(receiveBuf, "GET /settings.html", 18) == 0) // +
  2908. {
  2909. HTTP_UpdateUserLoginTime(user_id);
  2910. if (seclevel == 0)
  2911. fs_open("/settings.html", &file);
  2912. else
  2913. fs_open("/index.html", &file);
  2914. *sendLen = file.len;
  2915. return file.data;
  2916. }
  2917. else if (strncmp(receiveBuf, "GET /info.html", 14) == 0) // +
  2918. {
  2919. HTTP_UpdateUserLoginTime(user_id);
  2920. fs_open("/info.html", &file);
  2921. *sendLen = file.len;
  2922. return file.data;
  2923. }
  2924. else if (strncmp(receiveBuf, "GET /history.html", 17) == 0)
  2925. {
  2926. HTTP_UpdateUserLoginTime(user_id);
  2927. fs_open("/history.html", &file);
  2928. *sendLen = file.len;
  2929. return file.data;
  2930. }
  2931. else if (strncmp(receiveBuf, "GET /ups_history.html", 21) == 0)
  2932. {
  2933. HTTP_UpdateUserLoginTime(user_id);
  2934. fs_open("/ups_history.html", &file);
  2935. *sendLen = file.len;
  2936. return file.data;
  2937. }
  2938. else if (strncmp(receiveBuf, "GET /getJson.cgi", 16) == 0) // +
  2939. {
  2940. HTTP_GetParamsPage1(sendBuf);
  2941. *sendLen = strlen(sendBuf);
  2942. return sendBuf;
  2943. }
  2944. else if (strncmp(receiveBuf, "GET /settings.cgi", 17) == 0) // +
  2945. {
  2946. if (seclevel == 0) {
  2947. SET_PAGE = SET_PAGE_PAGE2;
  2948. if (HTTP_SettingsPage(receiveBuf, sendBuf, receivedBufLen, sendLen) == SEND_REQUIRED_YES)
  2949. {
  2950. *sendLen = strlen(sendBuf);
  2951. return sendBuf;
  2952. }
  2953. }
  2954. return 0;
  2955. }
  2956. else if (strncmp(receiveBuf, "POST /settings.cgi", 18) == 0)
  2957. {
  2958. if (seclevel == 0)
  2959. {
  2960. DataOffset = 0;
  2961. // POST Packet received
  2962. TotalReceived = 0;
  2963. TotalData = 0;
  2964. memset(sendBuf, 0, strlen(sendBuf));
  2965. // parse packet for Content-length field
  2966. size = Parse_Content_Length(receiveBuf, receivedBufLen);
  2967. DataOffset = strstr(receiveBuf, "managerIP");
  2968. /* case of MSIE8 : we do not receive data in the POST packet*/
  2969. if (DataOffset == 0)
  2970. {
  2971. //ssl_server_read();
  2972. SSL_ReadRoutine(&ssl, (unsigned char*)receiveBuf);
  2973. DataOffset = strstr(receiveBuf, "managerIP");
  2974. }
  2975. TotalReceived = receivedBufLen - (DataOffset - &receiveBuf[0]);
  2976. TotalData += TotalReceived;
  2977. strncat(sendBuf, DataOffset, TotalReceived);
  2978. for (int i = TotalData; i < size; i ++)
  2979. {
  2980. //ssl_server_read();
  2981. SSL_ReadRoutine(&ssl, (unsigned char*)receiveBuf);
  2982. strncat(sendBuf, receiveBuf, receivedBufLen);
  2983. TotalData += receivedBufLen;
  2984. }
  2985. // check if last data packet
  2986. if (TotalData == size)
  2987. {
  2988. DBG printf("State: Received %d bytes\r\n", (int)TotalData);
  2989. // printf("receive %s \r\n", sendBuf);
  2990. strncat(sendBuf, " ", 1);
  2991. HTTP_SetSettings(sendBuf, strlen(sendBuf));
  2992. memset(sendBuf, 0, size);
  2993. strcpy(sendBuf, "HTTP/1.1 200 OK\r\n");
  2994. strcat(sendBuf, "\r\n\r\n");
  2995. strcat(sendBuf,"<!DOCTYPE html><html lang=""><head><meta http-equiv=\"refresh\" content=\"0;url=/settings.html\"/></head></html>\r\n\r\n");
  2996. sendBufLoadLen = strlen(sendBuf);
  2997. *sendLen = sendBufLoadLen;
  2998. return sendBuf;
  2999. }
  3000. }
  3001. return 0;
  3002. }
  3003. else if (strncmp(receiveBuf, "GET /getcert.cgi", 16) == 0)
  3004. {
  3005. /* Send HTTP header first (Safari needs it) */
  3006. strcpy(sendBuf, HTTP_200_OK);
  3007. *sendLen = strlen(sendBuf);
  3008. SSL_WriteRoutine(&ssl, sendBuf, *sendLen);
  3009. // SSL_Test();
  3010. *sendLen = strlen(req_cert);
  3011. return req_cert;
  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. }