wolfio.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  1. /* wolfio.c
  2. *
  3. * Copyright (C) 2006-2021 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #ifndef WOLFCRYPT_ONLY
  26. #ifdef _WIN32_WCE
  27. /* On WinCE winsock2.h must be included before windows.h for socket stuff */
  28. #include <winsock2.h>
  29. #endif
  30. #include <wolfssl/internal.h>
  31. #include <wolfssl/error-ssl.h>
  32. #include <wolfssl/wolfio.h>
  33. #if defined(HAVE_HTTP_CLIENT)
  34. #include <stdlib.h> /* strtol() */
  35. #endif
  36. /*
  37. Possible IO enable options:
  38. * WOLFSSL_USER_IO: Disables default Embed* callbacks and default: off
  39. allows user to define their own using
  40. wolfSSL_CTX_SetIORecv and wolfSSL_CTX_SetIOSend
  41. * USE_WOLFSSL_IO: Enables the wolfSSL IO functions default: on
  42. * HAVE_HTTP_CLIENT: Enables HTTP client API's default: off
  43. (unless HAVE_OCSP or HAVE_CRL_IO defined)
  44. * HAVE_IO_TIMEOUT: Enables support for connect timeout default: off
  45. */
  46. /* if user writes own I/O callbacks they can define WOLFSSL_USER_IO to remove
  47. automatic setting of default I/O functions EmbedSend() and EmbedReceive()
  48. but they'll still need SetCallback xxx() at end of file
  49. */
  50. #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT)
  51. /* Translates return codes returned from
  52. * send() and recv() if need be.
  53. */
  54. static WC_INLINE int TranslateReturnCode(int old, int sd)
  55. {
  56. (void)sd;
  57. #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  58. if (old == 0) {
  59. errno = SOCKET_EWOULDBLOCK;
  60. return -1; /* convert to BSD style wouldblock as error */
  61. }
  62. if (old < 0) {
  63. errno = RTCS_geterror(sd);
  64. if (errno == RTCSERR_TCP_CONN_CLOSING)
  65. return 0; /* convert to BSD style closing */
  66. if (errno == RTCSERR_TCP_CONN_RLSD)
  67. errno = SOCKET_ECONNRESET;
  68. if (errno == RTCSERR_TCP_TIMED_OUT)
  69. errno = SOCKET_EAGAIN;
  70. }
  71. #endif
  72. return old;
  73. }
  74. static WC_INLINE int wolfSSL_LastError(int err)
  75. {
  76. (void)err; /* Suppress unused arg */
  77. #ifdef USE_WINDOWS_API
  78. return WSAGetLastError();
  79. #elif defined(EBSNET)
  80. return xn_getlasterror();
  81. #elif defined(WOLFSSL_LINUXKM)
  82. return err; /* Return provided error value */
  83. #elif defined(FUSION_RTOS)
  84. #include <fclerrno.h>
  85. return FCL_GET_ERRNO;
  86. #else
  87. return errno;
  88. #endif
  89. }
  90. static int TranslateIoError(int err)
  91. {
  92. if (err > 0)
  93. return err;
  94. err = wolfSSL_LastError(err);
  95. #if SOCKET_EWOULDBLOCK != SOCKET_EAGAIN
  96. if ((err == SOCKET_EWOULDBLOCK) || (err == SOCKET_EAGAIN))
  97. #else
  98. if (err == SOCKET_EWOULDBLOCK)
  99. #endif
  100. {
  101. WOLFSSL_MSG("\tWould block");
  102. return WOLFSSL_CBIO_ERR_WANT_READ;
  103. }
  104. else if (err == SOCKET_ECONNRESET) {
  105. WOLFSSL_MSG("\tConnection reset");
  106. return WOLFSSL_CBIO_ERR_CONN_RST;
  107. }
  108. else if (err == SOCKET_EINTR) {
  109. WOLFSSL_MSG("\tSocket interrupted");
  110. return WOLFSSL_CBIO_ERR_ISR;
  111. }
  112. else if (err == SOCKET_ECONNABORTED) {
  113. WOLFSSL_MSG("\tConnection aborted");
  114. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  115. }
  116. WOLFSSL_MSG("\tGeneral error");
  117. return WOLFSSL_CBIO_ERR_GENERAL;
  118. }
  119. #endif /* USE_WOLFSSL_IO || HAVE_HTTP_CLIENT */
  120. #ifdef OPENSSL_EXTRA
  121. #ifndef NO_BIO
  122. /* Use the WOLFSSL read BIO for receiving data. This is set by the function
  123. * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIORecv.
  124. *
  125. * ssl WOLFSSL struct passed in that has this function set as the receive
  126. * callback.
  127. * buf buffer to fill with data read
  128. * sz size of buf buffer
  129. * ctx a user set context
  130. *
  131. * returns the amount of data read or want read. See WOLFSSL_CBIO_ERR_* values.
  132. */
  133. int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  134. {
  135. int recvd = WOLFSSL_CBIO_ERR_GENERAL;
  136. WOLFSSL_ENTER("BioReceive");
  137. if (ssl->biord == NULL) {
  138. WOLFSSL_MSG("WOLFSSL biord not set");
  139. return WOLFSSL_CBIO_ERR_GENERAL;
  140. }
  141. recvd = wolfSSL_BIO_read(ssl->biord, buf, sz);
  142. if (recvd <= 0) {
  143. if (wolfSSL_BIO_supports_pending(ssl->biord) &&
  144. wolfSSL_BIO_ctrl_pending(ssl->biord) == 0) {
  145. if (ssl->biowr->type == WOLFSSL_BIO_BIO &&
  146. ssl->biowr->wrIdx != 0) {
  147. /* Let's signal to the app layer that we have
  148. * data pending that needs to be sent. */
  149. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  150. }
  151. return WOLFSSL_CBIO_ERR_WANT_READ;
  152. }
  153. else if (ssl->biord->type == WOLFSSL_BIO_SOCKET) {
  154. if (recvd == 0) {
  155. WOLFSSL_MSG("BioReceive connection closed");
  156. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  157. }
  158. #ifdef USE_WOLFSSL_IO
  159. recvd = TranslateIoError(recvd);
  160. #endif
  161. return recvd;
  162. }
  163. /* If retry and read flags are set, return WANT_READ */
  164. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
  165. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  166. return WOLFSSL_CBIO_ERR_WANT_READ;
  167. }
  168. WOLFSSL_MSG("BIO general error");
  169. return WOLFSSL_CBIO_ERR_GENERAL;
  170. }
  171. (void)ctx;
  172. return recvd;
  173. }
  174. /* Use the WOLFSSL write BIO for sending data. This is set by the function
  175. * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIOSend.
  176. *
  177. * ssl WOLFSSL struct passed in that has this function set as the send callback.
  178. * buf buffer with data to write out
  179. * sz size of buf buffer
  180. * ctx a user set context
  181. *
  182. * returns the amount of data sent or want send. See WOLFSSL_CBIO_ERR_* values.
  183. */
  184. int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  185. {
  186. int sent = WOLFSSL_CBIO_ERR_GENERAL;
  187. WOLFSSL_ENTER("BioSend");
  188. if (ssl->biowr == NULL) {
  189. WOLFSSL_MSG("WOLFSSL biowr not set");
  190. return WOLFSSL_CBIO_ERR_GENERAL;
  191. }
  192. sent = wolfSSL_BIO_write(ssl->biowr, buf, sz);
  193. if (sent <= 0) {
  194. if (ssl->biowr->type == WOLFSSL_BIO_SOCKET) {
  195. #ifdef USE_WOLFSSL_IO
  196. sent = TranslateIoError(sent);
  197. #endif
  198. return sent;
  199. }
  200. else if (ssl->biowr->type == WOLFSSL_BIO_BIO) {
  201. if (sent == WOLFSSL_BIO_ERROR) {
  202. WOLFSSL_MSG("\tWould Block");
  203. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  204. }
  205. }
  206. /* If retry and write flags are set, return WANT_WRITE */
  207. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_WRITE) &&
  208. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  209. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  210. }
  211. return WOLFSSL_CBIO_ERR_GENERAL;
  212. }
  213. (void)ctx;
  214. return sent;
  215. }
  216. #endif /* !NO_BIO */
  217. #endif /* OPENSSL_EXTRA */
  218. #ifdef USE_WOLFSSL_IO
  219. /* The receive embedded callback
  220. * return : nb bytes read, or error
  221. */
  222. int EmbedReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  223. {
  224. int recvd;
  225. #ifndef WOLFSSL_LINUXKM
  226. int sd = *(int*)ctx;
  227. #else
  228. struct socket *sd = (struct socket*)ctx;
  229. #endif
  230. recvd = wolfIO_Recv(sd, buf, sz, ssl->rflags);
  231. if (recvd < 0) {
  232. WOLFSSL_MSG("Embed Receive error");
  233. return TranslateIoError(recvd);
  234. }
  235. else if (recvd == 0) {
  236. WOLFSSL_MSG("Embed receive connection closed");
  237. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  238. }
  239. return recvd;
  240. }
  241. /* The send embedded callback
  242. * return : nb bytes sent, or error
  243. */
  244. int EmbedSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  245. {
  246. int sent;
  247. #ifndef WOLFSSL_LINUXKM
  248. int sd = *(int*)ctx;
  249. #else
  250. struct socket *sd = (struct socket*)ctx;
  251. #endif
  252. #ifdef WOLFSSL_MAX_SEND_SZ
  253. if (sz > WOLFSSL_MAX_SEND_SZ)
  254. sz = WOLFSSL_MAX_SEND_SZ;
  255. #endif
  256. sent = wolfIO_Send(sd, buf, sz, ssl->wflags);
  257. if (sent < 0) {
  258. WOLFSSL_MSG("Embed Send error");
  259. return TranslateIoError(sent);
  260. }
  261. return sent;
  262. }
  263. #ifdef WOLFSSL_DTLS
  264. #include <wolfssl/wolfcrypt/sha.h>
  265. #define SENDTO_FUNCTION sendto
  266. #define RECVFROM_FUNCTION recvfrom
  267. /* The receive embedded callback
  268. * return : nb bytes read, or error
  269. */
  270. int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  271. {
  272. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  273. int recvd;
  274. int sd = dtlsCtx->rfd;
  275. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  276. SOCKADDR_S peer;
  277. XSOCKLENT peerSz = sizeof(peer);
  278. WOLFSSL_ENTER("EmbedReceiveFrom()");
  279. /* Don't use ssl->options.handShakeDone since it is true even if
  280. * we are in the process of renegotiation */
  281. if (ssl->options.handShakeState == HANDSHAKE_DONE)
  282. dtls_timeout = 0;
  283. if (!wolfSSL_get_using_nonblock(ssl)) {
  284. #ifdef USE_WINDOWS_API
  285. DWORD timeout = dtls_timeout * 1000;
  286. #else
  287. struct timeval timeout;
  288. XMEMSET(&timeout, 0, sizeof(timeout));
  289. timeout.tv_sec = dtls_timeout;
  290. #endif
  291. if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
  292. sizeof(timeout)) != 0) {
  293. WOLFSSL_MSG("setsockopt rcvtimeo failed");
  294. }
  295. }
  296. #ifndef NO_ASN_TIME
  297. else if(IsSCR(ssl)) {
  298. if (ssl->dtls_start_timeout &&
  299. LowResTimer() - ssl->dtls_start_timeout > (word32)dtls_timeout) {
  300. ssl->dtls_start_timeout = 0;
  301. return WOLFSSL_CBIO_ERR_TIMEOUT;
  302. }
  303. else if (!ssl->dtls_start_timeout) {
  304. ssl->dtls_start_timeout = LowResTimer();
  305. }
  306. }
  307. #endif /* !NO_ASN_TIME */
  308. recvd = (int)RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags,
  309. (SOCKADDR*)&peer, &peerSz);
  310. recvd = TranslateReturnCode(recvd, sd);
  311. if (recvd < 0) {
  312. WOLFSSL_MSG("Embed Receive From error");
  313. recvd = TranslateIoError(recvd);
  314. if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
  315. !wolfSSL_dtls_get_using_nonblock(ssl)) {
  316. recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
  317. }
  318. return recvd;
  319. }
  320. else {
  321. if (dtlsCtx->peer.sz > 0
  322. && peerSz != (XSOCKLENT)dtlsCtx->peer.sz
  323. && XMEMCMP(&peer, dtlsCtx->peer.sa, peerSz) != 0) {
  324. WOLFSSL_MSG(" Ignored packet from invalid peer");
  325. return WOLFSSL_CBIO_ERR_WANT_READ;
  326. }
  327. }
  328. #ifndef NO_ASN_TIME
  329. ssl->dtls_start_timeout = 0;
  330. #endif /* !NO_ASN_TIME */
  331. return recvd;
  332. }
  333. /* The send embedded callback
  334. * return : nb bytes sent, or error
  335. */
  336. int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  337. {
  338. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  339. int sd = dtlsCtx->wfd;
  340. int sent;
  341. WOLFSSL_ENTER("EmbedSendTo()");
  342. sent = (int)SENDTO_FUNCTION(sd, buf, sz, ssl->wflags,
  343. (const SOCKADDR*)dtlsCtx->peer.sa,
  344. dtlsCtx->peer.sz);
  345. sent = TranslateReturnCode(sent, sd);
  346. if (sent < 0) {
  347. WOLFSSL_MSG("Embed Send To error");
  348. return TranslateIoError(sent);
  349. }
  350. return sent;
  351. }
  352. #ifdef WOLFSSL_MULTICAST
  353. /* The alternate receive embedded callback for Multicast
  354. * return : nb bytes read, or error
  355. */
  356. int EmbedReceiveFromMcast(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  357. {
  358. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  359. int recvd;
  360. int sd = dtlsCtx->rfd;
  361. WOLFSSL_ENTER("EmbedReceiveFromMcast()");
  362. recvd = (int)RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, NULL, NULL);
  363. recvd = TranslateReturnCode(recvd, sd);
  364. if (recvd < 0) {
  365. WOLFSSL_MSG("Embed Receive From error");
  366. recvd = TranslateIoError(recvd);
  367. if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
  368. !wolfSSL_dtls_get_using_nonblock(ssl)) {
  369. recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
  370. }
  371. return recvd;
  372. }
  373. return recvd;
  374. }
  375. #endif /* WOLFSSL_MULTICAST */
  376. /* The DTLS Generate Cookie callback
  377. * return : number of bytes copied into buf, or error
  378. */
  379. int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
  380. {
  381. int sd = ssl->wfd;
  382. SOCKADDR_S peer;
  383. XSOCKLENT peerSz = sizeof(peer);
  384. byte digest[WC_SHA256_DIGEST_SIZE];
  385. int ret = 0;
  386. (void)ctx;
  387. XMEMSET(&peer, 0, sizeof(peer));
  388. if (getpeername(sd, (SOCKADDR*)&peer, &peerSz) != 0) {
  389. WOLFSSL_MSG("getpeername failed in EmbedGenerateCookie");
  390. return GEN_COOKIE_E;
  391. }
  392. ret = wc_Sha256Hash((byte*)&peer, peerSz, digest);
  393. if (ret != 0)
  394. return ret;
  395. if (sz > WC_SHA256_DIGEST_SIZE)
  396. sz = WC_SHA256_DIGEST_SIZE;
  397. XMEMCPY(buf, digest, sz);
  398. return sz;
  399. }
  400. #endif /* WOLFSSL_DTLS */
  401. #ifdef WOLFSSL_SESSION_EXPORT
  402. #ifdef WOLFSSL_DTLS
  403. static int EmbedGetPeerDTLS(WOLFSSL* ssl, char* ip, int* ipSz,
  404. unsigned short* port, int* fam)
  405. {
  406. SOCKADDR_S peer;
  407. word32 peerSz;
  408. int ret;
  409. /* get peer information stored in ssl struct */
  410. peerSz = sizeof(SOCKADDR_S);
  411. if ((ret = wolfSSL_dtls_get_peer(ssl, (void*)&peer, &peerSz))
  412. != WOLFSSL_SUCCESS) {
  413. return ret;
  414. }
  415. /* extract family, ip, and port */
  416. *fam = ((SOCKADDR_S*)&peer)->ss_family;
  417. switch (*fam) {
  418. case WOLFSSL_IP4:
  419. if (XINET_NTOP(*fam, &(((SOCKADDR_IN*)&peer)->sin_addr),
  420. ip, *ipSz) == NULL) {
  421. WOLFSSL_MSG("XINET_NTOP error");
  422. return SOCKET_ERROR_E;
  423. }
  424. *port = XNTOHS(((SOCKADDR_IN*)&peer)->sin_port);
  425. break;
  426. case WOLFSSL_IP6:
  427. #ifdef WOLFSSL_IPV6
  428. if (XINET_NTOP(*fam, &(((SOCKADDR_IN6*)&peer)->sin6_addr),
  429. ip, *ipSz) == NULL) {
  430. WOLFSSL_MSG("XINET_NTOP error");
  431. return SOCKET_ERROR_E;
  432. }
  433. *port = XNTOHS(((SOCKADDR_IN6*)&peer)->sin6_port);
  434. #endif /* WOLFSSL_IPV6 */
  435. break;
  436. default:
  437. WOLFSSL_MSG("Unknown family type");
  438. return SOCKET_ERROR_E;
  439. }
  440. ip[*ipSz - 1] = '\0'; /* make sure has terminator */
  441. *ipSz = (word16)XSTRLEN(ip);
  442. return WOLFSSL_SUCCESS;
  443. }
  444. static int EmbedSetPeerDTLS(WOLFSSL* ssl, char* ip, int ipSz,
  445. unsigned short port, int fam)
  446. {
  447. int ret;
  448. SOCKADDR_S addr;
  449. /* sanity checks on arguments */
  450. if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
  451. return BAD_FUNC_ARG;
  452. }
  453. addr.ss_family = fam;
  454. switch (addr.ss_family) {
  455. case WOLFSSL_IP4:
  456. if (XINET_PTON(addr.ss_family, ip,
  457. &(((SOCKADDR_IN*)&addr)->sin_addr)) <= 0) {
  458. WOLFSSL_MSG("XINET_PTON error");
  459. return SOCKET_ERROR_E;
  460. }
  461. ((SOCKADDR_IN*)&addr)->sin_port = XHTONS(port);
  462. /* peer sa is free'd in SSL_ResourceFree */
  463. if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN*)&addr,
  464. sizeof(SOCKADDR_IN)))!= WOLFSSL_SUCCESS) {
  465. WOLFSSL_MSG("Import DTLS peer info error");
  466. return ret;
  467. }
  468. break;
  469. case WOLFSSL_IP6:
  470. #ifdef WOLFSSL_IPV6
  471. if (XINET_PTON(addr.ss_family, ip,
  472. &(((SOCKADDR_IN6*)&addr)->sin6_addr)) <= 0) {
  473. WOLFSSL_MSG("XINET_PTON error");
  474. return SOCKET_ERROR_E;
  475. }
  476. ((SOCKADDR_IN6*)&addr)->sin6_port = XHTONS(port);
  477. /* peer sa is free'd in SSL_ResourceFree */
  478. if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN6*)&addr,
  479. sizeof(SOCKADDR_IN6)))!= WOLFSSL_SUCCESS) {
  480. WOLFSSL_MSG("Import DTLS peer info error");
  481. return ret;
  482. }
  483. #endif /* WOLFSSL_IPV6 */
  484. break;
  485. default:
  486. WOLFSSL_MSG("Unknown address family");
  487. return BUFFER_E;
  488. }
  489. return WOLFSSL_SUCCESS;
  490. }
  491. #endif
  492. /* get the peer information in human readable form (ip, port, family)
  493. * default function assumes BSD sockets
  494. * can be overridden with wolfSSL_CTX_SetIOGetPeer
  495. */
  496. int EmbedGetPeer(WOLFSSL* ssl, char* ip, int* ipSz,
  497. unsigned short* port, int* fam)
  498. {
  499. if (ssl == NULL || ip == NULL || ipSz == NULL ||
  500. port == NULL || fam == NULL) {
  501. return BAD_FUNC_ARG;
  502. }
  503. if (ssl->options.dtls) {
  504. #ifdef WOLFSSL_DTLS
  505. return EmbedGetPeerDTLS(ssl, ip, ipSz, port, fam);
  506. #else
  507. return NOT_COMPILED_IN;
  508. #endif
  509. }
  510. else {
  511. *port = wolfSSL_get_fd(ssl);
  512. ip[0] = '\0';
  513. *ipSz = 0;
  514. *fam = 0;
  515. return WOLFSSL_SUCCESS;
  516. }
  517. }
  518. /* set the peer information in human readable form (ip, port, family)
  519. * default function assumes BSD sockets
  520. * can be overridden with wolfSSL_CTX_SetIOSetPeer
  521. */
  522. int EmbedSetPeer(WOLFSSL* ssl, char* ip, int ipSz,
  523. unsigned short port, int fam)
  524. {
  525. /* sanity checks on arguments */
  526. if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
  527. return BAD_FUNC_ARG;
  528. }
  529. if (ssl->options.dtls) {
  530. #ifdef WOLFSSL_DTLS
  531. return EmbedSetPeerDTLS(ssl, ip, ipSz, port, fam);
  532. #else
  533. return NOT_COMPILED_IN;
  534. #endif
  535. }
  536. else {
  537. wolfSSL_set_fd(ssl, port);
  538. (void)fam;
  539. return WOLFSSL_SUCCESS;
  540. }
  541. }
  542. #endif /* WOLFSSL_SESSION_EXPORT */
  543. #ifdef WOLFSSL_LINUXKM
  544. static int linuxkm_send(struct socket *socket, void *buf, int size,
  545. unsigned int flags)
  546. {
  547. int ret;
  548. struct kvec vec = { .iov_base = buf, .iov_len = size };
  549. struct msghdr msg = { .msg_flags = flags };
  550. ret = kernel_sendmsg(socket, &msg, &vec, 1, size);
  551. return ret;
  552. }
  553. static int linuxkm_recv(struct socket *socket, void *buf, int size,
  554. unsigned int flags)
  555. {
  556. int ret;
  557. struct kvec vec = { .iov_base = buf, .iov_len = size };
  558. struct msghdr msg = { .msg_flags = flags };
  559. ret = kernel_recvmsg(socket, &msg, &vec, 1, size, msg.msg_flags);
  560. return ret;
  561. }
  562. #endif /* WOLFSSL_LINUXKM */
  563. int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags)
  564. {
  565. int recvd;
  566. recvd = (int)RECV_FUNCTION(sd, buf, sz, rdFlags);
  567. recvd = TranslateReturnCode(recvd, sd);
  568. return recvd;
  569. }
  570. int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags)
  571. {
  572. int sent;
  573. sent = (int)SEND_FUNCTION(sd, buf, sz, wrFlags);
  574. sent = TranslateReturnCode(sent, sd);
  575. return sent;
  576. }
  577. #endif /* USE_WOLFSSL_IO */
  578. #ifdef HAVE_HTTP_CLIENT
  579. #ifndef HAVE_IO_TIMEOUT
  580. #define io_timeout_sec 0
  581. #else
  582. #ifndef DEFAULT_TIMEOUT_SEC
  583. #define DEFAULT_TIMEOUT_SEC 0 /* no timeout */
  584. #endif
  585. static int io_timeout_sec = DEFAULT_TIMEOUT_SEC;
  586. void wolfIO_SetTimeout(int to_sec)
  587. {
  588. io_timeout_sec = to_sec;
  589. }
  590. int wolfIO_SetBlockingMode(SOCKET_T sockfd, int non_blocking)
  591. {
  592. int ret = 0;
  593. #ifdef USE_WINDOWS_API
  594. unsigned long blocking = non_blocking;
  595. ret = ioctlsocket(sockfd, FIONBIO, &blocking);
  596. if (ret == SOCKET_ERROR)
  597. ret = -1;
  598. #else
  599. ret = fcntl(sockfd, F_GETFL, 0);
  600. if (ret >= 0) {
  601. if (non_blocking)
  602. ret |= O_NONBLOCK;
  603. else
  604. ret &= ~O_NONBLOCK;
  605. ret = fcntl(sockfd, F_SETFL, ret);
  606. }
  607. #endif
  608. if (ret < 0) {
  609. WOLFSSL_MSG("wolfIO_SetBlockingMode failed");
  610. }
  611. return ret;
  612. }
  613. int wolfIO_Select(SOCKET_T sockfd, int to_sec)
  614. {
  615. fd_set rfds, wfds;
  616. int nfds = 0;
  617. struct timeval timeout = { (to_sec > 0) ? to_sec : 0, 0};
  618. int ret;
  619. #ifndef USE_WINDOWS_API
  620. nfds = (int)sockfd + 1;
  621. #endif
  622. if ((sockfd < 0) || (sockfd >= FD_SETSIZE)) {
  623. WOLFSSL_MSG("socket fd out of FDSET range");
  624. return -1;
  625. }
  626. FD_ZERO(&rfds);
  627. FD_SET(sockfd, &rfds);
  628. wfds = rfds;
  629. ret = select(nfds, &rfds, &wfds, NULL, &timeout);
  630. if (ret == 0) {
  631. #ifdef DEBUG_HTTP
  632. printf("Timeout: %d\n", ret);
  633. #endif
  634. return HTTP_TIMEOUT;
  635. }
  636. else if (ret > 0) {
  637. if (FD_ISSET(sockfd, &wfds)) {
  638. if (!FD_ISSET(sockfd, &rfds)) {
  639. return 0;
  640. }
  641. }
  642. }
  643. WOLFSSL_MSG("Select error");
  644. return SOCKET_ERROR_E;
  645. }
  646. #endif /* HAVE_IO_TIMEOUT */
  647. static int wolfIO_Word16ToString(char* d, word16 number)
  648. {
  649. int i = 0;
  650. word16 order = 10000;
  651. word16 digit;
  652. if (d == NULL)
  653. return i;
  654. if (number == 0)
  655. d[i++] = '0';
  656. else {
  657. while (order) {
  658. digit = number / order;
  659. if (i > 0 || digit != 0)
  660. d[i++] = (char)digit + '0';
  661. if (digit != 0)
  662. number %= digit * order;
  663. order = (order > 1) ? order / 10 : 0;
  664. }
  665. }
  666. d[i] = 0; /* null terminate */
  667. return i;
  668. }
  669. int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec)
  670. {
  671. #ifdef HAVE_SOCKADDR
  672. int ret = 0;
  673. SOCKADDR_S addr;
  674. int sockaddr_len = sizeof(SOCKADDR_IN);
  675. /* use gethostbyname for c99 */
  676. #if defined(HAVE_GETADDRINFO) && !defined(WOLF_C99)
  677. ADDRINFO hints;
  678. ADDRINFO* answer = NULL;
  679. char strPort[6];
  680. #else
  681. #if !defined(WOLFSSL_USE_POPEN_HOST)
  682. HOSTENT* entry;
  683. #endif
  684. SOCKADDR_IN *sin;
  685. #endif
  686. if (sockfd == NULL || ip == NULL) {
  687. return -1;
  688. }
  689. XMEMSET(&addr, 0, sizeof(addr));
  690. #ifdef WOLFIO_DEBUG
  691. printf("TCP Connect: %s:%d\n", ip, port);
  692. #endif
  693. /* use gethostbyname for c99 */
  694. #if defined(HAVE_GETADDRINFO) && !defined(WOLF_C99)
  695. XMEMSET(&hints, 0, sizeof(hints));
  696. hints.ai_family = AF_UNSPEC;
  697. hints.ai_socktype = SOCK_STREAM;
  698. hints.ai_protocol = IPPROTO_TCP;
  699. if (wolfIO_Word16ToString(strPort, port) == 0) {
  700. WOLFSSL_MSG("invalid port number for responder");
  701. return -1;
  702. }
  703. if (getaddrinfo(ip, strPort, &hints, &answer) < 0 || answer == NULL) {
  704. WOLFSSL_MSG("no addr info for responder");
  705. return -1;
  706. }
  707. sockaddr_len = answer->ai_addrlen;
  708. XMEMCPY(&addr, answer->ai_addr, sockaddr_len);
  709. freeaddrinfo(answer);
  710. #elif defined(WOLFSSL_USE_POPEN_HOST)
  711. {
  712. char host_ipaddr[4] = { 127, 0, 0, 1 };
  713. int found = 1;
  714. if ((XSTRNCMP(ip, "localhost", 10) != 0) &&
  715. (XSTRNCMP(ip, "127.0.0.1", 10) != 0)) {
  716. FILE* fp;
  717. char host_out[100];
  718. char cmd[100];
  719. XSTRNCPY(cmd, "host ", 6);
  720. XSTRNCAT(cmd, ip, 99 - XSTRLEN(cmd));
  721. found = 0;
  722. fp = popen(cmd, "r");
  723. if (fp != NULL) {
  724. while (fgets(host_out, sizeof(host_out), fp) != NULL) {
  725. int i;
  726. int j = 0;
  727. for (j = 0; host_out[j] != '\0'; j++) {
  728. if ((host_out[j] >= '0') && (host_out[j] <= '9')) {
  729. break;
  730. }
  731. }
  732. found = (host_out[j] >= '0') && (host_out[j] <= '9');
  733. if (!found) {
  734. continue;
  735. }
  736. for (i = 0; i < 4; i++) {
  737. host_ipaddr[i] = atoi(host_out + j);
  738. while ((host_out[j] >= '0') && (host_out[j] <= '9')) {
  739. j++;
  740. }
  741. if (host_out[j] == '.') {
  742. j++;
  743. found &= (i != 3);
  744. }
  745. else {
  746. found &= (i == 3);
  747. break;
  748. }
  749. }
  750. if (found) {
  751. break;
  752. }
  753. }
  754. pclose(fp);
  755. }
  756. }
  757. if (found) {
  758. sin = (SOCKADDR_IN *)&addr;
  759. sin->sin_family = AF_INET;
  760. sin->sin_port = XHTONS(port);
  761. XMEMCPY(&sin->sin_addr.s_addr, host_ipaddr, sizeof(host_ipaddr));
  762. }
  763. else {
  764. WOLFSSL_MSG("no addr info for responder");
  765. return -1;
  766. }
  767. }
  768. #else
  769. entry = gethostbyname(ip);
  770. sin = (SOCKADDR_IN *)&addr;
  771. if (entry) {
  772. sin->sin_family = AF_INET;
  773. sin->sin_port = XHTONS(port);
  774. XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], entry->h_length);
  775. }
  776. else {
  777. WOLFSSL_MSG("no addr info for responder");
  778. return -1;
  779. }
  780. #endif
  781. *sockfd = (SOCKET_T)socket(addr.ss_family, SOCK_STREAM, 0);
  782. #ifdef USE_WINDOWS_API
  783. if (*sockfd == SOCKET_INVALID)
  784. #else
  785. if (*sockfd <= SOCKET_INVALID)
  786. #endif
  787. {
  788. WOLFSSL_MSG("bad socket fd, out of fds?");
  789. return -1;
  790. }
  791. #ifdef HAVE_IO_TIMEOUT
  792. /* if timeout value provided then set socket non-blocking */
  793. if (to_sec > 0) {
  794. wolfIO_SetBlockingMode(*sockfd, 1);
  795. }
  796. #else
  797. (void)to_sec;
  798. #endif
  799. ret = connect(*sockfd, (SOCKADDR *)&addr, sockaddr_len);
  800. #ifdef HAVE_IO_TIMEOUT
  801. if (ret != 0) {
  802. if ((errno == EINPROGRESS) && (to_sec > 0)) {
  803. /* wait for connect to complete */
  804. ret = wolfIO_Select(*sockfd, to_sec);
  805. /* restore blocking mode */
  806. wolfIO_SetBlockingMode(*sockfd, 0);
  807. }
  808. }
  809. #endif
  810. if (ret != 0) {
  811. WOLFSSL_MSG("Responder tcp connect failed");
  812. CloseSocket(*sockfd);
  813. *sockfd = SOCKET_INVALID;
  814. return -1;
  815. }
  816. return ret;
  817. #else
  818. (void)sockfd;
  819. (void)ip;
  820. (void)port;
  821. (void)to_sec;
  822. return -1;
  823. #endif /* HAVE_SOCKADDR */
  824. }
  825. int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port)
  826. {
  827. #ifdef HAVE_SOCKADDR
  828. int ret = 0;
  829. SOCKADDR_S addr;
  830. int sockaddr_len = sizeof(SOCKADDR_IN);
  831. SOCKADDR_IN *sin = (SOCKADDR_IN *)&addr;
  832. if (sockfd == NULL || port < 1) {
  833. return -1;
  834. }
  835. XMEMSET(&addr, 0, sizeof(addr));
  836. sin->sin_family = AF_INET;
  837. sin->sin_addr.s_addr = INADDR_ANY;
  838. sin->sin_port = XHTONS(port);
  839. *sockfd = (SOCKET_T)socket(AF_INET, SOCK_STREAM, 0);
  840. if (*sockfd < 0) {
  841. WOLFSSL_MSG("socket failed");
  842. *sockfd = SOCKET_INVALID;
  843. return -1;
  844. }
  845. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
  846. && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_ZEPHYR)
  847. {
  848. int optval = 1;
  849. XSOCKLENT optlen = sizeof(optval);
  850. ret = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, optlen);
  851. }
  852. #endif
  853. if (ret == 0)
  854. ret = bind(*sockfd, (SOCKADDR *)sin, sockaddr_len);
  855. if (ret == 0)
  856. ret = listen(*sockfd, SOMAXCONN);
  857. if (ret != 0) {
  858. WOLFSSL_MSG("wolfIO_TcpBind failed");
  859. CloseSocket(*sockfd);
  860. *sockfd = SOCKET_INVALID;
  861. ret = -1;
  862. }
  863. return ret;
  864. #else
  865. (void)sockfd;
  866. (void)port;
  867. return -1;
  868. #endif /* HAVE_SOCKADDR */
  869. }
  870. #ifdef HAVE_SOCKADDR
  871. int wolfIO_TcpAccept(SOCKET_T sockfd, SOCKADDR* peer_addr, XSOCKLENT* peer_len)
  872. {
  873. return accept(sockfd, peer_addr, peer_len);
  874. }
  875. #endif /* HAVE_SOCKADDR */
  876. #ifndef HTTP_SCRATCH_BUFFER_SIZE
  877. #define HTTP_SCRATCH_BUFFER_SIZE 512
  878. #endif
  879. #ifndef MAX_URL_ITEM_SIZE
  880. #define MAX_URL_ITEM_SIZE 80
  881. #endif
  882. int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath,
  883. word16* outPort)
  884. {
  885. int result = -1;
  886. if (url == NULL || urlSz == 0) {
  887. if (outName)
  888. *outName = 0;
  889. if (outPath)
  890. *outPath = 0;
  891. if (outPort)
  892. *outPort = 0;
  893. }
  894. else {
  895. int i, cur;
  896. /* need to break the url down into scheme, address, and port */
  897. /* "http://example.com:8080/" */
  898. /* "http://[::1]:443/" */
  899. if (XSTRNCMP(url, "http://", 7) == 0) {
  900. cur = 7;
  901. } else cur = 0;
  902. i = 0;
  903. if (url[cur] == '[') {
  904. cur++;
  905. /* copy until ']' */
  906. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
  907. url[cur] != ']') {
  908. if (outName)
  909. outName[i] = url[cur];
  910. i++; cur++;
  911. }
  912. cur++; /* skip ']' */
  913. }
  914. else {
  915. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
  916. url[cur] != ':' && url[cur] != '/') {
  917. if (outName)
  918. outName[i] = url[cur];
  919. i++; cur++;
  920. }
  921. }
  922. if (outName)
  923. outName[i] = 0;
  924. /* Need to pick out the path after the domain name */
  925. if (cur < urlSz && url[cur] == ':') {
  926. char port[6];
  927. int j;
  928. word32 bigPort = 0;
  929. i = 0;
  930. cur++;
  931. while (i < 6 && cur < urlSz && url[cur] != 0 && url[cur] != '/') {
  932. port[i] = url[cur];
  933. i++; cur++;
  934. }
  935. for (j = 0; j < i; j++) {
  936. if (port[j] < '0' || port[j] > '9') return -1;
  937. bigPort = (bigPort * 10) + (port[j] - '0');
  938. }
  939. if (outPort)
  940. *outPort = (word16)bigPort;
  941. }
  942. else if (outPort)
  943. *outPort = 80;
  944. if (cur < urlSz && url[cur] == '/') {
  945. i = 0;
  946. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0) {
  947. if (outPath)
  948. outPath[i] = url[cur];
  949. i++; cur++;
  950. }
  951. if (outPath)
  952. outPath[i] = 0;
  953. }
  954. else if (outPath) {
  955. outPath[0] = '/';
  956. outPath[1] = 0;
  957. }
  958. result = 0;
  959. }
  960. return result;
  961. }
  962. static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf,
  963. int* recvBufSz, int chunkSz, char* start, int len, int dynType, void* heap)
  964. {
  965. byte* newRecvBuf = NULL;
  966. int newRecvSz = *recvBufSz + chunkSz;
  967. int pos = 0;
  968. WOLFSSL_MSG("Processing HTTP response");
  969. #ifdef WOLFIO_DEBUG
  970. printf("HTTP Chunk %d->%d\n", *recvBufSz, chunkSz);
  971. #endif
  972. (void)heap;
  973. (void)dynType;
  974. if (chunkSz < 0 || len < 0) {
  975. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf invalid chunk or length size");
  976. return MEMORY_E;
  977. }
  978. if (newRecvSz <= 0) {
  979. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf new receive size overflow");
  980. return MEMORY_E;
  981. }
  982. newRecvBuf = (byte*)XMALLOC(newRecvSz, heap, dynType);
  983. if (newRecvBuf == NULL) {
  984. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf malloc failed");
  985. return MEMORY_E;
  986. }
  987. /* if buffer already exists, then we are growing it */
  988. if (*recvBuf) {
  989. XMEMCPY(&newRecvBuf[pos], *recvBuf, *recvBufSz);
  990. XFREE(*recvBuf, heap, dynType);
  991. pos += *recvBufSz;
  992. *recvBuf = NULL;
  993. }
  994. /* copy the remainder of the httpBuf into the respBuf */
  995. if (len != 0) {
  996. if (pos + len <= newRecvSz) {
  997. XMEMCPY(&newRecvBuf[pos], start, len);
  998. pos += len;
  999. }
  1000. else {
  1001. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf bad size");
  1002. XFREE(newRecvBuf, heap, dynType);
  1003. return -1;
  1004. }
  1005. }
  1006. /* receive the remainder of chunk */
  1007. while (len < chunkSz) {
  1008. int rxSz = wolfIO_Recv(sfd, (char*)&newRecvBuf[pos], chunkSz-len, 0);
  1009. if (rxSz > 0) {
  1010. len += rxSz;
  1011. pos += rxSz;
  1012. }
  1013. else {
  1014. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf recv failed");
  1015. XFREE(newRecvBuf, heap, dynType);
  1016. return -1;
  1017. }
  1018. }
  1019. *recvBuf = newRecvBuf;
  1020. *recvBufSz = newRecvSz;
  1021. return 0;
  1022. }
  1023. int wolfIO_HttpProcessResponse(int sfd, const char** appStrList,
  1024. byte** respBuf, byte* httpBuf, int httpBufSz, int dynType, void* heap)
  1025. {
  1026. static const char HTTP_PROTO[] = "HTTP/1.";
  1027. static const char HTTP_STATUS_200[] = "200";
  1028. int result = 0;
  1029. int len = 0;
  1030. char *start, *end;
  1031. int respBufSz = 0;
  1032. int isChunked = 0, chunkSz = 0;
  1033. enum phr_state { phr_init, phr_http_start, phr_have_length, phr_have_type,
  1034. phr_wait_end, phr_get_chunk_len, phr_get_chunk_data,
  1035. phr_http_end
  1036. } state = phr_init;
  1037. WOLFSSL_ENTER("wolfIO_HttpProcessResponse");
  1038. *respBuf = NULL;
  1039. start = end = NULL;
  1040. do {
  1041. if (state == phr_get_chunk_data) {
  1042. /* get chunk of data */
  1043. result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz,
  1044. chunkSz, start, len, dynType, heap);
  1045. state = (result != 0) ? phr_http_end : phr_get_chunk_len;
  1046. end = NULL;
  1047. len = 0;
  1048. }
  1049. /* read data if no \r\n or first time */
  1050. if (end == NULL) {
  1051. result = wolfIO_Recv(sfd, (char*)httpBuf+len, httpBufSz-len-1, 0);
  1052. if (result > 0) {
  1053. len += result;
  1054. start = (char*)httpBuf;
  1055. start[len] = 0;
  1056. }
  1057. else {
  1058. result = TranslateReturnCode(result, sfd);
  1059. result = wolfSSL_LastError(result);
  1060. if (result == SOCKET_EWOULDBLOCK || result == SOCKET_EAGAIN) {
  1061. return OCSP_WANT_READ;
  1062. }
  1063. WOLFSSL_MSG("wolfIO_HttpProcessResponse recv http from peer failed");
  1064. return HTTP_RECV_ERR;
  1065. }
  1066. }
  1067. end = XSTRSTR(start, "\r\n"); /* locate end */
  1068. /* handle incomplete rx */
  1069. if (end == NULL) {
  1070. if (len != 0)
  1071. XMEMMOVE(httpBuf, start, len);
  1072. start = end = NULL;
  1073. }
  1074. /* when start is "\r\n" */
  1075. else if (end == start) {
  1076. /* if waiting for end or need chunk len */
  1077. if (state == phr_wait_end || state == phr_get_chunk_len) {
  1078. state = (isChunked) ? phr_get_chunk_len : phr_http_end;
  1079. len -= 2; start += 2; /* skip \r\n */
  1080. }
  1081. else {
  1082. WOLFSSL_MSG("wolfIO_HttpProcessResponse header ended early");
  1083. return HTTP_HEADER_ERR;
  1084. }
  1085. }
  1086. else {
  1087. *end = 0; /* null terminate */
  1088. len -= (int)(end - start) + 2;
  1089. /* adjust len to remove the first line including the /r/n */
  1090. #ifdef WOLFIO_DEBUG
  1091. printf("HTTP Resp: %s\n", start);
  1092. #endif
  1093. switch (state) {
  1094. case phr_init:
  1095. /* length of "HTTP/1.x 200" == 12*/
  1096. if (XSTRLEN(start) < 12) {
  1097. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1098. "too short.");
  1099. return HTTP_HEADER_ERR;
  1100. }
  1101. if (XSTRNCASECMP(start, HTTP_PROTO,
  1102. sizeof(HTTP_PROTO) - 1) != 0) {
  1103. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1104. "doesn't start with HTTP/1.");
  1105. return HTTP_PROTO_ERR;
  1106. }
  1107. /* +2 for HTTP minor version and space between version and
  1108. * status code. */
  1109. start += sizeof(HTTP_PROTO) - 1 + 2 ;
  1110. if (XSTRNCASECMP(start, HTTP_STATUS_200,
  1111. sizeof(HTTP_STATUS_200) - 1) != 0) {
  1112. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1113. "doesn't have status code 200.");
  1114. return HTTP_STATUS_ERR;
  1115. }
  1116. state = phr_http_start;
  1117. break;
  1118. case phr_http_start:
  1119. case phr_have_length:
  1120. case phr_have_type:
  1121. if (XSTRLEN(start) < 13) { /* 13 is the shortest of the following
  1122. next lines we're checking for. */
  1123. WOLFSSL_MSG("wolfIO_HttpProcessResponse content type is too short.");
  1124. return HTTP_VERSION_ERR;
  1125. }
  1126. if (XSTRNCASECMP(start, "Content-Type:", 13) == 0) {
  1127. int i;
  1128. start += 13;
  1129. while (*start == ' ') start++;
  1130. /* try and match against appStrList */
  1131. i = 0;
  1132. while (appStrList[i] != NULL) {
  1133. if (XSTRNCASECMP(start, appStrList[i],
  1134. XSTRLEN(appStrList[i])) == 0) {
  1135. break;
  1136. }
  1137. i++;
  1138. }
  1139. if (appStrList[i] == NULL) {
  1140. WOLFSSL_MSG("wolfIO_HttpProcessResponse appstr mismatch");
  1141. return HTTP_APPSTR_ERR;
  1142. }
  1143. state = (state == phr_http_start) ? phr_have_type : phr_wait_end;
  1144. }
  1145. else if (XSTRNCASECMP(start, "Content-Length:", 15) == 0) {
  1146. start += 15;
  1147. while (*start == ' ') start++;
  1148. chunkSz = XATOI(start);
  1149. state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
  1150. }
  1151. else if (XSTRNCASECMP(start, "Transfer-Encoding:", 18) == 0) {
  1152. start += 18;
  1153. while (*start == ' ') start++;
  1154. if (XSTRNCASECMP(start, "chunked", 7) == 0) {
  1155. isChunked = 1;
  1156. state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
  1157. }
  1158. }
  1159. break;
  1160. case phr_get_chunk_len:
  1161. chunkSz = (int)strtol(start, NULL, 16); /* hex format */
  1162. state = (chunkSz == 0) ? phr_http_end : phr_get_chunk_data;
  1163. break;
  1164. case phr_get_chunk_data:
  1165. /* processing for chunk data done above, since \r\n isn't required */
  1166. case phr_wait_end:
  1167. case phr_http_end:
  1168. /* do nothing */
  1169. break;
  1170. } /* switch (state) */
  1171. /* skip to end plus \r\n */
  1172. start = end + 2;
  1173. }
  1174. } while (state != phr_http_end);
  1175. if (!isChunked) {
  1176. result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz, chunkSz,
  1177. start, len, dynType, heap);
  1178. }
  1179. if (result >= 0) {
  1180. result = respBufSz;
  1181. }
  1182. else {
  1183. WOLFSSL_ERROR(result);
  1184. }
  1185. return result;
  1186. }
  1187. int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName,
  1188. const char *path, int pathLen, int reqSz, const char *contentType,
  1189. byte *buf, int bufSize)
  1190. {
  1191. return wolfIO_HttpBuildRequest_ex(reqType, domainName, path, pathLen, reqSz, contentType, "", buf, bufSize);
  1192. }
  1193. int wolfIO_HttpBuildRequest_ex(const char *reqType, const char *domainName,
  1194. const char *path, int pathLen, int reqSz, const char *contentType,
  1195. const char *exHdrs, byte *buf, int bufSize)
  1196. {
  1197. word32 reqTypeLen, domainNameLen, reqSzStrLen, contentTypeLen, exHdrsLen, maxLen;
  1198. char reqSzStr[6];
  1199. char* req = (char*)buf;
  1200. const char* blankStr = " ";
  1201. const char* http11Str = " HTTP/1.1";
  1202. const char* hostStr = "\r\nHost: ";
  1203. const char* contentLenStr = "\r\nContent-Length: ";
  1204. const char* contentTypeStr = "\r\nContent-Type: ";
  1205. const char* singleCrLfStr = "\r\n";
  1206. const char* doubleCrLfStr = "\r\n\r\n";
  1207. word32 blankStrLen, http11StrLen, hostStrLen, contentLenStrLen,
  1208. contentTypeStrLen, singleCrLfStrLen, doubleCrLfStrLen;
  1209. reqTypeLen = (word32)XSTRLEN(reqType);
  1210. domainNameLen = (word32)XSTRLEN(domainName);
  1211. reqSzStrLen = wolfIO_Word16ToString(reqSzStr, (word16)reqSz);
  1212. contentTypeLen = (word32)XSTRLEN(contentType);
  1213. blankStrLen = (word32)XSTRLEN(blankStr);
  1214. http11StrLen = (word32)XSTRLEN(http11Str);
  1215. hostStrLen = (word32)XSTRLEN(hostStr);
  1216. contentLenStrLen = (word32)XSTRLEN(contentLenStr);
  1217. contentTypeStrLen = (word32)XSTRLEN(contentTypeStr);
  1218. if(exHdrs){
  1219. singleCrLfStrLen = (word32)XSTRLEN(singleCrLfStr);
  1220. exHdrsLen = (word32)XSTRLEN(exHdrs);
  1221. } else {
  1222. singleCrLfStrLen = 0;
  1223. exHdrsLen = 0;
  1224. }
  1225. doubleCrLfStrLen = (word32)XSTRLEN(doubleCrLfStr);
  1226. /* determine max length and check it */
  1227. maxLen =
  1228. reqTypeLen +
  1229. blankStrLen +
  1230. pathLen +
  1231. http11StrLen +
  1232. hostStrLen +
  1233. domainNameLen +
  1234. contentLenStrLen +
  1235. reqSzStrLen +
  1236. contentTypeStrLen +
  1237. contentTypeLen +
  1238. singleCrLfStrLen +
  1239. exHdrsLen +
  1240. doubleCrLfStrLen +
  1241. 1 /* null term */;
  1242. if (maxLen > (word32)bufSize)
  1243. return 0;
  1244. XSTRNCPY((char*)buf, reqType, bufSize);
  1245. buf += reqTypeLen; bufSize -= reqTypeLen;
  1246. XSTRNCPY((char*)buf, blankStr, bufSize);
  1247. buf += blankStrLen; bufSize -= blankStrLen;
  1248. XSTRNCPY((char*)buf, path, bufSize);
  1249. buf += pathLen; bufSize -= pathLen;
  1250. XSTRNCPY((char*)buf, http11Str, bufSize);
  1251. buf += http11StrLen; bufSize -= http11StrLen;
  1252. if (domainNameLen > 0) {
  1253. XSTRNCPY((char*)buf, hostStr, bufSize);
  1254. buf += hostStrLen; bufSize -= hostStrLen;
  1255. XSTRNCPY((char*)buf, domainName, bufSize);
  1256. buf += domainNameLen; bufSize -= domainNameLen;
  1257. }
  1258. if (reqSz > 0 && reqSzStrLen > 0) {
  1259. XSTRNCPY((char*)buf, contentLenStr, bufSize);
  1260. buf += contentLenStrLen; bufSize -= contentLenStrLen;
  1261. XSTRNCPY((char*)buf, reqSzStr, bufSize);
  1262. buf += reqSzStrLen; bufSize -= reqSzStrLen;
  1263. }
  1264. if (contentTypeLen > 0) {
  1265. XSTRNCPY((char*)buf, contentTypeStr, bufSize);
  1266. buf += contentTypeStrLen; bufSize -= contentTypeStrLen;
  1267. XSTRNCPY((char*)buf, contentType, bufSize);
  1268. buf += contentTypeLen; bufSize -= contentTypeLen;
  1269. }
  1270. if (exHdrsLen > 0)
  1271. {
  1272. XSTRNCPY((char *)buf, singleCrLfStr, bufSize);
  1273. buf += singleCrLfStrLen;
  1274. bufSize -= singleCrLfStrLen;
  1275. XSTRNCPY((char *)buf, exHdrs, bufSize);
  1276. buf += exHdrsLen;
  1277. bufSize -= exHdrsLen;
  1278. }
  1279. XSTRNCPY((char*)buf, doubleCrLfStr, bufSize);
  1280. buf += doubleCrLfStrLen;
  1281. #ifdef WOLFIO_DEBUG
  1282. printf("HTTP %s: %s", reqType, req);
  1283. #endif
  1284. /* calculate actual length based on original and new pointer */
  1285. return (int)((char*)buf - req);
  1286. }
  1287. #ifdef HAVE_OCSP
  1288. int wolfIO_HttpBuildRequestOcsp(const char* domainName, const char* path,
  1289. int ocspReqSz, byte* buf, int bufSize)
  1290. {
  1291. const char *cacheCtl = "Cache-Control: no-cache";
  1292. return wolfIO_HttpBuildRequest_ex("POST", domainName, path, (int)XSTRLEN(path),
  1293. ocspReqSz, "application/ocsp-request", cacheCtl, buf, bufSize);
  1294. }
  1295. /* return: >0 OCSP Response Size
  1296. * -1 error */
  1297. int wolfIO_HttpProcessResponseOcsp(int sfd, byte** respBuf,
  1298. byte* httpBuf, int httpBufSz, void* heap)
  1299. {
  1300. const char* appStrList[] = {
  1301. "application/ocsp-response",
  1302. NULL
  1303. };
  1304. return wolfIO_HttpProcessResponse(sfd, appStrList,
  1305. respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_OCSP, heap);
  1306. }
  1307. /* in default wolfSSL callback ctx is the heap pointer */
  1308. int EmbedOcspLookup(void* ctx, const char* url, int urlSz,
  1309. byte* ocspReqBuf, int ocspReqSz, byte** ocspRespBuf)
  1310. {
  1311. SOCKET_T sfd = SOCKET_INVALID;
  1312. word16 port;
  1313. int ret = -1;
  1314. #ifdef WOLFSSL_SMALL_STACK
  1315. char* path;
  1316. char* domainName;
  1317. #else
  1318. char path[MAX_URL_ITEM_SIZE];
  1319. char domainName[MAX_URL_ITEM_SIZE];
  1320. #endif
  1321. #ifdef WOLFSSL_SMALL_STACK
  1322. path = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1323. if (path == NULL)
  1324. return MEMORY_E;
  1325. domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL,
  1326. DYNAMIC_TYPE_TMP_BUFFER);
  1327. if (domainName == NULL) {
  1328. XFREE(path, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1329. return MEMORY_E;
  1330. }
  1331. #endif
  1332. if (ocspReqBuf == NULL || ocspReqSz == 0) {
  1333. WOLFSSL_MSG("OCSP request is required for lookup");
  1334. }
  1335. else if (ocspRespBuf == NULL) {
  1336. WOLFSSL_MSG("Cannot save OCSP response");
  1337. }
  1338. else if (wolfIO_DecodeUrl(url, urlSz, domainName, path, &port) < 0) {
  1339. WOLFSSL_MSG("Unable to decode OCSP URL");
  1340. }
  1341. else {
  1342. /* Note, the library uses the EmbedOcspRespFree() callback to
  1343. * free this buffer. */
  1344. int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
  1345. byte* httpBuf = (byte*)XMALLOC(httpBufSz, ctx, DYNAMIC_TYPE_OCSP);
  1346. if (httpBuf == NULL) {
  1347. WOLFSSL_MSG("Unable to create OCSP response buffer");
  1348. }
  1349. else {
  1350. httpBufSz = wolfIO_HttpBuildRequestOcsp(domainName, path, ocspReqSz,
  1351. httpBuf, httpBufSz);
  1352. ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
  1353. if (ret != 0) {
  1354. WOLFSSL_MSG("OCSP Responder connection failed");
  1355. }
  1356. else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0) !=
  1357. httpBufSz) {
  1358. WOLFSSL_MSG("OCSP http request failed");
  1359. }
  1360. else if (wolfIO_Send(sfd, (char*)ocspReqBuf, ocspReqSz, 0) !=
  1361. ocspReqSz) {
  1362. WOLFSSL_MSG("OCSP ocsp request failed");
  1363. }
  1364. else {
  1365. ret = wolfIO_HttpProcessResponseOcsp(sfd, ocspRespBuf, httpBuf,
  1366. HTTP_SCRATCH_BUFFER_SIZE, ctx);
  1367. }
  1368. if (sfd != SOCKET_INVALID)
  1369. CloseSocket(sfd);
  1370. XFREE(httpBuf, ctx, DYNAMIC_TYPE_OCSP);
  1371. }
  1372. }
  1373. #ifdef WOLFSSL_SMALL_STACK
  1374. XFREE(path, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1375. XFREE(domainName, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1376. #endif
  1377. return ret;
  1378. }
  1379. /* in default callback ctx is heap hint */
  1380. void EmbedOcspRespFree(void* ctx, byte *resp)
  1381. {
  1382. if (resp)
  1383. XFREE(resp, ctx, DYNAMIC_TYPE_OCSP);
  1384. (void)ctx;
  1385. }
  1386. #endif /* HAVE_OCSP */
  1387. #if defined(HAVE_CRL) && defined(HAVE_CRL_IO)
  1388. int wolfIO_HttpBuildRequestCrl(const char* url, int urlSz,
  1389. const char* domainName, byte* buf, int bufSize)
  1390. {
  1391. const char *cacheCtl = "Cache-Control: no-cache";
  1392. return wolfIO_HttpBuildRequest_ex("GET", domainName, url, urlSz, 0, "",
  1393. cacheCtl, buf, bufSize);
  1394. }
  1395. int wolfIO_HttpProcessResponseCrl(WOLFSSL_CRL* crl, int sfd, byte* httpBuf,
  1396. int httpBufSz)
  1397. {
  1398. int ret;
  1399. byte *respBuf = NULL;
  1400. const char* appStrList[] = {
  1401. "application/pkix-crl",
  1402. "application/x-pkcs7-crl",
  1403. NULL
  1404. };
  1405. ret = wolfIO_HttpProcessResponse(sfd, appStrList,
  1406. &respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_CRL, crl->heap);
  1407. if (ret >= 0) {
  1408. ret = BufferLoadCRL(crl, respBuf, ret, WOLFSSL_FILETYPE_ASN1, 0);
  1409. }
  1410. XFREE(respBuf, crl->heap, DYNAMIC_TYPE_CRL);
  1411. return ret;
  1412. }
  1413. int EmbedCrlLookup(WOLFSSL_CRL* crl, const char* url, int urlSz)
  1414. {
  1415. SOCKET_T sfd = SOCKET_INVALID;
  1416. word16 port;
  1417. int ret = -1;
  1418. #ifdef WOLFSSL_SMALL_STACK
  1419. char* domainName;
  1420. #else
  1421. char domainName[MAX_URL_ITEM_SIZE];
  1422. #endif
  1423. #ifdef WOLFSSL_SMALL_STACK
  1424. domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, crl->heap,
  1425. DYNAMIC_TYPE_TMP_BUFFER);
  1426. if (domainName == NULL) {
  1427. return MEMORY_E;
  1428. }
  1429. #endif
  1430. if (wolfIO_DecodeUrl(url, urlSz, domainName, NULL, &port) < 0) {
  1431. WOLFSSL_MSG("Unable to decode CRL URL");
  1432. }
  1433. else {
  1434. int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
  1435. byte* httpBuf = (byte*)XMALLOC(httpBufSz, crl->heap,
  1436. DYNAMIC_TYPE_CRL);
  1437. if (httpBuf == NULL) {
  1438. WOLFSSL_MSG("Unable to create CRL response buffer");
  1439. }
  1440. else {
  1441. httpBufSz = wolfIO_HttpBuildRequestCrl(url, urlSz, domainName,
  1442. httpBuf, httpBufSz);
  1443. ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
  1444. if (ret != 0) {
  1445. WOLFSSL_MSG("CRL connection failed");
  1446. }
  1447. else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0)
  1448. != httpBufSz) {
  1449. WOLFSSL_MSG("CRL http get failed");
  1450. }
  1451. else {
  1452. ret = wolfIO_HttpProcessResponseCrl(crl, sfd, httpBuf,
  1453. HTTP_SCRATCH_BUFFER_SIZE);
  1454. }
  1455. if (sfd != SOCKET_INVALID)
  1456. CloseSocket(sfd);
  1457. XFREE(httpBuf, crl->heap, DYNAMIC_TYPE_CRL);
  1458. }
  1459. }
  1460. #ifdef WOLFSSL_SMALL_STACK
  1461. XFREE(domainName, crl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1462. #endif
  1463. return ret;
  1464. }
  1465. #endif /* HAVE_CRL && HAVE_CRL_IO */
  1466. #endif /* HAVE_HTTP_CLIENT */
  1467. void wolfSSL_CTX_SetIORecv(WOLFSSL_CTX *ctx, CallbackIORecv CBIORecv)
  1468. {
  1469. if (ctx) {
  1470. ctx->CBIORecv = CBIORecv;
  1471. #ifdef OPENSSL_EXTRA
  1472. ctx->cbioFlag |= WOLFSSL_CBIO_RECV;
  1473. #endif
  1474. }
  1475. }
  1476. void wolfSSL_CTX_SetIOSend(WOLFSSL_CTX *ctx, CallbackIOSend CBIOSend)
  1477. {
  1478. if (ctx) {
  1479. ctx->CBIOSend = CBIOSend;
  1480. #ifdef OPENSSL_EXTRA
  1481. ctx->cbioFlag |= WOLFSSL_CBIO_SEND;
  1482. #endif
  1483. }
  1484. }
  1485. /* sets the IO callback to use for receives at WOLFSSL level */
  1486. void wolfSSL_SSLSetIORecv(WOLFSSL *ssl, CallbackIORecv CBIORecv)
  1487. {
  1488. if (ssl) {
  1489. ssl->CBIORecv = CBIORecv;
  1490. #ifdef OPENSSL_EXTRA
  1491. ssl->cbioFlag |= WOLFSSL_CBIO_RECV;
  1492. #endif
  1493. }
  1494. }
  1495. /* sets the IO callback to use for sends at WOLFSSL level */
  1496. void wolfSSL_SSLSetIOSend(WOLFSSL *ssl, CallbackIOSend CBIOSend)
  1497. {
  1498. if (ssl) {
  1499. ssl->CBIOSend = CBIOSend;
  1500. #ifdef OPENSSL_EXTRA
  1501. ssl->cbioFlag |= WOLFSSL_CBIO_SEND;
  1502. #endif
  1503. }
  1504. }
  1505. void wolfSSL_SetIOReadCtx(WOLFSSL* ssl, void *rctx)
  1506. {
  1507. if (ssl)
  1508. ssl->IOCB_ReadCtx = rctx;
  1509. }
  1510. void wolfSSL_SetIOWriteCtx(WOLFSSL* ssl, void *wctx)
  1511. {
  1512. if (ssl)
  1513. ssl->IOCB_WriteCtx = wctx;
  1514. }
  1515. void* wolfSSL_GetIOReadCtx(WOLFSSL* ssl)
  1516. {
  1517. if (ssl)
  1518. return ssl->IOCB_ReadCtx;
  1519. return NULL;
  1520. }
  1521. void* wolfSSL_GetIOWriteCtx(WOLFSSL* ssl)
  1522. {
  1523. if (ssl)
  1524. return ssl->IOCB_WriteCtx;
  1525. return NULL;
  1526. }
  1527. void wolfSSL_SetIOReadFlags(WOLFSSL* ssl, int flags)
  1528. {
  1529. if (ssl)
  1530. ssl->rflags = flags;
  1531. }
  1532. void wolfSSL_SetIOWriteFlags(WOLFSSL* ssl, int flags)
  1533. {
  1534. if (ssl)
  1535. ssl->wflags = flags;
  1536. }
  1537. #ifdef WOLFSSL_DTLS
  1538. void wolfSSL_CTX_SetGenCookie(WOLFSSL_CTX* ctx, CallbackGenCookie cb)
  1539. {
  1540. if (ctx)
  1541. ctx->CBIOCookie = cb;
  1542. }
  1543. void wolfSSL_SetCookieCtx(WOLFSSL* ssl, void *ctx)
  1544. {
  1545. if (ssl)
  1546. ssl->IOCB_CookieCtx = ctx;
  1547. }
  1548. void* wolfSSL_GetCookieCtx(WOLFSSL* ssl)
  1549. {
  1550. if (ssl)
  1551. return ssl->IOCB_CookieCtx;
  1552. return NULL;
  1553. }
  1554. #endif /* WOLFSSL_DTLS */
  1555. #ifdef WOLFSSL_SESSION_EXPORT
  1556. void wolfSSL_CTX_SetIOGetPeer(WOLFSSL_CTX* ctx, CallbackGetPeer cb)
  1557. {
  1558. if (ctx)
  1559. ctx->CBGetPeer = cb;
  1560. }
  1561. void wolfSSL_CTX_SetIOSetPeer(WOLFSSL_CTX* ctx, CallbackSetPeer cb)
  1562. {
  1563. if (ctx)
  1564. ctx->CBSetPeer = cb;
  1565. }
  1566. #endif /* WOLFSSL_SESSION_EXPORT */
  1567. #ifdef HAVE_NETX
  1568. /* The NetX receive callback
  1569. * return : bytes read, or error
  1570. */
  1571. int NetX_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1572. {
  1573. NetX_Ctx* nxCtx = (NetX_Ctx*)ctx;
  1574. ULONG left;
  1575. ULONG total;
  1576. ULONG copied = 0;
  1577. UINT status;
  1578. (void)ssl;
  1579. if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
  1580. WOLFSSL_MSG("NetX Recv NULL parameters");
  1581. return WOLFSSL_CBIO_ERR_GENERAL;
  1582. }
  1583. if (nxCtx->nxPacket == NULL) {
  1584. status = nx_tcp_socket_receive(nxCtx->nxSocket, &nxCtx->nxPacket,
  1585. nxCtx->nxWait);
  1586. if (status != NX_SUCCESS) {
  1587. WOLFSSL_MSG("NetX Recv receive error");
  1588. return WOLFSSL_CBIO_ERR_GENERAL;
  1589. }
  1590. }
  1591. if (nxCtx->nxPacket) {
  1592. status = nx_packet_length_get(nxCtx->nxPacket, &total);
  1593. if (status != NX_SUCCESS) {
  1594. WOLFSSL_MSG("NetX Recv length get error");
  1595. return WOLFSSL_CBIO_ERR_GENERAL;
  1596. }
  1597. left = total - nxCtx->nxOffset;
  1598. status = nx_packet_data_extract_offset(nxCtx->nxPacket, nxCtx->nxOffset,
  1599. buf, sz, &copied);
  1600. if (status != NX_SUCCESS) {
  1601. WOLFSSL_MSG("NetX Recv data extract offset error");
  1602. return WOLFSSL_CBIO_ERR_GENERAL;
  1603. }
  1604. nxCtx->nxOffset += copied;
  1605. if (copied == left) {
  1606. WOLFSSL_MSG("NetX Recv Drained packet");
  1607. nx_packet_release(nxCtx->nxPacket);
  1608. nxCtx->nxPacket = NULL;
  1609. nxCtx->nxOffset = 0;
  1610. }
  1611. }
  1612. return copied;
  1613. }
  1614. /* The NetX send callback
  1615. * return : bytes sent, or error
  1616. */
  1617. int NetX_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  1618. {
  1619. NetX_Ctx* nxCtx = (NetX_Ctx*)ctx;
  1620. NX_PACKET* packet;
  1621. NX_PACKET_POOL* pool; /* shorthand */
  1622. UINT status;
  1623. (void)ssl;
  1624. if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
  1625. WOLFSSL_MSG("NetX Send NULL parameters");
  1626. return WOLFSSL_CBIO_ERR_GENERAL;
  1627. }
  1628. pool = nxCtx->nxSocket->nx_tcp_socket_ip_ptr->nx_ip_default_packet_pool;
  1629. status = nx_packet_allocate(pool, &packet, NX_TCP_PACKET,
  1630. nxCtx->nxWait);
  1631. if (status != NX_SUCCESS) {
  1632. WOLFSSL_MSG("NetX Send packet alloc error");
  1633. return WOLFSSL_CBIO_ERR_GENERAL;
  1634. }
  1635. status = nx_packet_data_append(packet, buf, sz, pool, nxCtx->nxWait);
  1636. if (status != NX_SUCCESS) {
  1637. nx_packet_release(packet);
  1638. WOLFSSL_MSG("NetX Send data append error");
  1639. return WOLFSSL_CBIO_ERR_GENERAL;
  1640. }
  1641. status = nx_tcp_socket_send(nxCtx->nxSocket, packet, nxCtx->nxWait);
  1642. if (status != NX_SUCCESS) {
  1643. nx_packet_release(packet);
  1644. WOLFSSL_MSG("NetX Send socket send error");
  1645. return WOLFSSL_CBIO_ERR_GENERAL;
  1646. }
  1647. return sz;
  1648. }
  1649. /* like set_fd, but for default NetX context */
  1650. void wolfSSL_SetIO_NetX(WOLFSSL* ssl, NX_TCP_SOCKET* nxSocket, ULONG waitOption)
  1651. {
  1652. if (ssl) {
  1653. ssl->nxCtx.nxSocket = nxSocket;
  1654. ssl->nxCtx.nxWait = waitOption;
  1655. }
  1656. }
  1657. #endif /* HAVE_NETX */
  1658. #ifdef MICRIUM
  1659. /* Micrium uTCP/IP port, using the NetSock API
  1660. * TCP and UDP are currently supported with the callbacks below.
  1661. *
  1662. * WOLFSSL_SESSION_EXPORT is not yet supported, would need EmbedGetPeer()
  1663. * and EmbedSetPeer() callbacks implemented.
  1664. *
  1665. * HAVE_CRL is not yet supported, would need an EmbedCrlLookup()
  1666. * callback implemented.
  1667. *
  1668. * HAVE_OCSP is not yet supported, would need an EmbedOCSPLookup()
  1669. * callback implemented.
  1670. */
  1671. /* The Micrium uTCP/IP send callback
  1672. * return : bytes sent, or error
  1673. */
  1674. int MicriumSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  1675. {
  1676. NET_SOCK_ID sd = *(int*)ctx;
  1677. NET_SOCK_RTN_CODE ret;
  1678. NET_ERR err;
  1679. ret = NetSock_TxData(sd, buf, sz, ssl->wflags, &err);
  1680. if (ret < 0) {
  1681. WOLFSSL_MSG("Embed Send error");
  1682. if (err == NET_ERR_TX) {
  1683. WOLFSSL_MSG("\tWould block");
  1684. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  1685. } else {
  1686. WOLFSSL_MSG("\tGeneral error");
  1687. return WOLFSSL_CBIO_ERR_GENERAL;
  1688. }
  1689. }
  1690. return ret;
  1691. }
  1692. /* The Micrium uTCP/IP receive callback
  1693. * return : nb bytes read, or error
  1694. */
  1695. int MicriumReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1696. {
  1697. NET_SOCK_ID sd = *(int*)ctx;
  1698. NET_SOCK_RTN_CODE ret;
  1699. NET_ERR err;
  1700. #ifdef WOLFSSL_DTLS
  1701. {
  1702. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  1703. if (wolfSSL_dtls(ssl)
  1704. && !wolfSSL_dtls_get_using_nonblock(ssl)
  1705. && dtls_timeout != 0) {
  1706. /* needs timeout in milliseconds */
  1707. NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout * 1000, &err);
  1708. if (err != NET_SOCK_ERR_NONE) {
  1709. WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
  1710. }
  1711. }
  1712. }
  1713. #endif
  1714. ret = NetSock_RxData(sd, buf, sz, ssl->rflags, &err);
  1715. if (ret < 0) {
  1716. WOLFSSL_MSG("Embed Receive error");
  1717. if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
  1718. err == NET_ERR_FAULT_LOCK_ACQUIRE) {
  1719. if (!wolfSSL_dtls(ssl) || wolfSSL_dtls_get_using_nonblock(ssl)) {
  1720. WOLFSSL_MSG("\tWould block");
  1721. return WOLFSSL_CBIO_ERR_WANT_READ;
  1722. }
  1723. else {
  1724. WOLFSSL_MSG("\tSocket timeout");
  1725. return WOLFSSL_CBIO_ERR_TIMEOUT;
  1726. }
  1727. } else if (err == NET_SOCK_ERR_CLOSED) {
  1728. WOLFSSL_MSG("Embed receive connection closed");
  1729. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  1730. } else {
  1731. WOLFSSL_MSG("\tGeneral error");
  1732. return WOLFSSL_CBIO_ERR_GENERAL;
  1733. }
  1734. }
  1735. return ret;
  1736. }
  1737. /* The Micrium uTCP/IP receivefrom callback
  1738. * return : nb bytes read, or error
  1739. */
  1740. int MicriumReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1741. {
  1742. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  1743. NET_SOCK_ID sd = dtlsCtx->rfd;
  1744. NET_SOCK_ADDR peer;
  1745. NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
  1746. NET_SOCK_RTN_CODE ret;
  1747. NET_ERR err;
  1748. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  1749. WOLFSSL_ENTER("MicriumReceiveFrom()");
  1750. if (ssl->options.handShakeDone)
  1751. dtls_timeout = 0;
  1752. if (!wolfSSL_dtls_get_using_nonblock(ssl)) {
  1753. /* needs timeout in milliseconds */
  1754. NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout * 1000, &err);
  1755. if (err != NET_SOCK_ERR_NONE) {
  1756. WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
  1757. }
  1758. }
  1759. ret = NetSock_RxDataFrom(sd, buf, sz, ssl->rflags, &peer, &peerSz,
  1760. 0, 0, 0, &err);
  1761. if (ret < 0) {
  1762. WOLFSSL_MSG("Embed Receive From error");
  1763. if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
  1764. err == NET_ERR_FAULT_LOCK_ACQUIRE) {
  1765. if (wolfSSL_dtls_get_using_nonblock(ssl)) {
  1766. WOLFSSL_MSG("\tWould block");
  1767. return WOLFSSL_CBIO_ERR_WANT_READ;
  1768. }
  1769. else {
  1770. WOLFSSL_MSG("\tSocket timeout");
  1771. return WOLFSSL_CBIO_ERR_TIMEOUT;
  1772. }
  1773. } else {
  1774. WOLFSSL_MSG("\tGeneral error");
  1775. return WOLFSSL_CBIO_ERR_GENERAL;
  1776. }
  1777. }
  1778. else {
  1779. if (dtlsCtx->peer.sz > 0
  1780. && peerSz != (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz
  1781. && XMEMCMP(&peer, dtlsCtx->peer.sa, peerSz) != 0) {
  1782. WOLFSSL_MSG("\tIgnored packet from invalid peer");
  1783. return WOLFSSL_CBIO_ERR_WANT_READ;
  1784. }
  1785. }
  1786. return ret;
  1787. }
  1788. /* The Micrium uTCP/IP sendto callback
  1789. * return : nb bytes sent, or error
  1790. */
  1791. int MicriumSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  1792. {
  1793. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  1794. NET_SOCK_ID sd = dtlsCtx->wfd;
  1795. NET_SOCK_RTN_CODE ret;
  1796. NET_ERR err;
  1797. WOLFSSL_ENTER("MicriumSendTo()");
  1798. ret = NetSock_TxDataTo(sd, buf, sz, ssl->wflags,
  1799. (NET_SOCK_ADDR*)dtlsCtx->peer.sa,
  1800. (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz,
  1801. &err);
  1802. if (err < 0) {
  1803. WOLFSSL_MSG("Embed Send To error");
  1804. if (err == NET_ERR_TX) {
  1805. WOLFSSL_MSG("\tWould block");
  1806. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  1807. } else {
  1808. WOLFSSL_MSG("\tGeneral error");
  1809. return WOLFSSL_CBIO_ERR_GENERAL;
  1810. }
  1811. }
  1812. return ret;
  1813. }
  1814. /* Micrium DTLS Generate Cookie callback
  1815. * return : number of bytes copied into buf, or error
  1816. */
  1817. int MicriumGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
  1818. {
  1819. NET_SOCK_ADDR peer;
  1820. NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
  1821. byte digest[WC_SHA_DIGEST_SIZE];
  1822. int ret = 0;
  1823. (void)ctx;
  1824. XMEMSET(&peer, 0, sizeof(peer));
  1825. if (wolfSSL_dtls_get_peer(ssl, (void*)&peer,
  1826. (unsigned int*)&peerSz) != WOLFSSL_SUCCESS) {
  1827. WOLFSSL_MSG("getpeername failed in MicriumGenerateCookie");
  1828. return GEN_COOKIE_E;
  1829. }
  1830. ret = wc_ShaHash((byte*)&peer, peerSz, digest);
  1831. if (ret != 0)
  1832. return ret;
  1833. if (sz > WC_SHA_DIGEST_SIZE)
  1834. sz = WC_SHA_DIGEST_SIZE;
  1835. XMEMCPY(buf, digest, sz);
  1836. return sz;
  1837. }
  1838. #endif /* MICRIUM */
  1839. #if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  1840. #include <os/os_error.h>
  1841. #include <os/os_mbuf.h>
  1842. #include <os/os_mempool.h>
  1843. #define MB_NAME "wolfssl_mb"
  1844. typedef struct Mynewt_Ctx {
  1845. struct mn_socket *mnSocket; /* send/recv socket handler */
  1846. struct mn_sockaddr_in mnSockAddrIn; /* socket address */
  1847. struct os_mbuf *mnPacket; /* incoming packet handle
  1848. for short reads */
  1849. int reading; /* reading flag */
  1850. /* private */
  1851. void *mnMemBuffer; /* memory buffer for mempool */
  1852. struct os_mempool mnMempool; /* mempool */
  1853. struct os_mbuf_pool mnMbufpool; /* mbuf pool */
  1854. } Mynewt_Ctx;
  1855. void mynewt_ctx_clear(void *ctx) {
  1856. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  1857. if(!mynewt_ctx) return;
  1858. if(mynewt_ctx->mnPacket) {
  1859. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  1860. mynewt_ctx->mnPacket = NULL;
  1861. }
  1862. os_mempool_clear(&mynewt_ctx->mnMempool);
  1863. XFREE(mynewt_ctx->mnMemBuffer, 0, 0);
  1864. XFREE(mynewt_ctx, 0, 0);
  1865. }
  1866. /* return Mynewt_Ctx instance */
  1867. void* mynewt_ctx_new() {
  1868. int rc = 0;
  1869. Mynewt_Ctx *mynewt_ctx;
  1870. int mem_buf_count = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_COUNT);
  1871. int mem_buf_size = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_SIZE);
  1872. int mempool_bytes = OS_MEMPOOL_BYTES(mem_buf_count, mem_buf_size);
  1873. mynewt_ctx = (Mynewt_Ctx *)XMALLOC(sizeof(struct Mynewt_Ctx),
  1874. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1875. if(!mynewt_ctx) return NULL;
  1876. XMEMSET(mynewt_ctx, 0, sizeof(Mynewt_Ctx));
  1877. mynewt_ctx->mnMemBuffer = (void *)XMALLOC(mempool_bytes, 0, 0);
  1878. if(!mynewt_ctx->mnMemBuffer) {
  1879. mynewt_ctx_clear((void*)mynewt_ctx);
  1880. return NULL;
  1881. }
  1882. rc = os_mempool_init(&mynewt_ctx->mnMempool,
  1883. mem_buf_count, mem_buf_size,
  1884. mynewt_ctx->mnMemBuffer, MB_NAME);
  1885. if(rc != 0) {
  1886. mynewt_ctx_clear((void*)mynewt_ctx);
  1887. return NULL;
  1888. }
  1889. rc = os_mbuf_pool_init(&mynewt_ctx->mnMbufpool, &mynewt_ctx->mnMempool,
  1890. mem_buf_count, mem_buf_size);
  1891. if(rc != 0) {
  1892. mynewt_ctx_clear((void*)mynewt_ctx);
  1893. return NULL;
  1894. }
  1895. return mynewt_ctx;
  1896. }
  1897. static void mynewt_sock_writable(void *arg, int err);
  1898. static void mynewt_sock_readable(void *arg, int err);
  1899. static const union mn_socket_cb mynewt_sock_cbs = {
  1900. .socket.writable = mynewt_sock_writable,
  1901. .socket.readable = mynewt_sock_readable,
  1902. };
  1903. static void mynewt_sock_writable(void *arg, int err)
  1904. {
  1905. /* do nothing */
  1906. }
  1907. static void mynewt_sock_readable(void *arg, int err)
  1908. {
  1909. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)arg;
  1910. if (err && mynewt_ctx->reading) {
  1911. mynewt_ctx->reading = 0;
  1912. }
  1913. }
  1914. /* The Mynewt receive callback
  1915. * return : bytes read, or error
  1916. */
  1917. int Mynewt_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1918. {
  1919. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  1920. int rc = 0;
  1921. struct mn_sockaddr_in from;
  1922. struct os_mbuf *m;
  1923. int read_sz = 0;
  1924. word16 total;
  1925. if (mynewt_ctx == NULL || mynewt_ctx->mnSocket == NULL) {
  1926. WOLFSSL_MSG("Mynewt Recv NULL parameters");
  1927. return WOLFSSL_CBIO_ERR_GENERAL;
  1928. }
  1929. if(mynewt_ctx->mnPacket == NULL) {
  1930. mynewt_ctx->mnPacket = os_mbuf_get_pkthdr(&mynewt_ctx->mnMbufpool, 0);
  1931. if(mynewt_ctx->mnPacket == NULL) {
  1932. return MEMORY_E;
  1933. }
  1934. mynewt_ctx->reading = 1;
  1935. while(mynewt_ctx->reading && rc == 0) {
  1936. rc = mn_recvfrom(mynewt_ctx->mnSocket, &m, (struct mn_sockaddr *) &from);
  1937. if(rc == MN_ECONNABORTED) {
  1938. rc = 0;
  1939. mynewt_ctx->reading = 0;
  1940. break;
  1941. }
  1942. if (!(rc == 0 || rc == MN_EAGAIN)) {
  1943. WOLFSSL_MSG("Mynewt Recv receive error");
  1944. mynewt_ctx->reading = 0;
  1945. break;
  1946. }
  1947. if(rc == 0) {
  1948. int len = OS_MBUF_PKTLEN(m);
  1949. if(len == 0) {
  1950. break;
  1951. }
  1952. rc = os_mbuf_appendfrom(mynewt_ctx->mnPacket, m, 0, len);
  1953. if(rc != 0) {
  1954. WOLFSSL_MSG("Mynewt Recv os_mbuf_appendfrom error");
  1955. break;
  1956. }
  1957. os_mbuf_free_chain(m);
  1958. m = NULL;
  1959. } else if(rc == MN_EAGAIN) {
  1960. /* continue to until reading all of packet data. */
  1961. rc = 0;
  1962. break;
  1963. }
  1964. }
  1965. if(rc != 0) {
  1966. mynewt_ctx->reading = 0;
  1967. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  1968. mynewt_ctx->mnPacket = NULL;
  1969. return rc;
  1970. }
  1971. }
  1972. if(mynewt_ctx->mnPacket) {
  1973. total = OS_MBUF_PKTLEN(mynewt_ctx->mnPacket);
  1974. read_sz = (total >= sz)? sz : total;
  1975. os_mbuf_copydata(mynewt_ctx->mnPacket, 0, read_sz, (void*)buf);
  1976. os_mbuf_adj(mynewt_ctx->mnPacket, read_sz);
  1977. if (read_sz == total) {
  1978. WOLFSSL_MSG("Mynewt Recv Drained packet");
  1979. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  1980. mynewt_ctx->mnPacket = NULL;
  1981. }
  1982. }
  1983. return read_sz;
  1984. }
  1985. /* The Mynewt send callback
  1986. * return : bytes sent, or error
  1987. */
  1988. int Mynewt_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  1989. {
  1990. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  1991. int rc = 0;
  1992. struct os_mbuf *m;
  1993. int write_sz = 0;
  1994. m = os_msys_get_pkthdr(sz, 0);
  1995. if (!m) {
  1996. WOLFSSL_MSG("Mynewt Send os_msys_get_pkthdr error");
  1997. return WOLFSSL_CBIO_ERR_GENERAL;
  1998. }
  1999. rc = os_mbuf_copyinto(m, 0, buf, sz);
  2000. if (rc != 0) {
  2001. WOLFSSL_MSG("Mynewt Send os_mbuf_copyinto error");
  2002. os_mbuf_free_chain(m);
  2003. return rc;
  2004. }
  2005. rc = mn_sendto(mynewt_ctx->mnSocket, m, (struct mn_sockaddr *)&mynewt_ctx->mnSockAddrIn);
  2006. if(rc != 0) {
  2007. WOLFSSL_MSG("Mynewt Send mn_sendto error");
  2008. os_mbuf_free_chain(m);
  2009. return rc;
  2010. }
  2011. write_sz = sz;
  2012. return write_sz;
  2013. }
  2014. /* like set_fd, but for default NetX context */
  2015. void wolfSSL_SetIO_Mynewt(WOLFSSL* ssl, struct mn_socket* mnSocket, struct mn_sockaddr_in* mnSockAddrIn)
  2016. {
  2017. if (ssl && ssl->mnCtx) {
  2018. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)ssl->mnCtx;
  2019. mynewt_ctx->mnSocket = mnSocket;
  2020. XMEMCPY(&mynewt_ctx->mnSockAddrIn, mnSockAddrIn, sizeof(struct mn_sockaddr_in));
  2021. mn_socket_set_cbs(mynewt_ctx->mnSocket, mnSocket, &mynewt_sock_cbs);
  2022. }
  2023. }
  2024. #endif /* defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) */
  2025. #ifdef WOLFSSL_UIP
  2026. #include <uip.h>
  2027. #include <stdio.h>
  2028. /* uIP TCP/IP port, using the native tcp/udp socket api.
  2029. * TCP and UDP are currently supported with the callbacks below.
  2030. *
  2031. */
  2032. /* The uIP tcp send callback
  2033. * return : bytes sent, or error
  2034. */
  2035. int uIPSend(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2036. {
  2037. uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
  2038. int ret;
  2039. unsigned int max_sendlen;
  2040. int total_written = 0;
  2041. (void)ssl;
  2042. do {
  2043. unsigned int bytes_left = sz - total_written;
  2044. max_sendlen = tcp_socket_max_sendlen(&ctx->conn.tcp);
  2045. if (bytes_left > max_sendlen) {
  2046. printf("Send limited by buffer\r\n");
  2047. bytes_left = max_sendlen;
  2048. }
  2049. if (bytes_left == 0) {
  2050. printf("Buffer full!\r\n");
  2051. break;
  2052. }
  2053. ret = tcp_socket_send(&ctx->conn.tcp, (unsigned char *)buf + total_written, bytes_left);
  2054. if (ret <= 0)
  2055. break;
  2056. total_written += ret;
  2057. } while(total_written < sz);
  2058. if (total_written == 0)
  2059. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2060. return total_written;
  2061. }
  2062. int uIPSendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2063. {
  2064. uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
  2065. int ret = 0;
  2066. (void)ssl;
  2067. ret = udp_socket_sendto(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr, ctx->peer_port );
  2068. if (ret == 0)
  2069. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2070. return ret;
  2071. }
  2072. /* The uIP uTCP/IP receive callback
  2073. * return : nb bytes read, or error
  2074. */
  2075. int uIPReceive(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
  2076. {
  2077. uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
  2078. if (!ctx || !ctx->ssl_rx_databuf)
  2079. return -1;
  2080. (void)ssl;
  2081. if (ctx->ssl_rb_len > 0) {
  2082. if (sz > ctx->ssl_rb_len - ctx->ssl_rb_off)
  2083. sz = ctx->ssl_rb_len - ctx->ssl_rb_off;
  2084. XMEMCPY(buf, ctx->ssl_rx_databuf + ctx->ssl_rb_off, sz);
  2085. ctx->ssl_rb_off += sz;
  2086. if (ctx->ssl_rb_off >= ctx->ssl_rb_len) {
  2087. ctx->ssl_rb_len = 0;
  2088. ctx->ssl_rb_off = 0;
  2089. }
  2090. return sz;
  2091. } else {
  2092. return WOLFSSL_CBIO_ERR_WANT_READ;
  2093. }
  2094. }
  2095. /* uIP DTLS Generate Cookie callback
  2096. * return : number of bytes copied into buf, or error
  2097. */
  2098. int uIPGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
  2099. {
  2100. uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
  2101. byte token[32];
  2102. byte digest[WC_SHA_DIGEST_SIZE];
  2103. int ret = 0;
  2104. XMEMSET(token, 0, sizeof(token));
  2105. XMEMCPY(token, &ctx->peer_addr, sizeof(uip_ipaddr_t));
  2106. XMEMCPY(token + sizeof(uip_ipaddr_t), &ctx->peer_port, sizeof(word16));
  2107. ret = wc_ShaHash(token, sizeof(uip_ipaddr_t) + sizeof(word16), digest);
  2108. if (ret != 0)
  2109. return ret;
  2110. if (sz > WC_SHA_DIGEST_SIZE)
  2111. sz = WC_SHA_DIGEST_SIZE;
  2112. XMEMCPY(buf, digest, sz);
  2113. return sz;
  2114. }
  2115. #endif /* WOLFSSL_UIP */
  2116. #ifdef WOLFSSL_GNRC
  2117. #include <net/sock.h>
  2118. #include <net/sock/tcp.h>
  2119. #include <stdio.h>
  2120. /* GNRC TCP/IP port, using the native tcp/udp socket api.
  2121. * TCP and UDP are currently supported with the callbacks below.
  2122. *
  2123. */
  2124. /* The GNRC tcp send callback
  2125. * return : bytes sent, or error
  2126. */
  2127. int GNRC_SendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2128. {
  2129. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2130. int ret = 0;
  2131. (void)ssl;
  2132. if (!ctx)
  2133. return WOLFSSL_CBIO_ERR_GENERAL;
  2134. ret = sock_udp_send(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr);
  2135. if (ret == 0)
  2136. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2137. return ret;
  2138. }
  2139. /* The GNRC TCP/IP receive callback
  2140. * return : nb bytes read, or error
  2141. */
  2142. int GNRC_ReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
  2143. {
  2144. sock_udp_ep_t ep;
  2145. int ret;
  2146. word32 timeout = wolfSSL_dtls_get_current_timeout(ssl) * 1000000;
  2147. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2148. if (!ctx)
  2149. return WOLFSSL_CBIO_ERR_GENERAL;
  2150. (void)ssl;
  2151. if (wolfSSL_get_using_nonblock(ctx->ssl)) {
  2152. timeout = 0;
  2153. }
  2154. ret = sock_udp_recv(&ctx->conn.udp, buf, sz, timeout, &ep);
  2155. if (ret > 0) {
  2156. if (ctx->peer_addr.port == 0)
  2157. XMEMCPY(&ctx->peer_addr, &ep, sizeof(sock_udp_ep_t));
  2158. }
  2159. if (ret == -ETIMEDOUT) {
  2160. return WOLFSSL_CBIO_ERR_WANT_READ;
  2161. }
  2162. return ret;
  2163. }
  2164. /* GNRC DTLS Generate Cookie callback
  2165. * return : number of bytes copied into buf, or error
  2166. */
  2167. #define GNRC_MAX_TOKEN_SIZE (32)
  2168. int GNRC_GenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
  2169. {
  2170. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2171. if (!ctx)
  2172. return WOLFSSL_CBIO_ERR_GENERAL;
  2173. byte token[GNRC_MAX_TOKEN_SIZE];
  2174. byte digest[WC_SHA_DIGEST_SIZE];
  2175. int ret = 0;
  2176. size_t token_size = sizeof(sock_udp_ep_t);
  2177. (void)ssl;
  2178. if (token_size > GNRC_MAX_TOKEN_SIZE)
  2179. token_size = GNRC_MAX_TOKEN_SIZE;
  2180. XMEMSET(token, 0, GNRC_MAX_TOKEN_SIZE);
  2181. XMEMCPY(token, &ctx->peer_addr, token_size);
  2182. ret = wc_ShaHash(token, token_size, digest);
  2183. if (ret != 0)
  2184. return ret;
  2185. if (sz > WC_SHA_DIGEST_SIZE)
  2186. sz = WC_SHA_DIGEST_SIZE;
  2187. XMEMCPY(buf, digest, sz);
  2188. return sz;
  2189. }
  2190. #endif /* WOLFSSL_GNRC */
  2191. #endif /* WOLFCRYPT_ONLY */