http_server.c 89 KB

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