http_server.c 114 KB

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