wolfio.c 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484
  1. /* wolfio.c
  2. *
  3. * Copyright (C) 2006-2023 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. #ifndef WOLFSSL_STRERROR_BUFFER_SIZE
  22. #define WOLFSSL_STRERROR_BUFFER_SIZE 256
  23. #endif
  24. #ifdef HAVE_CONFIG_H
  25. #include <config.h>
  26. #endif
  27. #include <wolfssl/wolfcrypt/settings.h>
  28. #ifndef WOLFCRYPT_ONLY
  29. #ifdef _WIN32_WCE
  30. /* On WinCE winsock2.h must be included before windows.h for socket stuff */
  31. #include <winsock2.h>
  32. #endif
  33. #include <wolfssl/internal.h>
  34. #include <wolfssl/error-ssl.h>
  35. #include <wolfssl/wolfio.h>
  36. #if defined(HAVE_HTTP_CLIENT)
  37. #include <stdlib.h> /* strtol() */
  38. #endif
  39. /*
  40. Possible IO enable options:
  41. * WOLFSSL_USER_IO: Disables default Embed* callbacks and default: off
  42. allows user to define their own using
  43. wolfSSL_CTX_SetIORecv and wolfSSL_CTX_SetIOSend
  44. * USE_WOLFSSL_IO: Enables the wolfSSL IO functions default: on
  45. * HAVE_HTTP_CLIENT: Enables HTTP client API's default: off
  46. (unless HAVE_OCSP or HAVE_CRL_IO defined)
  47. * HAVE_IO_TIMEOUT: Enables support for connect timeout default: off
  48. *
  49. * DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER: This flag has effect only if
  50. * ASN_NO_TIME is enabled. If enabled invalid peers messages are ignored
  51. * indefinetely. If not enabled EmbedReceiveFrom will return timeout after
  52. * DTLS_RECEIVEFROM_MAX_INVALID_PEER number of packets from invalid peers. When
  53. * enabled, without a timer, EmbedReceivefrom can't check if the timeout is
  54. * expired and it may never return under a continuous flow of invalid packets.
  55. * default: off
  56. */
  57. /* if user writes own I/O callbacks they can define WOLFSSL_USER_IO to remove
  58. automatic setting of default I/O functions EmbedSend() and EmbedReceive()
  59. but they'll still need SetCallback xxx() at end of file
  60. */
  61. #if defined(NO_ASN_TIME) && !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER) \
  62. && !defined(DTLS_RECEIVEFROM_MAX_INVALID_PEER)
  63. #define DTLS_RECEIVEFROM_MAX_INVALID_PEER 10
  64. #endif
  65. #if defined(USE_WOLFSSL_IO) || defined(HAVE_HTTP_CLIENT)
  66. /* Translates return codes returned from
  67. * send() and recv() if need be.
  68. */
  69. static WC_INLINE int TranslateReturnCode(int old, int sd)
  70. {
  71. (void)sd;
  72. #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  73. if (old == 0) {
  74. errno = SOCKET_EWOULDBLOCK;
  75. return -1; /* convert to BSD style wouldblock as error */
  76. }
  77. if (old < 0) {
  78. errno = RTCS_geterror(sd);
  79. if (errno == RTCSERR_TCP_CONN_CLOSING)
  80. return 0; /* convert to BSD style closing */
  81. if (errno == RTCSERR_TCP_CONN_RLSD)
  82. errno = SOCKET_ECONNRESET;
  83. if (errno == RTCSERR_TCP_TIMED_OUT)
  84. errno = SOCKET_EAGAIN;
  85. }
  86. #endif
  87. return old;
  88. }
  89. static WC_INLINE int wolfSSL_LastError(int err)
  90. {
  91. (void)err; /* Suppress unused arg */
  92. #ifdef USE_WINDOWS_API
  93. return WSAGetLastError();
  94. #elif defined(EBSNET)
  95. return xn_getlasterror();
  96. #elif defined(WOLFSSL_LINUXKM)
  97. return err; /* Return provided error value */
  98. #elif defined(FUSION_RTOS)
  99. #include <fclerrno.h>
  100. return FCL_GET_ERRNO;
  101. #else
  102. return errno;
  103. #endif
  104. }
  105. static int TranslateIoError(int err)
  106. {
  107. #ifdef _WIN32
  108. size_t errstr_offset;
  109. char errstr[WOLFSSL_STRERROR_BUFFER_SIZE];
  110. #endif /* _WIN32 */
  111. if (err > 0)
  112. return err;
  113. err = wolfSSL_LastError(err);
  114. #if SOCKET_EWOULDBLOCK != SOCKET_EAGAIN
  115. if ((err == SOCKET_EWOULDBLOCK) || (err == SOCKET_EAGAIN))
  116. #else
  117. if (err == SOCKET_EWOULDBLOCK)
  118. #endif
  119. {
  120. WOLFSSL_MSG("\tWould block");
  121. return WOLFSSL_CBIO_ERR_WANT_READ;
  122. }
  123. else if (err == SOCKET_ECONNRESET) {
  124. WOLFSSL_MSG("\tConnection reset");
  125. return WOLFSSL_CBIO_ERR_CONN_RST;
  126. }
  127. else if (err == SOCKET_EINTR) {
  128. WOLFSSL_MSG("\tSocket interrupted");
  129. return WOLFSSL_CBIO_ERR_ISR;
  130. }
  131. else if (err == SOCKET_EPIPE) {
  132. WOLFSSL_MSG("\tBroken pipe");
  133. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  134. }
  135. else if (err == SOCKET_ECONNABORTED) {
  136. WOLFSSL_MSG("\tConnection aborted");
  137. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  138. }
  139. #if defined(_WIN32)
  140. strcpy_s(errstr, sizeof(errstr), "\tGeneral error: ");
  141. errstr_offset = strlen(errstr);
  142. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  143. NULL,
  144. err,
  145. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  146. (LPSTR)(errstr + errstr_offset),
  147. (DWORD)(sizeof(errstr) - errstr_offset),
  148. NULL);
  149. WOLFSSL_MSG(errstr);
  150. #else
  151. WOLFSSL_MSG("\tGeneral error");
  152. #endif
  153. return WOLFSSL_CBIO_ERR_GENERAL;
  154. }
  155. #endif /* USE_WOLFSSL_IO || HAVE_HTTP_CLIENT */
  156. #ifdef OPENSSL_EXTRA
  157. #ifndef NO_BIO
  158. /* Use the WOLFSSL read BIO for receiving data. This is set by the function
  159. * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIORecv.
  160. *
  161. * ssl WOLFSSL struct passed in that has this function set as the receive
  162. * callback.
  163. * buf buffer to fill with data read
  164. * sz size of buf buffer
  165. * ctx a user set context
  166. *
  167. * returns the amount of data read or want read. See WOLFSSL_CBIO_ERR_* values.
  168. */
  169. int BioReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  170. {
  171. int recvd = WOLFSSL_CBIO_ERR_GENERAL;
  172. WOLFSSL_ENTER("BioReceive");
  173. if (ssl->biord == NULL) {
  174. WOLFSSL_MSG("WOLFSSL biord not set");
  175. return WOLFSSL_CBIO_ERR_GENERAL;
  176. }
  177. recvd = wolfSSL_BIO_read(ssl->biord, buf, sz);
  178. if (recvd <= 0) {
  179. if (/* ssl->biowr->wrIdx is checked for Bind9 */
  180. wolfSSL_BIO_method_type(ssl->biowr) == WOLFSSL_BIO_BIO &&
  181. wolfSSL_BIO_wpending(ssl->biowr) != 0 &&
  182. /* Not sure this pending check is necessary but let's double
  183. * check that the read BIO is empty before we signal a write
  184. * need */
  185. wolfSSL_BIO_supports_pending(ssl->biord) &&
  186. wolfSSL_BIO_ctrl_pending(ssl->biord) == 0) {
  187. /* Let's signal to the app layer that we have
  188. * data pending that needs to be sent. */
  189. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  190. }
  191. else if (ssl->biord->type == WOLFSSL_BIO_SOCKET) {
  192. if (recvd == 0) {
  193. WOLFSSL_MSG("BioReceive connection closed");
  194. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  195. }
  196. #ifdef USE_WOLFSSL_IO
  197. recvd = TranslateIoError(recvd);
  198. #endif
  199. return recvd;
  200. }
  201. /* If retry and read flags are set, return WANT_READ */
  202. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_READ) &&
  203. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  204. return WOLFSSL_CBIO_ERR_WANT_READ;
  205. }
  206. WOLFSSL_MSG("BIO general error");
  207. return WOLFSSL_CBIO_ERR_GENERAL;
  208. }
  209. (void)ctx;
  210. return recvd;
  211. }
  212. /* Use the WOLFSSL write BIO for sending data. This is set by the function
  213. * wolfSSL_set_bio and can also be set by wolfSSL_CTX_SetIOSend.
  214. *
  215. * ssl WOLFSSL struct passed in that has this function set as the send callback.
  216. * buf buffer with data to write out
  217. * sz size of buf buffer
  218. * ctx a user set context
  219. *
  220. * returns the amount of data sent or want send. See WOLFSSL_CBIO_ERR_* values.
  221. */
  222. int BioSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  223. {
  224. int sent = WOLFSSL_CBIO_ERR_GENERAL;
  225. WOLFSSL_ENTER("BioSend");
  226. if (ssl->biowr == NULL) {
  227. WOLFSSL_MSG("WOLFSSL biowr not set");
  228. return WOLFSSL_CBIO_ERR_GENERAL;
  229. }
  230. sent = wolfSSL_BIO_write(ssl->biowr, buf, sz);
  231. if (sent <= 0) {
  232. if (ssl->biowr->type == WOLFSSL_BIO_SOCKET) {
  233. #ifdef USE_WOLFSSL_IO
  234. sent = TranslateIoError(sent);
  235. #endif
  236. return sent;
  237. }
  238. else if (ssl->biowr->type == WOLFSSL_BIO_BIO) {
  239. if (sent == WOLFSSL_BIO_ERROR) {
  240. WOLFSSL_MSG("\tWould Block");
  241. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  242. }
  243. }
  244. /* If retry and write flags are set, return WANT_WRITE */
  245. if ((ssl->biord->flags & WOLFSSL_BIO_FLAG_WRITE) &&
  246. (ssl->biord->flags & WOLFSSL_BIO_FLAG_RETRY)) {
  247. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  248. }
  249. return WOLFSSL_CBIO_ERR_GENERAL;
  250. }
  251. (void)ctx;
  252. return sent;
  253. }
  254. #endif /* !NO_BIO */
  255. #endif /* OPENSSL_EXTRA */
  256. #ifdef USE_WOLFSSL_IO
  257. /* The receive embedded callback
  258. * return : nb bytes read, or error
  259. */
  260. int EmbedReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  261. {
  262. int recvd;
  263. #ifndef WOLFSSL_LINUXKM
  264. int sd = *(int*)ctx;
  265. #else
  266. struct socket *sd = (struct socket*)ctx;
  267. #endif
  268. recvd = wolfIO_Recv(sd, buf, sz, ssl->rflags);
  269. if (recvd < 0) {
  270. WOLFSSL_MSG("Embed Receive error");
  271. return TranslateIoError(recvd);
  272. }
  273. else if (recvd == 0) {
  274. WOLFSSL_MSG("Embed receive connection closed");
  275. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  276. }
  277. return recvd;
  278. }
  279. /* The send embedded callback
  280. * return : nb bytes sent, or error
  281. */
  282. int EmbedSend(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  283. {
  284. int sent;
  285. #ifndef WOLFSSL_LINUXKM
  286. int sd = *(int*)ctx;
  287. #else
  288. struct socket *sd = (struct socket*)ctx;
  289. #endif
  290. #ifdef WOLFSSL_MAX_SEND_SZ
  291. if (sz > WOLFSSL_MAX_SEND_SZ)
  292. sz = WOLFSSL_MAX_SEND_SZ;
  293. #endif
  294. sent = wolfIO_Send(sd, buf, sz, ssl->wflags);
  295. if (sent < 0) {
  296. WOLFSSL_MSG("Embed Send error");
  297. return TranslateIoError(sent);
  298. }
  299. return sent;
  300. }
  301. #ifdef WOLFSSL_DTLS
  302. #include <wolfssl/wolfcrypt/sha.h>
  303. #ifndef DTLS_SENDTO_FUNCTION
  304. #define DTLS_SENDTO_FUNCTION sendto
  305. #endif
  306. #ifndef DTLS_RECVFROM_FUNCTION
  307. #define DTLS_RECVFROM_FUNCTION recvfrom
  308. #endif
  309. static int sockAddrEqual(
  310. SOCKADDR_S *a, XSOCKLENT aLen, SOCKADDR_S *b, XSOCKLENT bLen)
  311. {
  312. if (aLen != bLen)
  313. return 0;
  314. if (a->ss_family != b->ss_family)
  315. return 0;
  316. if (a->ss_family == WOLFSSL_IP4) {
  317. if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN))
  318. return 0;
  319. if (((SOCKADDR_IN*)a)->sin_port != ((SOCKADDR_IN*)b)->sin_port)
  320. return 0;
  321. if (((SOCKADDR_IN*)a)->sin_addr.s_addr !=
  322. ((SOCKADDR_IN*)b)->sin_addr.s_addr)
  323. return 0;
  324. return 1;
  325. }
  326. #ifdef WOLFSSL_IPV6
  327. if (a->ss_family == WOLFSSL_IP6) {
  328. SOCKADDR_IN6 *a6, *b6;
  329. if (aLen < (XSOCKLENT)sizeof(SOCKADDR_IN6))
  330. return 0;
  331. a6 = (SOCKADDR_IN6*)a;
  332. b6 = (SOCKADDR_IN6*)b;
  333. if (((SOCKADDR_IN6*)a)->sin6_port != ((SOCKADDR_IN6*)b)->sin6_port)
  334. return 0;
  335. if (XMEMCMP((void*)&a6->sin6_addr, (void*)&b6->sin6_addr,
  336. sizeof(a6->sin6_addr)) != 0)
  337. return 0;
  338. return 1;
  339. }
  340. #endif /* WOLFSSL_IPV6 */
  341. return 0;
  342. }
  343. #ifndef WOLFSSL_IPV6
  344. static int PeerIsIpv6(const SOCKADDR_S *peer, XSOCKLENT len)
  345. {
  346. if (len < (XSOCKLENT)sizeof(peer->ss_family))
  347. return 0;
  348. return peer->ss_family == WOLFSSL_IP6;
  349. }
  350. #endif /* !WOLFSSL_IPV6 */
  351. static int isDGramSock(int sfd)
  352. {
  353. int type = 0;
  354. /* optvalue 'type' is of size int */
  355. XSOCKLENT length = (XSOCKLENT)sizeof(type);
  356. if (getsockopt(sfd, SOL_SOCKET, SO_TYPE, (XSOCKOPT_TYPE_OPTVAL_TYPE)&type,
  357. &length) == 0 && type != SOCK_DGRAM) {
  358. return 0;
  359. }
  360. else {
  361. return 1;
  362. }
  363. }
  364. /* The receive embedded callback
  365. * return : nb bytes read, or error
  366. */
  367. int EmbedReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  368. {
  369. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  370. int recvd;
  371. int sd = dtlsCtx->rfd;
  372. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  373. byte doDtlsTimeout;
  374. SOCKADDR_S lclPeer;
  375. SOCKADDR_S* peer;
  376. XSOCKLENT peerSz = 0;
  377. #ifndef NO_ASN_TIME
  378. word32 start = 0;
  379. #elif !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER)
  380. word32 invalidPeerPackets = 0;
  381. #endif
  382. WOLFSSL_ENTER("EmbedReceiveFrom");
  383. if (dtlsCtx->connected) {
  384. peer = NULL;
  385. }
  386. else if (dtlsCtx->userSet) {
  387. #ifndef WOLFSSL_IPV6
  388. if (PeerIsIpv6((SOCKADDR_S*)dtlsCtx->peer.sa, dtlsCtx->peer.sz)) {
  389. WOLFSSL_MSG("ipv6 dtls peer set but no ipv6 support compiled");
  390. return NOT_COMPILED_IN;
  391. }
  392. #endif
  393. peer = &lclPeer;
  394. XMEMSET(&lclPeer, 0, sizeof(lclPeer));
  395. peerSz = sizeof(lclPeer);
  396. }
  397. else {
  398. /* Store the peer address. It is used to calculate the DTLS cookie. */
  399. if (dtlsCtx->peer.sa == NULL) {
  400. dtlsCtx->peer.sa = (void*)XMALLOC(sizeof(SOCKADDR_S),
  401. ssl->heap, DYNAMIC_TYPE_SOCKADDR);
  402. dtlsCtx->peer.sz = 0;
  403. if (dtlsCtx->peer.sa != NULL)
  404. dtlsCtx->peer.bufSz = sizeof(SOCKADDR_S);
  405. else
  406. dtlsCtx->peer.bufSz = 0;
  407. }
  408. peer = (SOCKADDR_S*)dtlsCtx->peer.sa;
  409. peerSz = dtlsCtx->peer.bufSz;
  410. }
  411. /* Don't use ssl->options.handShakeDone since it is true even if
  412. * we are in the process of renegotiation */
  413. doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
  414. #ifdef WOLFSSL_DTLS13
  415. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  416. doDtlsTimeout =
  417. doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
  418. (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
  419. }
  420. #endif /* WOLFSSL_DTLS13 */
  421. do {
  422. if (!doDtlsTimeout) {
  423. dtls_timeout = 0;
  424. }
  425. else {
  426. #ifndef NO_ASN_TIME
  427. if (start == 0) {
  428. start = LowResTimer();
  429. }
  430. else {
  431. dtls_timeout -= LowResTimer() - start;
  432. start = LowResTimer();
  433. if (dtls_timeout < 0 || dtls_timeout > DTLS_TIMEOUT_MAX)
  434. return WOLFSSL_CBIO_ERR_TIMEOUT;
  435. }
  436. #endif
  437. }
  438. if (!wolfSSL_get_using_nonblock(ssl)) {
  439. #ifdef USE_WINDOWS_API
  440. DWORD timeout = dtls_timeout * 1000;
  441. #ifdef WOLFSSL_DTLS13
  442. if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
  443. IsAtLeastTLSv1_3(ssl->version))
  444. timeout /= 4;
  445. #endif /* WOLFSSL_DTLS13 */
  446. #else
  447. struct timeval timeout;
  448. XMEMSET(&timeout, 0, sizeof(timeout));
  449. #ifdef WOLFSSL_DTLS13
  450. if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
  451. IsAtLeastTLSv1_3(ssl->version)) {
  452. if (dtls_timeout >= 4)
  453. timeout.tv_sec = dtls_timeout / 4;
  454. else
  455. timeout.tv_usec = dtls_timeout * 1000000 / 4;
  456. }
  457. else
  458. #endif /* WOLFSSL_DTLS13 */
  459. timeout.tv_sec = dtls_timeout;
  460. #endif
  461. if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
  462. sizeof(timeout)) != 0) {
  463. WOLFSSL_MSG("setsockopt rcvtimeo failed");
  464. }
  465. }
  466. #ifndef NO_ASN_TIME
  467. else if (IsSCR(ssl)) {
  468. if (ssl->dtls_start_timeout &&
  469. LowResTimer() - ssl->dtls_start_timeout >
  470. (word32)dtls_timeout) {
  471. ssl->dtls_start_timeout = 0;
  472. return WOLFSSL_CBIO_ERR_TIMEOUT;
  473. }
  474. else if (!ssl->dtls_start_timeout) {
  475. ssl->dtls_start_timeout = LowResTimer();
  476. }
  477. }
  478. #endif /* !NO_ASN_TIME */
  479. recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags,
  480. (SOCKADDR*)peer, peer != NULL ? &peerSz : NULL);
  481. /* From the RECV(2) man page
  482. * The returned address is truncated if the buffer provided is too
  483. * small; in this case, addrlen will return a value greater than was
  484. * supplied to the call.
  485. */
  486. if (dtlsCtx->connected) {
  487. /* No need to sanitize the value of peerSz */
  488. }
  489. else if (dtlsCtx->userSet) {
  490. /* Truncate peer size */
  491. if (peerSz > (XSOCKLENT)sizeof(lclPeer))
  492. peerSz = (XSOCKLENT)sizeof(lclPeer);
  493. }
  494. else {
  495. /* Truncate peer size */
  496. if (peerSz > (XSOCKLENT)dtlsCtx->peer.bufSz)
  497. peerSz = (XSOCKLENT)dtlsCtx->peer.bufSz;
  498. }
  499. recvd = TranslateReturnCode(recvd, sd);
  500. if (recvd < 0) {
  501. WOLFSSL_MSG("Embed Receive From error");
  502. recvd = TranslateIoError(recvd);
  503. if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
  504. !wolfSSL_dtls_get_using_nonblock(ssl)) {
  505. recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
  506. }
  507. return recvd;
  508. }
  509. else if (recvd == 0) {
  510. if (!isDGramSock(sd)) {
  511. /* Closed TCP connection */
  512. recvd = WOLFSSL_CBIO_ERR_CONN_CLOSE;
  513. }
  514. else {
  515. WOLFSSL_MSG("Ignoring 0-length datagram");
  516. continue;
  517. }
  518. return recvd;
  519. }
  520. else if (dtlsCtx->connected) {
  521. /* Nothing to do */
  522. }
  523. else if (dtlsCtx->userSet) {
  524. /* Check we received the packet from the correct peer */
  525. if (dtlsCtx->peer.sz > 0 &&
  526. (peerSz != (XSOCKLENT)dtlsCtx->peer.sz ||
  527. !sockAddrEqual(peer, peerSz, (SOCKADDR_S*)dtlsCtx->peer.sa,
  528. dtlsCtx->peer.sz))) {
  529. WOLFSSL_MSG(" Ignored packet from invalid peer");
  530. #if defined(NO_ASN_TIME) && \
  531. !defined(DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER)
  532. if (doDtlsTimeout) {
  533. invalidPeerPackets++;
  534. if (invalidPeerPackets > DTLS_RECEIVEFROM_MAX_INVALID_PEER)
  535. return wolfSSL_dtls_get_using_nonblock(ssl)
  536. ? WOLFSSL_CBIO_ERR_WANT_READ
  537. : WOLFSSL_CBIO_ERR_TIMEOUT;
  538. }
  539. #endif /* NO_ASN_TIME && !DTLS_RECEIVEFROM_NO_TIMEOUT_ON_INVALID_PEER */
  540. continue;
  541. }
  542. }
  543. else {
  544. /* Store size of saved address */
  545. dtlsCtx->peer.sz = peerSz;
  546. }
  547. #ifndef NO_ASN_TIME
  548. ssl->dtls_start_timeout = 0;
  549. #endif /* !NO_ASN_TIME */
  550. break;
  551. } while (1);
  552. return recvd;
  553. }
  554. /* The send embedded callback
  555. * return : nb bytes sent, or error
  556. */
  557. int EmbedSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  558. {
  559. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  560. int sd = dtlsCtx->wfd;
  561. int sent;
  562. const SOCKADDR_S* peer = NULL;
  563. XSOCKLENT peerSz = 0;
  564. WOLFSSL_ENTER("EmbedSendTo");
  565. if (!isDGramSock(sd)) {
  566. /* Probably a TCP socket. peer and peerSz MUST be NULL and 0 */
  567. }
  568. else if (!dtlsCtx->connected) {
  569. peer = (const SOCKADDR_S*)dtlsCtx->peer.sa;
  570. peerSz = dtlsCtx->peer.sz;
  571. #ifndef WOLFSSL_IPV6
  572. if (PeerIsIpv6(peer, peerSz)) {
  573. WOLFSSL_MSG("ipv6 dtls peer set but no ipv6 support compiled");
  574. return NOT_COMPILED_IN;
  575. }
  576. #endif
  577. }
  578. sent = (int)DTLS_SENDTO_FUNCTION(sd, buf, sz, ssl->wflags,
  579. (const SOCKADDR*)peer, peerSz);
  580. sent = TranslateReturnCode(sent, sd);
  581. if (sent < 0) {
  582. WOLFSSL_MSG("Embed Send To error");
  583. return TranslateIoError(sent);
  584. }
  585. return sent;
  586. }
  587. #ifdef WOLFSSL_MULTICAST
  588. /* The alternate receive embedded callback for Multicast
  589. * return : nb bytes read, or error
  590. */
  591. int EmbedReceiveFromMcast(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  592. {
  593. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  594. int recvd;
  595. int sd = dtlsCtx->rfd;
  596. WOLFSSL_ENTER("EmbedReceiveFromMcast");
  597. recvd = (int)DTLS_RECVFROM_FUNCTION(sd, buf, sz, ssl->rflags, NULL, NULL);
  598. recvd = TranslateReturnCode(recvd, sd);
  599. if (recvd < 0) {
  600. WOLFSSL_MSG("Embed Receive From error");
  601. recvd = TranslateIoError(recvd);
  602. if (recvd == WOLFSSL_CBIO_ERR_WANT_READ &&
  603. !wolfSSL_dtls_get_using_nonblock(ssl)) {
  604. recvd = WOLFSSL_CBIO_ERR_TIMEOUT;
  605. }
  606. return recvd;
  607. }
  608. return recvd;
  609. }
  610. #endif /* WOLFSSL_MULTICAST */
  611. /* The DTLS Generate Cookie callback
  612. * return : number of bytes copied into buf, or error
  613. */
  614. int EmbedGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
  615. {
  616. int sd = ssl->wfd;
  617. SOCKADDR_S peer;
  618. XSOCKLENT peerSz = sizeof(peer);
  619. byte digest[WC_SHA256_DIGEST_SIZE];
  620. int ret = 0;
  621. (void)ctx;
  622. XMEMSET(&peer, 0, sizeof(peer));
  623. if (getpeername(sd, (SOCKADDR*)&peer, &peerSz) != 0) {
  624. WOLFSSL_MSG("getpeername failed in EmbedGenerateCookie");
  625. return GEN_COOKIE_E;
  626. }
  627. ret = wc_Sha256Hash((byte*)&peer, peerSz, digest);
  628. if (ret != 0)
  629. return ret;
  630. if (sz > WC_SHA256_DIGEST_SIZE)
  631. sz = WC_SHA256_DIGEST_SIZE;
  632. XMEMCPY(buf, digest, sz);
  633. return sz;
  634. }
  635. #endif /* WOLFSSL_DTLS */
  636. #ifdef WOLFSSL_SESSION_EXPORT
  637. #ifdef WOLFSSL_DTLS
  638. static int EmbedGetPeerDTLS(WOLFSSL* ssl, char* ip, int* ipSz,
  639. unsigned short* port, int* fam)
  640. {
  641. SOCKADDR_S peer;
  642. word32 peerSz;
  643. int ret;
  644. /* get peer information stored in ssl struct */
  645. peerSz = sizeof(SOCKADDR_S);
  646. if ((ret = wolfSSL_dtls_get_peer(ssl, (void*)&peer, &peerSz))
  647. != WOLFSSL_SUCCESS) {
  648. return ret;
  649. }
  650. /* extract family, ip, and port */
  651. *fam = ((SOCKADDR_S*)&peer)->ss_family;
  652. switch (*fam) {
  653. case WOLFSSL_IP4:
  654. if (XINET_NTOP(*fam, &(((SOCKADDR_IN*)&peer)->sin_addr),
  655. ip, *ipSz) == NULL) {
  656. WOLFSSL_MSG("XINET_NTOP error");
  657. return SOCKET_ERROR_E;
  658. }
  659. *port = XNTOHS(((SOCKADDR_IN*)&peer)->sin_port);
  660. break;
  661. case WOLFSSL_IP6:
  662. #ifdef WOLFSSL_IPV6
  663. if (XINET_NTOP(*fam, &(((SOCKADDR_IN6*)&peer)->sin6_addr),
  664. ip, *ipSz) == NULL) {
  665. WOLFSSL_MSG("XINET_NTOP error");
  666. return SOCKET_ERROR_E;
  667. }
  668. *port = XNTOHS(((SOCKADDR_IN6*)&peer)->sin6_port);
  669. #endif /* WOLFSSL_IPV6 */
  670. break;
  671. default:
  672. WOLFSSL_MSG("Unknown family type");
  673. return SOCKET_ERROR_E;
  674. }
  675. ip[*ipSz - 1] = '\0'; /* make sure has terminator */
  676. *ipSz = (word16)XSTRLEN(ip);
  677. return WOLFSSL_SUCCESS;
  678. }
  679. static int EmbedSetPeerDTLS(WOLFSSL* ssl, char* ip, int ipSz,
  680. unsigned short port, int fam)
  681. {
  682. int ret;
  683. SOCKADDR_S addr;
  684. /* sanity checks on arguments */
  685. if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
  686. return BAD_FUNC_ARG;
  687. }
  688. addr.ss_family = fam;
  689. switch (addr.ss_family) {
  690. case WOLFSSL_IP4:
  691. if (XINET_PTON(addr.ss_family, ip,
  692. &(((SOCKADDR_IN*)&addr)->sin_addr)) <= 0) {
  693. WOLFSSL_MSG("XINET_PTON error");
  694. return SOCKET_ERROR_E;
  695. }
  696. ((SOCKADDR_IN*)&addr)->sin_port = XHTONS(port);
  697. /* peer sa is free'd in SSL_ResourceFree */
  698. if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN*)&addr,
  699. sizeof(SOCKADDR_IN)))!= WOLFSSL_SUCCESS) {
  700. WOLFSSL_MSG("Import DTLS peer info error");
  701. return ret;
  702. }
  703. break;
  704. case WOLFSSL_IP6:
  705. #ifdef WOLFSSL_IPV6
  706. if (XINET_PTON(addr.ss_family, ip,
  707. &(((SOCKADDR_IN6*)&addr)->sin6_addr)) <= 0) {
  708. WOLFSSL_MSG("XINET_PTON error");
  709. return SOCKET_ERROR_E;
  710. }
  711. ((SOCKADDR_IN6*)&addr)->sin6_port = XHTONS(port);
  712. /* peer sa is free'd in SSL_ResourceFree */
  713. if ((ret = wolfSSL_dtls_set_peer(ssl, (SOCKADDR_IN6*)&addr,
  714. sizeof(SOCKADDR_IN6)))!= WOLFSSL_SUCCESS) {
  715. WOLFSSL_MSG("Import DTLS peer info error");
  716. return ret;
  717. }
  718. #endif /* WOLFSSL_IPV6 */
  719. break;
  720. default:
  721. WOLFSSL_MSG("Unknown address family");
  722. return BUFFER_E;
  723. }
  724. return WOLFSSL_SUCCESS;
  725. }
  726. #endif
  727. /* get the peer information in human readable form (ip, port, family)
  728. * default function assumes BSD sockets
  729. * can be overridden with wolfSSL_CTX_SetIOGetPeer
  730. */
  731. int EmbedGetPeer(WOLFSSL* ssl, char* ip, int* ipSz,
  732. unsigned short* port, int* fam)
  733. {
  734. if (ssl == NULL || ip == NULL || ipSz == NULL ||
  735. port == NULL || fam == NULL) {
  736. return BAD_FUNC_ARG;
  737. }
  738. if (ssl->options.dtls) {
  739. #ifdef WOLFSSL_DTLS
  740. return EmbedGetPeerDTLS(ssl, ip, ipSz, port, fam);
  741. #else
  742. return NOT_COMPILED_IN;
  743. #endif
  744. }
  745. else {
  746. *port = wolfSSL_get_fd(ssl);
  747. ip[0] = '\0';
  748. *ipSz = 0;
  749. *fam = 0;
  750. return WOLFSSL_SUCCESS;
  751. }
  752. }
  753. /* set the peer information in human readable form (ip, port, family)
  754. * default function assumes BSD sockets
  755. * can be overridden with wolfSSL_CTX_SetIOSetPeer
  756. */
  757. int EmbedSetPeer(WOLFSSL* ssl, char* ip, int ipSz,
  758. unsigned short port, int fam)
  759. {
  760. /* sanity checks on arguments */
  761. if (ssl == NULL || ip == NULL || ipSz < 0 || ipSz > MAX_EXPORT_IP) {
  762. return BAD_FUNC_ARG;
  763. }
  764. if (ssl->options.dtls) {
  765. #ifdef WOLFSSL_DTLS
  766. return EmbedSetPeerDTLS(ssl, ip, ipSz, port, fam);
  767. #else
  768. return NOT_COMPILED_IN;
  769. #endif
  770. }
  771. else {
  772. wolfSSL_set_fd(ssl, port);
  773. (void)fam;
  774. return WOLFSSL_SUCCESS;
  775. }
  776. }
  777. #endif /* WOLFSSL_SESSION_EXPORT */
  778. #ifdef WOLFSSL_LINUXKM
  779. static int linuxkm_send(struct socket *socket, void *buf, int size,
  780. unsigned int flags)
  781. {
  782. int ret;
  783. struct kvec vec = { .iov_base = buf, .iov_len = size };
  784. struct msghdr msg = { .msg_flags = flags };
  785. ret = kernel_sendmsg(socket, &msg, &vec, 1, size);
  786. return ret;
  787. }
  788. static int linuxkm_recv(struct socket *socket, void *buf, int size,
  789. unsigned int flags)
  790. {
  791. int ret;
  792. struct kvec vec = { .iov_base = buf, .iov_len = size };
  793. struct msghdr msg = { .msg_flags = flags };
  794. ret = kernel_recvmsg(socket, &msg, &vec, 1, size, msg.msg_flags);
  795. return ret;
  796. }
  797. #endif /* WOLFSSL_LINUXKM */
  798. int wolfIO_Recv(SOCKET_T sd, char *buf, int sz, int rdFlags)
  799. {
  800. int recvd;
  801. recvd = (int)RECV_FUNCTION(sd, buf, sz, rdFlags);
  802. recvd = TranslateReturnCode(recvd, (int)sd);
  803. return recvd;
  804. }
  805. int wolfIO_Send(SOCKET_T sd, char *buf, int sz, int wrFlags)
  806. {
  807. int sent;
  808. sent = (int)SEND_FUNCTION(sd, buf, sz, wrFlags);
  809. sent = TranslateReturnCode(sent, (int)sd);
  810. return sent;
  811. }
  812. #endif /* USE_WOLFSSL_IO */
  813. #ifdef HAVE_HTTP_CLIENT
  814. #ifndef HAVE_IO_TIMEOUT
  815. #define io_timeout_sec 0
  816. #else
  817. #ifndef DEFAULT_TIMEOUT_SEC
  818. #define DEFAULT_TIMEOUT_SEC 0 /* no timeout */
  819. #endif
  820. static int io_timeout_sec = DEFAULT_TIMEOUT_SEC;
  821. void wolfIO_SetTimeout(int to_sec)
  822. {
  823. io_timeout_sec = to_sec;
  824. }
  825. int wolfIO_SetBlockingMode(SOCKET_T sockfd, int non_blocking)
  826. {
  827. int ret = 0;
  828. #ifdef USE_WINDOWS_API
  829. unsigned long blocking = non_blocking;
  830. ret = ioctlsocket(sockfd, FIONBIO, &blocking);
  831. if (ret == SOCKET_ERROR)
  832. ret = -1;
  833. #else
  834. ret = fcntl(sockfd, F_GETFL, 0);
  835. if (ret >= 0) {
  836. if (non_blocking)
  837. ret |= O_NONBLOCK;
  838. else
  839. ret &= ~O_NONBLOCK;
  840. ret = fcntl(sockfd, F_SETFL, ret);
  841. }
  842. #endif
  843. if (ret < 0) {
  844. WOLFSSL_MSG("wolfIO_SetBlockingMode failed");
  845. }
  846. return ret;
  847. }
  848. int wolfIO_Select(SOCKET_T sockfd, int to_sec)
  849. {
  850. fd_set rfds, wfds;
  851. int nfds = 0;
  852. struct timeval timeout = { (to_sec > 0) ? to_sec : 0, 0};
  853. int ret;
  854. #ifndef USE_WINDOWS_API
  855. nfds = (int)sockfd + 1;
  856. if ((sockfd < 0) || (sockfd >= FD_SETSIZE)) {
  857. WOLFSSL_MSG("socket fd out of FDSET range");
  858. return -1;
  859. }
  860. #endif
  861. FD_ZERO(&rfds);
  862. FD_SET(sockfd, &rfds);
  863. wfds = rfds;
  864. ret = select(nfds, &rfds, &wfds, NULL, &timeout);
  865. if (ret == 0) {
  866. #ifdef DEBUG_HTTP
  867. fprintf(stderr, "Timeout: %d\n", ret);
  868. #endif
  869. return HTTP_TIMEOUT;
  870. }
  871. else if (ret > 0) {
  872. if (FD_ISSET(sockfd, &wfds)) {
  873. if (!FD_ISSET(sockfd, &rfds)) {
  874. return 0;
  875. }
  876. }
  877. }
  878. WOLFSSL_MSG("Select error");
  879. return SOCKET_ERROR_E;
  880. }
  881. #endif /* HAVE_IO_TIMEOUT */
  882. static int wolfIO_Word16ToString(char* d, word16 number)
  883. {
  884. int i = 0;
  885. word16 order = 10000;
  886. word16 digit;
  887. if (d == NULL)
  888. return i;
  889. if (number == 0)
  890. d[i++] = '0';
  891. else {
  892. while (order) {
  893. digit = number / order;
  894. if (i > 0 || digit != 0)
  895. d[i++] = (char)digit + '0';
  896. if (digit != 0)
  897. number %= digit * order;
  898. order = (order > 1) ? order / 10 : 0;
  899. }
  900. }
  901. d[i] = 0; /* null terminate */
  902. return i;
  903. }
  904. int wolfIO_TcpConnect(SOCKET_T* sockfd, const char* ip, word16 port, int to_sec)
  905. {
  906. #ifdef HAVE_SOCKADDR
  907. int ret = 0;
  908. SOCKADDR_S addr;
  909. int sockaddr_len;
  910. #if defined(HAVE_GETADDRINFO)
  911. /* use getaddrinfo */
  912. ADDRINFO hints;
  913. ADDRINFO* answer = NULL;
  914. char strPort[6];
  915. #else
  916. /* use gethostbyname */
  917. #if !defined(WOLFSSL_USE_POPEN_HOST)
  918. #if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
  919. !defined(SINGLE_THREADED)
  920. HOSTENT entry_buf, *entry = NULL;
  921. char *ghbn_r_buf = NULL;
  922. int ghbn_r_errno;
  923. #else
  924. HOSTENT *entry;
  925. #endif
  926. #endif
  927. #ifdef WOLFSSL_IPV6
  928. SOCKADDR_IN6 *sin;
  929. #else
  930. SOCKADDR_IN *sin;
  931. #endif
  932. #endif /* HAVE_SOCKADDR */
  933. if (sockfd == NULL || ip == NULL) {
  934. return -1;
  935. }
  936. #if !defined(HAVE_GETADDRINFO)
  937. #ifdef WOLFSSL_IPV6
  938. sockaddr_len = sizeof(SOCKADDR_IN6);
  939. #else
  940. sockaddr_len = sizeof(SOCKADDR_IN);
  941. #endif
  942. #endif
  943. XMEMSET(&addr, 0, sizeof(addr));
  944. #ifdef WOLFIO_DEBUG
  945. printf("TCP Connect: %s:%d\n", ip, port);
  946. #endif
  947. /* use gethostbyname for c99 */
  948. #if defined(HAVE_GETADDRINFO)
  949. XMEMSET(&hints, 0, sizeof(hints));
  950. #ifdef WOLFSSL_IPV6
  951. hints.ai_family = AF_UNSPEC; /* detect IPv4 or IPv6 */
  952. #else
  953. hints.ai_family = AF_INET; /* detect only IPv4 */
  954. #endif
  955. hints.ai_socktype = SOCK_STREAM;
  956. hints.ai_protocol = IPPROTO_TCP;
  957. if (wolfIO_Word16ToString(strPort, port) == 0) {
  958. WOLFSSL_MSG("invalid port number for responder");
  959. return -1;
  960. }
  961. if (getaddrinfo(ip, strPort, &hints, &answer) < 0 || answer == NULL) {
  962. WOLFSSL_MSG("no addr info for responder");
  963. return -1;
  964. }
  965. sockaddr_len = answer->ai_addrlen;
  966. XMEMCPY(&addr, answer->ai_addr, sockaddr_len);
  967. freeaddrinfo(answer);
  968. #elif defined(WOLFSSL_USE_POPEN_HOST) && !defined(WOLFSSL_IPV6)
  969. {
  970. char host_ipaddr[4] = { 127, 0, 0, 1 };
  971. int found = 1;
  972. if ((XSTRNCMP(ip, "localhost", 10) != 0) &&
  973. (XSTRNCMP(ip, "127.0.0.1", 10) != 0)) {
  974. FILE* fp;
  975. char host_out[100];
  976. char cmd[100];
  977. XSTRNCPY(cmd, "host ", 6);
  978. XSTRNCAT(cmd, ip, 99 - XSTRLEN(cmd));
  979. found = 0;
  980. fp = popen(cmd, "r");
  981. if (fp != NULL) {
  982. while (fgets(host_out, sizeof(host_out), fp) != NULL) {
  983. int i;
  984. int j = 0;
  985. for (j = 0; host_out[j] != '\0'; j++) {
  986. if ((host_out[j] >= '0') && (host_out[j] <= '9')) {
  987. break;
  988. }
  989. }
  990. found = (host_out[j] >= '0') && (host_out[j] <= '9');
  991. if (!found) {
  992. continue;
  993. }
  994. for (i = 0; i < 4; i++) {
  995. host_ipaddr[i] = atoi(host_out + j);
  996. while ((host_out[j] >= '0') && (host_out[j] <= '9')) {
  997. j++;
  998. }
  999. if (host_out[j] == '.') {
  1000. j++;
  1001. found &= (i != 3);
  1002. }
  1003. else {
  1004. found &= (i == 3);
  1005. break;
  1006. }
  1007. }
  1008. if (found) {
  1009. break;
  1010. }
  1011. }
  1012. pclose(fp);
  1013. }
  1014. }
  1015. if (found) {
  1016. sin = (SOCKADDR_IN *)&addr;
  1017. sin->sin_family = AF_INET;
  1018. sin->sin_port = XHTONS(port);
  1019. XMEMCPY(&sin->sin_addr.s_addr, host_ipaddr, sizeof(host_ipaddr));
  1020. }
  1021. else {
  1022. WOLFSSL_MSG("no addr info for responder");
  1023. return -1;
  1024. }
  1025. }
  1026. #else
  1027. #if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
  1028. !defined(SINGLE_THREADED)
  1029. /* 2048 is a magic number that empirically works. the header and
  1030. * documentation provide no guidance on appropriate buffer size other than
  1031. * "if buf is too small, the functions will return ERANGE, and the call
  1032. * should be retried with a larger buffer."
  1033. */
  1034. ghbn_r_buf = (char *)XMALLOC(2048, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1035. if (ghbn_r_buf != NULL) {
  1036. gethostbyname_r(ip, &entry_buf, ghbn_r_buf, 2048, &entry, &ghbn_r_errno);
  1037. }
  1038. #else
  1039. entry = gethostbyname(ip);
  1040. #endif
  1041. if (entry) {
  1042. #ifdef WOLFSSL_IPV6
  1043. sin = (SOCKADDR_IN6 *)&addr;
  1044. sin->sin6_family = AF_INET6;
  1045. sin->sin6_port = XHTONS(port);
  1046. XMEMCPY(&sin->sin6_addr, entry->h_addr_list[0], entry->h_length);
  1047. #else
  1048. sin = (SOCKADDR_IN *)&addr;
  1049. sin->sin_family = AF_INET;
  1050. sin->sin_port = XHTONS(port);
  1051. XMEMCPY(&sin->sin_addr.s_addr, entry->h_addr_list[0], entry->h_length);
  1052. #endif
  1053. }
  1054. #if defined(__GLIBC__) && (__GLIBC__ >= 2) && defined(__USE_MISC) && \
  1055. !defined(SINGLE_THREADED)
  1056. XFREE(ghbn_r_buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1057. #endif
  1058. if (entry == NULL) {
  1059. WOLFSSL_MSG("no addr info for responder");
  1060. return -1;
  1061. }
  1062. #endif
  1063. *sockfd = (SOCKET_T)socket(addr.ss_family, SOCK_STREAM, 0);
  1064. #ifdef USE_WINDOWS_API
  1065. if (*sockfd == SOCKET_INVALID)
  1066. #else
  1067. if (*sockfd <= SOCKET_INVALID)
  1068. #endif
  1069. {
  1070. WOLFSSL_MSG("bad socket fd, out of fds?");
  1071. *sockfd = SOCKET_INVALID;
  1072. return -1;
  1073. }
  1074. #ifdef HAVE_IO_TIMEOUT
  1075. /* if timeout value provided then set socket non-blocking */
  1076. if (to_sec > 0) {
  1077. wolfIO_SetBlockingMode(*sockfd, 1);
  1078. }
  1079. #else
  1080. (void)to_sec;
  1081. #endif
  1082. ret = connect(*sockfd, (SOCKADDR *)&addr, sockaddr_len);
  1083. #ifdef HAVE_IO_TIMEOUT
  1084. if ((ret != 0) && (to_sec > 0)) {
  1085. #ifdef USE_WINDOWS_API
  1086. if ((ret == SOCKET_ERROR) && (wolfSSL_LastError(ret) == WSAEWOULDBLOCK))
  1087. #else
  1088. if (errno == EINPROGRESS)
  1089. #endif
  1090. {
  1091. /* wait for connect to complete */
  1092. ret = wolfIO_Select(*sockfd, to_sec);
  1093. /* restore blocking mode */
  1094. wolfIO_SetBlockingMode(*sockfd, 0);
  1095. }
  1096. }
  1097. #endif
  1098. if (ret != 0) {
  1099. WOLFSSL_MSG("Responder tcp connect failed");
  1100. CloseSocket(*sockfd);
  1101. *sockfd = SOCKET_INVALID;
  1102. return -1;
  1103. }
  1104. return ret;
  1105. #else
  1106. (void)sockfd;
  1107. (void)ip;
  1108. (void)port;
  1109. (void)to_sec;
  1110. return -1;
  1111. #endif /* HAVE_SOCKADDR */
  1112. }
  1113. int wolfIO_TcpBind(SOCKET_T* sockfd, word16 port)
  1114. {
  1115. #ifdef HAVE_SOCKADDR
  1116. int ret = 0;
  1117. SOCKADDR_S addr;
  1118. int sockaddr_len = sizeof(SOCKADDR_IN);
  1119. SOCKADDR_IN *sin = (SOCKADDR_IN *)&addr;
  1120. if (sockfd == NULL || port < 1) {
  1121. return -1;
  1122. }
  1123. XMEMSET(&addr, 0, sizeof(addr));
  1124. sin->sin_family = AF_INET;
  1125. sin->sin_addr.s_addr = INADDR_ANY;
  1126. sin->sin_port = XHTONS(port);
  1127. *sockfd = (SOCKET_T)socket(AF_INET, SOCK_STREAM, 0);
  1128. #ifdef USE_WINDOWS_API
  1129. if (*sockfd == SOCKET_INVALID)
  1130. #else
  1131. if (*sockfd <= SOCKET_INVALID)
  1132. #endif
  1133. {
  1134. WOLFSSL_MSG("socket failed");
  1135. *sockfd = SOCKET_INVALID;
  1136. return -1;
  1137. }
  1138. #if !defined(USE_WINDOWS_API) && !defined(WOLFSSL_MDK_ARM)\
  1139. && !defined(WOLFSSL_KEIL_TCP_NET) && !defined(WOLFSSL_ZEPHYR)
  1140. {
  1141. int optval = 1;
  1142. XSOCKLENT optlen = sizeof(optval);
  1143. ret = setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, optlen);
  1144. }
  1145. #endif
  1146. if (ret == 0)
  1147. ret = bind(*sockfd, (SOCKADDR *)sin, sockaddr_len);
  1148. if (ret == 0)
  1149. ret = listen(*sockfd, SOMAXCONN);
  1150. if (ret != 0) {
  1151. WOLFSSL_MSG("wolfIO_TcpBind failed");
  1152. CloseSocket(*sockfd);
  1153. *sockfd = SOCKET_INVALID;
  1154. ret = -1;
  1155. }
  1156. return ret;
  1157. #else
  1158. (void)sockfd;
  1159. (void)port;
  1160. return -1;
  1161. #endif /* HAVE_SOCKADDR */
  1162. }
  1163. #ifdef HAVE_SOCKADDR
  1164. int wolfIO_TcpAccept(SOCKET_T sockfd, SOCKADDR* peer_addr, XSOCKLENT* peer_len)
  1165. {
  1166. return (int)accept(sockfd, peer_addr, peer_len);
  1167. }
  1168. #endif /* HAVE_SOCKADDR */
  1169. #ifndef HTTP_SCRATCH_BUFFER_SIZE
  1170. #define HTTP_SCRATCH_BUFFER_SIZE 512
  1171. #endif
  1172. #ifndef MAX_URL_ITEM_SIZE
  1173. #define MAX_URL_ITEM_SIZE 80
  1174. #endif
  1175. int wolfIO_DecodeUrl(const char* url, int urlSz, char* outName, char* outPath,
  1176. word16* outPort)
  1177. {
  1178. int result = -1;
  1179. if (url == NULL || urlSz == 0) {
  1180. if (outName)
  1181. *outName = 0;
  1182. if (outPath)
  1183. *outPath = 0;
  1184. if (outPort)
  1185. *outPort = 0;
  1186. }
  1187. else {
  1188. int i, cur;
  1189. /* need to break the url down into scheme, address, and port */
  1190. /* "http://example.com:8080/" */
  1191. /* "http://[::1]:443/" */
  1192. if (XSTRNCMP(url, "http://", 7) == 0) {
  1193. cur = 7;
  1194. } else cur = 0;
  1195. i = 0;
  1196. if (url[cur] == '[') {
  1197. cur++;
  1198. /* copy until ']' */
  1199. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
  1200. url[cur] != ']') {
  1201. if (outName)
  1202. outName[i] = url[cur];
  1203. i++; cur++;
  1204. }
  1205. cur++; /* skip ']' */
  1206. }
  1207. else {
  1208. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0 &&
  1209. url[cur] != ':' && url[cur] != '/') {
  1210. if (outName)
  1211. outName[i] = url[cur];
  1212. i++; cur++;
  1213. }
  1214. }
  1215. if (outName)
  1216. outName[i] = 0;
  1217. /* Need to pick out the path after the domain name */
  1218. if (cur < urlSz && url[cur] == ':') {
  1219. char port[6];
  1220. int j;
  1221. word32 bigPort = 0;
  1222. i = 0;
  1223. cur++;
  1224. while (i < 6 && cur < urlSz && url[cur] != 0 && url[cur] != '/') {
  1225. port[i] = url[cur];
  1226. i++; cur++;
  1227. }
  1228. for (j = 0; j < i; j++) {
  1229. if (port[j] < '0' || port[j] > '9') return -1;
  1230. bigPort = (bigPort * 10) + (port[j] - '0');
  1231. }
  1232. if (outPort)
  1233. *outPort = (word16)bigPort;
  1234. }
  1235. else if (outPort)
  1236. *outPort = 80;
  1237. if (cur < urlSz && url[cur] == '/') {
  1238. i = 0;
  1239. while (i < MAX_URL_ITEM_SIZE-1 && cur < urlSz && url[cur] != 0) {
  1240. if (outPath)
  1241. outPath[i] = url[cur];
  1242. i++; cur++;
  1243. }
  1244. if (outPath)
  1245. outPath[i] = 0;
  1246. }
  1247. else if (outPath) {
  1248. outPath[0] = '/';
  1249. outPath[1] = 0;
  1250. }
  1251. result = 0;
  1252. }
  1253. return result;
  1254. }
  1255. static int wolfIO_HttpProcessResponseBuf(int sfd, byte **recvBuf,
  1256. int* recvBufSz, int chunkSz, char* start, int len, int dynType, void* heap)
  1257. {
  1258. byte* newRecvBuf = NULL;
  1259. int newRecvSz = *recvBufSz + chunkSz;
  1260. int pos = 0;
  1261. WOLFSSL_MSG("Processing HTTP response");
  1262. #ifdef WOLFIO_DEBUG
  1263. printf("HTTP Chunk %d->%d\n", *recvBufSz, chunkSz);
  1264. #endif
  1265. (void)heap;
  1266. (void)dynType;
  1267. if (chunkSz < 0 || len < 0) {
  1268. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf invalid chunk or length size");
  1269. return MEMORY_E;
  1270. }
  1271. if (newRecvSz <= 0) {
  1272. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf new receive size overflow");
  1273. return MEMORY_E;
  1274. }
  1275. newRecvBuf = (byte*)XMALLOC(newRecvSz, heap, dynType);
  1276. if (newRecvBuf == NULL) {
  1277. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf malloc failed");
  1278. return MEMORY_E;
  1279. }
  1280. /* if buffer already exists, then we are growing it */
  1281. if (*recvBuf) {
  1282. XMEMCPY(&newRecvBuf[pos], *recvBuf, *recvBufSz);
  1283. XFREE(*recvBuf, heap, dynType);
  1284. pos += *recvBufSz;
  1285. *recvBuf = NULL;
  1286. }
  1287. /* copy the remainder of the httpBuf into the respBuf */
  1288. if (len != 0) {
  1289. if (pos + len <= newRecvSz) {
  1290. XMEMCPY(&newRecvBuf[pos], start, len);
  1291. pos += len;
  1292. }
  1293. else {
  1294. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf bad size");
  1295. XFREE(newRecvBuf, heap, dynType);
  1296. return -1;
  1297. }
  1298. }
  1299. /* receive the remainder of chunk */
  1300. while (len < chunkSz) {
  1301. int rxSz = wolfIO_Recv(sfd, (char*)&newRecvBuf[pos], chunkSz-len, 0);
  1302. if (rxSz > 0) {
  1303. len += rxSz;
  1304. pos += rxSz;
  1305. }
  1306. else {
  1307. WOLFSSL_MSG("wolfIO_HttpProcessResponseBuf recv failed");
  1308. XFREE(newRecvBuf, heap, dynType);
  1309. return -1;
  1310. }
  1311. }
  1312. *recvBuf = newRecvBuf;
  1313. *recvBufSz = newRecvSz;
  1314. return 0;
  1315. }
  1316. int wolfIO_HttpProcessResponse(int sfd, const char** appStrList,
  1317. byte** respBuf, byte* httpBuf, int httpBufSz, int dynType, void* heap)
  1318. {
  1319. static const char HTTP_PROTO[] = "HTTP/1.";
  1320. static const char HTTP_STATUS_200[] = "200";
  1321. int result = 0;
  1322. int len = 0;
  1323. char *start, *end;
  1324. int respBufSz = 0;
  1325. int isChunked = 0, chunkSz = 0;
  1326. enum phr_state { phr_init, phr_http_start, phr_have_length, phr_have_type,
  1327. phr_wait_end, phr_get_chunk_len, phr_get_chunk_data,
  1328. phr_http_end
  1329. } state = phr_init;
  1330. WOLFSSL_ENTER("wolfIO_HttpProcessResponse");
  1331. *respBuf = NULL;
  1332. start = end = NULL;
  1333. do {
  1334. if (state == phr_get_chunk_data) {
  1335. /* get chunk of data */
  1336. result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz,
  1337. chunkSz, start, len, dynType, heap);
  1338. state = (result != 0) ? phr_http_end : phr_get_chunk_len;
  1339. end = NULL;
  1340. len = 0;
  1341. }
  1342. /* read data if no \r\n or first time */
  1343. if ((start == NULL) || (end == NULL)) {
  1344. result = wolfIO_Recv(sfd, (char*)httpBuf+len, httpBufSz-len-1, 0);
  1345. if (result > 0) {
  1346. len += result;
  1347. start = (char*)httpBuf;
  1348. start[len] = 0;
  1349. }
  1350. else {
  1351. result = TranslateReturnCode(result, sfd);
  1352. result = wolfSSL_LastError(result);
  1353. if (result == SOCKET_EWOULDBLOCK || result == SOCKET_EAGAIN) {
  1354. return OCSP_WANT_READ;
  1355. }
  1356. WOLFSSL_MSG("wolfIO_HttpProcessResponse recv http from peer failed");
  1357. return HTTP_RECV_ERR;
  1358. }
  1359. }
  1360. end = XSTRSTR(start, "\r\n"); /* locate end */
  1361. /* handle incomplete rx */
  1362. if (end == NULL) {
  1363. if (len != 0)
  1364. XMEMMOVE(httpBuf, start, len);
  1365. start = end = NULL;
  1366. }
  1367. /* when start is "\r\n" */
  1368. else if (end == start) {
  1369. /* if waiting for end or need chunk len */
  1370. if (state == phr_wait_end || state == phr_get_chunk_len) {
  1371. state = (isChunked) ? phr_get_chunk_len : phr_http_end;
  1372. len -= 2; start += 2; /* skip \r\n */
  1373. }
  1374. else {
  1375. WOLFSSL_MSG("wolfIO_HttpProcessResponse header ended early");
  1376. return HTTP_HEADER_ERR;
  1377. }
  1378. }
  1379. else {
  1380. *end = 0; /* null terminate */
  1381. len -= (int)(end - start) + 2;
  1382. /* adjust len to remove the first line including the /r/n */
  1383. #ifdef WOLFIO_DEBUG
  1384. printf("HTTP Resp: %s\n", start);
  1385. #endif
  1386. switch (state) {
  1387. case phr_init:
  1388. /* length of "HTTP/1.x 200" == 12*/
  1389. if (XSTRLEN(start) < 12) {
  1390. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1391. "too short.");
  1392. return HTTP_HEADER_ERR;
  1393. }
  1394. if (XSTRNCASECMP(start, HTTP_PROTO,
  1395. sizeof(HTTP_PROTO) - 1) != 0) {
  1396. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1397. "doesn't start with HTTP/1.");
  1398. return HTTP_PROTO_ERR;
  1399. }
  1400. /* +2 for HTTP minor version and space between version and
  1401. * status code. */
  1402. start += sizeof(HTTP_PROTO) - 1 + 2 ;
  1403. if (XSTRNCASECMP(start, HTTP_STATUS_200,
  1404. sizeof(HTTP_STATUS_200) - 1) != 0) {
  1405. WOLFSSL_MSG("wolfIO_HttpProcessResponse HTTP header "
  1406. "doesn't have status code 200.");
  1407. return HTTP_STATUS_ERR;
  1408. }
  1409. state = phr_http_start;
  1410. break;
  1411. case phr_http_start:
  1412. case phr_have_length:
  1413. case phr_have_type:
  1414. if (XSTRNCASECMP(start, "Content-Type:", 13) == 0) {
  1415. int i;
  1416. start += 13;
  1417. while (*start == ' ') start++;
  1418. /* try and match against appStrList */
  1419. i = 0;
  1420. while (appStrList[i] != NULL) {
  1421. if (XSTRNCASECMP(start, appStrList[i],
  1422. XSTRLEN(appStrList[i])) == 0) {
  1423. break;
  1424. }
  1425. i++;
  1426. }
  1427. if (appStrList[i] == NULL) {
  1428. WOLFSSL_MSG("wolfIO_HttpProcessResponse appstr mismatch");
  1429. return HTTP_APPSTR_ERR;
  1430. }
  1431. state = (state == phr_http_start) ? phr_have_type : phr_wait_end;
  1432. }
  1433. else if (XSTRNCASECMP(start, "Content-Length:", 15) == 0) {
  1434. start += 15;
  1435. while (*start == ' ') start++;
  1436. chunkSz = XATOI(start);
  1437. state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
  1438. }
  1439. else if (XSTRNCASECMP(start, "Transfer-Encoding:", 18) == 0) {
  1440. start += 18;
  1441. while (*start == ' ') start++;
  1442. if (XSTRNCASECMP(start, "chunked", 7) == 0) {
  1443. isChunked = 1;
  1444. state = (state == phr_http_start) ? phr_have_length : phr_wait_end;
  1445. }
  1446. }
  1447. break;
  1448. case phr_get_chunk_len:
  1449. chunkSz = (int)strtol(start, NULL, 16); /* hex format */
  1450. state = (chunkSz == 0) ? phr_http_end : phr_get_chunk_data;
  1451. break;
  1452. case phr_get_chunk_data:
  1453. /* processing for chunk data done above, since \r\n isn't required */
  1454. case phr_wait_end:
  1455. case phr_http_end:
  1456. /* do nothing */
  1457. break;
  1458. } /* switch (state) */
  1459. /* skip to end plus \r\n */
  1460. start = end + 2;
  1461. }
  1462. } while (state != phr_http_end);
  1463. if (!isChunked) {
  1464. result = wolfIO_HttpProcessResponseBuf(sfd, respBuf, &respBufSz, chunkSz,
  1465. start, len, dynType, heap);
  1466. }
  1467. if (result >= 0) {
  1468. result = respBufSz;
  1469. }
  1470. else {
  1471. WOLFSSL_ERROR(result);
  1472. }
  1473. return result;
  1474. }
  1475. int wolfIO_HttpBuildRequest(const char *reqType, const char *domainName,
  1476. const char *path, int pathLen, int reqSz, const char *contentType,
  1477. byte *buf, int bufSize)
  1478. {
  1479. return wolfIO_HttpBuildRequest_ex(reqType, domainName, path, pathLen, reqSz, contentType, "", buf, bufSize);
  1480. }
  1481. int wolfIO_HttpBuildRequest_ex(const char *reqType, const char *domainName,
  1482. const char *path, int pathLen, int reqSz, const char *contentType,
  1483. const char *exHdrs, byte *buf, int bufSize)
  1484. {
  1485. word32 reqTypeLen, domainNameLen, reqSzStrLen, contentTypeLen, exHdrsLen, maxLen;
  1486. char reqSzStr[6];
  1487. char* req = (char*)buf;
  1488. const char* blankStr = " ";
  1489. const char* http11Str = " HTTP/1.1";
  1490. const char* hostStr = "\r\nHost: ";
  1491. const char* contentLenStr = "\r\nContent-Length: ";
  1492. const char* contentTypeStr = "\r\nContent-Type: ";
  1493. const char* singleCrLfStr = "\r\n";
  1494. const char* doubleCrLfStr = "\r\n\r\n";
  1495. word32 blankStrLen, http11StrLen, hostStrLen, contentLenStrLen,
  1496. contentTypeStrLen, singleCrLfStrLen, doubleCrLfStrLen;
  1497. reqTypeLen = (word32)XSTRLEN(reqType);
  1498. domainNameLen = (word32)XSTRLEN(domainName);
  1499. reqSzStrLen = wolfIO_Word16ToString(reqSzStr, (word16)reqSz);
  1500. contentTypeLen = (word32)XSTRLEN(contentType);
  1501. blankStrLen = (word32)XSTRLEN(blankStr);
  1502. http11StrLen = (word32)XSTRLEN(http11Str);
  1503. hostStrLen = (word32)XSTRLEN(hostStr);
  1504. contentLenStrLen = (word32)XSTRLEN(contentLenStr);
  1505. contentTypeStrLen = (word32)XSTRLEN(contentTypeStr);
  1506. if(exHdrs){
  1507. singleCrLfStrLen = (word32)XSTRLEN(singleCrLfStr);
  1508. exHdrsLen = (word32)XSTRLEN(exHdrs);
  1509. } else {
  1510. singleCrLfStrLen = 0;
  1511. exHdrsLen = 0;
  1512. }
  1513. doubleCrLfStrLen = (word32)XSTRLEN(doubleCrLfStr);
  1514. /* determine max length and check it */
  1515. maxLen =
  1516. reqTypeLen +
  1517. blankStrLen +
  1518. pathLen +
  1519. http11StrLen +
  1520. hostStrLen +
  1521. domainNameLen +
  1522. contentLenStrLen +
  1523. reqSzStrLen +
  1524. contentTypeStrLen +
  1525. contentTypeLen +
  1526. singleCrLfStrLen +
  1527. exHdrsLen +
  1528. doubleCrLfStrLen +
  1529. 1 /* null term */;
  1530. if (maxLen > (word32)bufSize)
  1531. return 0;
  1532. XSTRNCPY((char*)buf, reqType, bufSize);
  1533. buf += reqTypeLen; bufSize -= reqTypeLen;
  1534. XSTRNCPY((char*)buf, blankStr, bufSize);
  1535. buf += blankStrLen; bufSize -= blankStrLen;
  1536. XSTRNCPY((char*)buf, path, bufSize);
  1537. buf += pathLen; bufSize -= pathLen;
  1538. XSTRNCPY((char*)buf, http11Str, bufSize);
  1539. buf += http11StrLen; bufSize -= http11StrLen;
  1540. if (domainNameLen > 0) {
  1541. XSTRNCPY((char*)buf, hostStr, bufSize);
  1542. buf += hostStrLen; bufSize -= hostStrLen;
  1543. XSTRNCPY((char*)buf, domainName, bufSize);
  1544. buf += domainNameLen; bufSize -= domainNameLen;
  1545. }
  1546. if (reqSz > 0 && reqSzStrLen > 0) {
  1547. XSTRNCPY((char*)buf, contentLenStr, bufSize);
  1548. buf += contentLenStrLen; bufSize -= contentLenStrLen;
  1549. XSTRNCPY((char*)buf, reqSzStr, bufSize);
  1550. buf += reqSzStrLen; bufSize -= reqSzStrLen;
  1551. }
  1552. if (contentTypeLen > 0) {
  1553. XSTRNCPY((char*)buf, contentTypeStr, bufSize);
  1554. buf += contentTypeStrLen; bufSize -= contentTypeStrLen;
  1555. XSTRNCPY((char*)buf, contentType, bufSize);
  1556. buf += contentTypeLen; bufSize -= contentTypeLen;
  1557. }
  1558. if (exHdrsLen > 0)
  1559. {
  1560. XSTRNCPY((char *)buf, singleCrLfStr, bufSize);
  1561. buf += singleCrLfStrLen;
  1562. bufSize -= singleCrLfStrLen;
  1563. XSTRNCPY((char *)buf, exHdrs, bufSize);
  1564. buf += exHdrsLen;
  1565. bufSize -= exHdrsLen;
  1566. }
  1567. XSTRNCPY((char*)buf, doubleCrLfStr, bufSize);
  1568. buf += doubleCrLfStrLen;
  1569. #ifdef WOLFIO_DEBUG
  1570. printf("HTTP %s: %s", reqType, req);
  1571. #endif
  1572. /* calculate actual length based on original and new pointer */
  1573. return (int)((char*)buf - req);
  1574. }
  1575. #ifdef HAVE_OCSP
  1576. int wolfIO_HttpBuildRequestOcsp(const char* domainName, const char* path,
  1577. int ocspReqSz, byte* buf, int bufSize)
  1578. {
  1579. const char *cacheCtl = "Cache-Control: no-cache";
  1580. return wolfIO_HttpBuildRequest_ex("POST", domainName, path, (int)XSTRLEN(path),
  1581. ocspReqSz, "application/ocsp-request", cacheCtl, buf, bufSize);
  1582. }
  1583. /* return: >0 OCSP Response Size
  1584. * -1 error */
  1585. int wolfIO_HttpProcessResponseOcsp(int sfd, byte** respBuf,
  1586. byte* httpBuf, int httpBufSz, void* heap)
  1587. {
  1588. const char* appStrList[] = {
  1589. "application/ocsp-response",
  1590. NULL
  1591. };
  1592. return wolfIO_HttpProcessResponse(sfd, appStrList,
  1593. respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_OCSP, heap);
  1594. }
  1595. /* in default wolfSSL callback ctx is the heap pointer */
  1596. int EmbedOcspLookup(void* ctx, const char* url, int urlSz,
  1597. byte* ocspReqBuf, int ocspReqSz, byte** ocspRespBuf)
  1598. {
  1599. SOCKET_T sfd = SOCKET_INVALID;
  1600. word16 port;
  1601. int ret = -1;
  1602. #ifdef WOLFSSL_SMALL_STACK
  1603. char* path;
  1604. char* domainName;
  1605. #else
  1606. char path[MAX_URL_ITEM_SIZE];
  1607. char domainName[MAX_URL_ITEM_SIZE];
  1608. #endif
  1609. #ifdef WOLFSSL_SMALL_STACK
  1610. path = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1611. if (path == NULL)
  1612. return MEMORY_E;
  1613. domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, NULL,
  1614. DYNAMIC_TYPE_TMP_BUFFER);
  1615. if (domainName == NULL) {
  1616. XFREE(path, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1617. return MEMORY_E;
  1618. }
  1619. #endif
  1620. if (ocspReqBuf == NULL || ocspReqSz == 0) {
  1621. WOLFSSL_MSG("OCSP request is required for lookup");
  1622. }
  1623. else if (ocspRespBuf == NULL) {
  1624. WOLFSSL_MSG("Cannot save OCSP response");
  1625. }
  1626. else if (wolfIO_DecodeUrl(url, urlSz, domainName, path, &port) < 0) {
  1627. WOLFSSL_MSG("Unable to decode OCSP URL");
  1628. }
  1629. else {
  1630. /* Note, the library uses the EmbedOcspRespFree() callback to
  1631. * free this buffer. */
  1632. int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
  1633. byte* httpBuf = (byte*)XMALLOC(httpBufSz, ctx, DYNAMIC_TYPE_OCSP);
  1634. if (httpBuf == NULL) {
  1635. WOLFSSL_MSG("Unable to create OCSP response buffer");
  1636. }
  1637. else {
  1638. httpBufSz = wolfIO_HttpBuildRequestOcsp(domainName, path, ocspReqSz,
  1639. httpBuf, httpBufSz);
  1640. ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
  1641. if (ret != 0) {
  1642. WOLFSSL_MSG("OCSP Responder connection failed");
  1643. }
  1644. else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0) !=
  1645. httpBufSz) {
  1646. WOLFSSL_MSG("OCSP http request failed");
  1647. }
  1648. else if (wolfIO_Send(sfd, (char*)ocspReqBuf, ocspReqSz, 0) !=
  1649. ocspReqSz) {
  1650. WOLFSSL_MSG("OCSP ocsp request failed");
  1651. }
  1652. else {
  1653. ret = wolfIO_HttpProcessResponseOcsp((int)sfd, ocspRespBuf, httpBuf,
  1654. HTTP_SCRATCH_BUFFER_SIZE, ctx);
  1655. }
  1656. if (sfd != SOCKET_INVALID)
  1657. CloseSocket(sfd);
  1658. XFREE(httpBuf, ctx, DYNAMIC_TYPE_OCSP);
  1659. }
  1660. }
  1661. #ifdef WOLFSSL_SMALL_STACK
  1662. XFREE(path, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1663. XFREE(domainName, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1664. #endif
  1665. return ret;
  1666. }
  1667. /* in default callback ctx is heap hint */
  1668. void EmbedOcspRespFree(void* ctx, byte *resp)
  1669. {
  1670. if (resp)
  1671. XFREE(resp, ctx, DYNAMIC_TYPE_OCSP);
  1672. (void)ctx;
  1673. }
  1674. #endif /* HAVE_OCSP */
  1675. #if defined(HAVE_CRL) && defined(HAVE_CRL_IO)
  1676. int wolfIO_HttpBuildRequestCrl(const char* url, int urlSz,
  1677. const char* domainName, byte* buf, int bufSize)
  1678. {
  1679. const char *cacheCtl = "Cache-Control: no-cache";
  1680. return wolfIO_HttpBuildRequest_ex("GET", domainName, url, urlSz, 0, "",
  1681. cacheCtl, buf, bufSize);
  1682. }
  1683. int wolfIO_HttpProcessResponseCrl(WOLFSSL_CRL* crl, int sfd, byte* httpBuf,
  1684. int httpBufSz)
  1685. {
  1686. int ret;
  1687. byte *respBuf = NULL;
  1688. const char* appStrList[] = {
  1689. "application/pkix-crl",
  1690. "application/x-pkcs7-crl",
  1691. NULL
  1692. };
  1693. ret = wolfIO_HttpProcessResponse(sfd, appStrList,
  1694. &respBuf, httpBuf, httpBufSz, DYNAMIC_TYPE_CRL, crl->heap);
  1695. if (ret >= 0) {
  1696. ret = BufferLoadCRL(crl, respBuf, ret, WOLFSSL_FILETYPE_ASN1, 0);
  1697. }
  1698. XFREE(respBuf, crl->heap, DYNAMIC_TYPE_CRL);
  1699. return ret;
  1700. }
  1701. int EmbedCrlLookup(WOLFSSL_CRL* crl, const char* url, int urlSz)
  1702. {
  1703. SOCKET_T sfd = SOCKET_INVALID;
  1704. word16 port;
  1705. int ret = -1;
  1706. #ifdef WOLFSSL_SMALL_STACK
  1707. char* domainName;
  1708. #else
  1709. char domainName[MAX_URL_ITEM_SIZE];
  1710. #endif
  1711. #ifdef WOLFSSL_SMALL_STACK
  1712. domainName = (char*)XMALLOC(MAX_URL_ITEM_SIZE, crl->heap,
  1713. DYNAMIC_TYPE_TMP_BUFFER);
  1714. if (domainName == NULL) {
  1715. return MEMORY_E;
  1716. }
  1717. #endif
  1718. if (wolfIO_DecodeUrl(url, urlSz, domainName, NULL, &port) < 0) {
  1719. WOLFSSL_MSG("Unable to decode CRL URL");
  1720. }
  1721. else {
  1722. int httpBufSz = HTTP_SCRATCH_BUFFER_SIZE;
  1723. byte* httpBuf = (byte*)XMALLOC(httpBufSz, crl->heap,
  1724. DYNAMIC_TYPE_CRL);
  1725. if (httpBuf == NULL) {
  1726. WOLFSSL_MSG("Unable to create CRL response buffer");
  1727. }
  1728. else {
  1729. httpBufSz = wolfIO_HttpBuildRequestCrl(url, urlSz, domainName,
  1730. httpBuf, httpBufSz);
  1731. ret = wolfIO_TcpConnect(&sfd, domainName, port, io_timeout_sec);
  1732. if (ret != 0) {
  1733. WOLFSSL_MSG("CRL connection failed");
  1734. }
  1735. else if (wolfIO_Send(sfd, (char*)httpBuf, httpBufSz, 0)
  1736. != httpBufSz) {
  1737. WOLFSSL_MSG("CRL http get failed");
  1738. }
  1739. else {
  1740. ret = wolfIO_HttpProcessResponseCrl(crl, sfd, httpBuf,
  1741. HTTP_SCRATCH_BUFFER_SIZE);
  1742. }
  1743. if (sfd != SOCKET_INVALID)
  1744. CloseSocket(sfd);
  1745. XFREE(httpBuf, crl->heap, DYNAMIC_TYPE_CRL);
  1746. }
  1747. }
  1748. #ifdef WOLFSSL_SMALL_STACK
  1749. XFREE(domainName, crl->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1750. #endif
  1751. return ret;
  1752. }
  1753. #endif /* HAVE_CRL && HAVE_CRL_IO */
  1754. #endif /* HAVE_HTTP_CLIENT */
  1755. void wolfSSL_CTX_SetIORecv(WOLFSSL_CTX *ctx, CallbackIORecv CBIORecv)
  1756. {
  1757. if (ctx) {
  1758. ctx->CBIORecv = CBIORecv;
  1759. #ifdef OPENSSL_EXTRA
  1760. ctx->cbioFlag |= WOLFSSL_CBIO_RECV;
  1761. #endif
  1762. }
  1763. }
  1764. void wolfSSL_CTX_SetIOSend(WOLFSSL_CTX *ctx, CallbackIOSend CBIOSend)
  1765. {
  1766. if (ctx) {
  1767. ctx->CBIOSend = CBIOSend;
  1768. #ifdef OPENSSL_EXTRA
  1769. ctx->cbioFlag |= WOLFSSL_CBIO_SEND;
  1770. #endif
  1771. }
  1772. }
  1773. /* sets the IO callback to use for receives at WOLFSSL level */
  1774. void wolfSSL_SSLSetIORecv(WOLFSSL *ssl, CallbackIORecv CBIORecv)
  1775. {
  1776. if (ssl) {
  1777. ssl->CBIORecv = CBIORecv;
  1778. #ifdef OPENSSL_EXTRA
  1779. ssl->cbioFlag |= WOLFSSL_CBIO_RECV;
  1780. #endif
  1781. }
  1782. }
  1783. /* sets the IO callback to use for sends at WOLFSSL level */
  1784. void wolfSSL_SSLSetIOSend(WOLFSSL *ssl, CallbackIOSend CBIOSend)
  1785. {
  1786. if (ssl) {
  1787. ssl->CBIOSend = CBIOSend;
  1788. #ifdef OPENSSL_EXTRA
  1789. ssl->cbioFlag |= WOLFSSL_CBIO_SEND;
  1790. #endif
  1791. }
  1792. }
  1793. void wolfSSL_SetIOReadCtx(WOLFSSL* ssl, void *rctx)
  1794. {
  1795. if (ssl)
  1796. ssl->IOCB_ReadCtx = rctx;
  1797. }
  1798. void wolfSSL_SetIOWriteCtx(WOLFSSL* ssl, void *wctx)
  1799. {
  1800. if (ssl)
  1801. ssl->IOCB_WriteCtx = wctx;
  1802. }
  1803. void* wolfSSL_GetIOReadCtx(WOLFSSL* ssl)
  1804. {
  1805. if (ssl)
  1806. return ssl->IOCB_ReadCtx;
  1807. return NULL;
  1808. }
  1809. void* wolfSSL_GetIOWriteCtx(WOLFSSL* ssl)
  1810. {
  1811. if (ssl)
  1812. return ssl->IOCB_WriteCtx;
  1813. return NULL;
  1814. }
  1815. void wolfSSL_SetIOReadFlags(WOLFSSL* ssl, int flags)
  1816. {
  1817. if (ssl)
  1818. ssl->rflags = flags;
  1819. }
  1820. void wolfSSL_SetIOWriteFlags(WOLFSSL* ssl, int flags)
  1821. {
  1822. if (ssl)
  1823. ssl->wflags = flags;
  1824. }
  1825. #ifdef WOLFSSL_DTLS
  1826. void wolfSSL_CTX_SetGenCookie(WOLFSSL_CTX* ctx, CallbackGenCookie cb)
  1827. {
  1828. if (ctx)
  1829. ctx->CBIOCookie = cb;
  1830. }
  1831. void wolfSSL_SetCookieCtx(WOLFSSL* ssl, void *ctx)
  1832. {
  1833. if (ssl)
  1834. ssl->IOCB_CookieCtx = ctx;
  1835. }
  1836. void* wolfSSL_GetCookieCtx(WOLFSSL* ssl)
  1837. {
  1838. if (ssl)
  1839. return ssl->IOCB_CookieCtx;
  1840. return NULL;
  1841. }
  1842. #endif /* WOLFSSL_DTLS */
  1843. #ifdef WOLFSSL_SESSION_EXPORT
  1844. void wolfSSL_CTX_SetIOGetPeer(WOLFSSL_CTX* ctx, CallbackGetPeer cb)
  1845. {
  1846. if (ctx)
  1847. ctx->CBGetPeer = cb;
  1848. }
  1849. void wolfSSL_CTX_SetIOSetPeer(WOLFSSL_CTX* ctx, CallbackSetPeer cb)
  1850. {
  1851. if (ctx)
  1852. ctx->CBSetPeer = cb;
  1853. }
  1854. #endif /* WOLFSSL_SESSION_EXPORT */
  1855. #ifdef HAVE_NETX
  1856. /* The NetX receive callback
  1857. * return : bytes read, or error
  1858. */
  1859. int NetX_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1860. {
  1861. NetX_Ctx* nxCtx = (NetX_Ctx*)ctx;
  1862. ULONG left;
  1863. ULONG total;
  1864. ULONG copied = 0;
  1865. UINT status;
  1866. (void)ssl;
  1867. if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
  1868. WOLFSSL_MSG("NetX Recv NULL parameters");
  1869. return WOLFSSL_CBIO_ERR_GENERAL;
  1870. }
  1871. if (nxCtx->nxPacket == NULL) {
  1872. status = nx_tcp_socket_receive(nxCtx->nxSocket, &nxCtx->nxPacket,
  1873. nxCtx->nxWait);
  1874. if (status != NX_SUCCESS) {
  1875. WOLFSSL_MSG("NetX Recv receive error");
  1876. return WOLFSSL_CBIO_ERR_GENERAL;
  1877. }
  1878. }
  1879. if (nxCtx->nxPacket) {
  1880. status = nx_packet_length_get(nxCtx->nxPacket, &total);
  1881. if (status != NX_SUCCESS) {
  1882. WOLFSSL_MSG("NetX Recv length get error");
  1883. return WOLFSSL_CBIO_ERR_GENERAL;
  1884. }
  1885. left = total - nxCtx->nxOffset;
  1886. status = nx_packet_data_extract_offset(nxCtx->nxPacket, nxCtx->nxOffset,
  1887. buf, sz, &copied);
  1888. if (status != NX_SUCCESS) {
  1889. WOLFSSL_MSG("NetX Recv data extract offset error");
  1890. return WOLFSSL_CBIO_ERR_GENERAL;
  1891. }
  1892. nxCtx->nxOffset += copied;
  1893. if (copied == left) {
  1894. WOLFSSL_MSG("NetX Recv Drained packet");
  1895. nx_packet_release(nxCtx->nxPacket);
  1896. nxCtx->nxPacket = NULL;
  1897. nxCtx->nxOffset = 0;
  1898. }
  1899. }
  1900. return copied;
  1901. }
  1902. /* The NetX send callback
  1903. * return : bytes sent, or error
  1904. */
  1905. int NetX_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  1906. {
  1907. NetX_Ctx* nxCtx = (NetX_Ctx*)ctx;
  1908. NX_PACKET* packet;
  1909. NX_PACKET_POOL* pool; /* shorthand */
  1910. UINT status;
  1911. (void)ssl;
  1912. if (nxCtx == NULL || nxCtx->nxSocket == NULL) {
  1913. WOLFSSL_MSG("NetX Send NULL parameters");
  1914. return WOLFSSL_CBIO_ERR_GENERAL;
  1915. }
  1916. pool = nxCtx->nxSocket->nx_tcp_socket_ip_ptr->nx_ip_default_packet_pool;
  1917. status = nx_packet_allocate(pool, &packet, NX_TCP_PACKET,
  1918. nxCtx->nxWait);
  1919. if (status != NX_SUCCESS) {
  1920. WOLFSSL_MSG("NetX Send packet alloc error");
  1921. return WOLFSSL_CBIO_ERR_GENERAL;
  1922. }
  1923. status = nx_packet_data_append(packet, buf, sz, pool, nxCtx->nxWait);
  1924. if (status != NX_SUCCESS) {
  1925. nx_packet_release(packet);
  1926. WOLFSSL_MSG("NetX Send data append error");
  1927. return WOLFSSL_CBIO_ERR_GENERAL;
  1928. }
  1929. status = nx_tcp_socket_send(nxCtx->nxSocket, packet, nxCtx->nxWait);
  1930. if (status != NX_SUCCESS) {
  1931. nx_packet_release(packet);
  1932. WOLFSSL_MSG("NetX Send socket send error");
  1933. return WOLFSSL_CBIO_ERR_GENERAL;
  1934. }
  1935. return sz;
  1936. }
  1937. /* like set_fd, but for default NetX context */
  1938. void wolfSSL_SetIO_NetX(WOLFSSL* ssl, NX_TCP_SOCKET* nxSocket, ULONG waitOption)
  1939. {
  1940. if (ssl) {
  1941. ssl->nxCtx.nxSocket = nxSocket;
  1942. ssl->nxCtx.nxWait = waitOption;
  1943. }
  1944. }
  1945. #endif /* HAVE_NETX */
  1946. #ifdef MICRIUM
  1947. /* Micrium uTCP/IP port, using the NetSock API
  1948. * TCP and UDP are currently supported with the callbacks below.
  1949. *
  1950. * WOLFSSL_SESSION_EXPORT is not yet supported, would need EmbedGetPeer()
  1951. * and EmbedSetPeer() callbacks implemented.
  1952. *
  1953. * HAVE_CRL is not yet supported, would need an EmbedCrlLookup()
  1954. * callback implemented.
  1955. *
  1956. * HAVE_OCSP is not yet supported, would need an EmbedOCSPLookup()
  1957. * callback implemented.
  1958. */
  1959. /* The Micrium uTCP/IP send callback
  1960. * return : bytes sent, or error
  1961. */
  1962. int MicriumSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  1963. {
  1964. NET_SOCK_ID sd = *(int*)ctx;
  1965. NET_SOCK_RTN_CODE ret;
  1966. NET_ERR err;
  1967. ret = NetSock_TxData(sd, buf, sz, ssl->wflags, &err);
  1968. if (ret < 0) {
  1969. WOLFSSL_MSG("Embed Send error");
  1970. if (err == NET_ERR_TX) {
  1971. WOLFSSL_MSG("\tWould block");
  1972. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  1973. } else {
  1974. WOLFSSL_MSG("\tGeneral error");
  1975. return WOLFSSL_CBIO_ERR_GENERAL;
  1976. }
  1977. }
  1978. return ret;
  1979. }
  1980. /* The Micrium uTCP/IP receive callback
  1981. * return : nb bytes read, or error
  1982. */
  1983. int MicriumReceive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  1984. {
  1985. NET_SOCK_ID sd = *(int*)ctx;
  1986. NET_SOCK_RTN_CODE ret;
  1987. NET_ERR err;
  1988. #ifdef WOLFSSL_DTLS
  1989. {
  1990. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  1991. /* Don't use ssl->options.handShakeDone since it is true even if
  1992. * we are in the process of renegotiation */
  1993. byte doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
  1994. #ifdef WOLFSSL_DTLS13
  1995. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  1996. doDtlsTimeout =
  1997. doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
  1998. (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
  1999. }
  2000. #endif /* WOLFSSL_DTLS13 */
  2001. if (!doDtlsTimeout)
  2002. dtls_timeout = 0;
  2003. if (!wolfSSL_dtls_get_using_nonblock(ssl)) {
  2004. /* needs timeout in milliseconds */
  2005. #ifdef WOLFSSL_DTLS13
  2006. if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
  2007. IsAtLeastTLSv1_3(ssl->version)) {
  2008. dtls_timeout = (1000 * dtls_timeout) / 4;
  2009. } else
  2010. #endif /* WOLFSSL_DTLS13 */
  2011. dtls_timeout = 1000 * dtls_timeout;
  2012. NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout, &err);
  2013. if (err != NET_SOCK_ERR_NONE) {
  2014. WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
  2015. }
  2016. }
  2017. }
  2018. #endif
  2019. ret = NetSock_RxData(sd, buf, sz, ssl->rflags, &err);
  2020. if (ret < 0) {
  2021. WOLFSSL_MSG("Embed Receive error");
  2022. if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
  2023. err == NET_ERR_FAULT_LOCK_ACQUIRE) {
  2024. if (!wolfSSL_dtls(ssl) || wolfSSL_dtls_get_using_nonblock(ssl)) {
  2025. WOLFSSL_MSG("\tWould block");
  2026. return WOLFSSL_CBIO_ERR_WANT_READ;
  2027. }
  2028. else {
  2029. WOLFSSL_MSG("\tSocket timeout");
  2030. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2031. }
  2032. } else if (err == NET_SOCK_ERR_CLOSED) {
  2033. WOLFSSL_MSG("Embed receive connection closed");
  2034. return WOLFSSL_CBIO_ERR_CONN_CLOSE;
  2035. } else {
  2036. WOLFSSL_MSG("\tGeneral error");
  2037. return WOLFSSL_CBIO_ERR_GENERAL;
  2038. }
  2039. }
  2040. return ret;
  2041. }
  2042. /* The Micrium uTCP/IP receivefrom callback
  2043. * return : nb bytes read, or error
  2044. */
  2045. int MicriumReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  2046. {
  2047. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  2048. NET_SOCK_ID sd = dtlsCtx->rfd;
  2049. NET_SOCK_ADDR peer;
  2050. NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
  2051. NET_SOCK_RTN_CODE ret;
  2052. NET_ERR err;
  2053. WOLFSSL_ENTER("MicriumReceiveFrom");
  2054. #ifdef WOLFSSL_DTLS
  2055. {
  2056. int dtls_timeout = wolfSSL_dtls_get_current_timeout(ssl);
  2057. /* Don't use ssl->options.handShakeDone since it is true even if
  2058. * we are in the process of renegotiation */
  2059. byte doDtlsTimeout = ssl->options.handShakeState != HANDSHAKE_DONE;
  2060. #ifdef WOLFSSL_DTLS13
  2061. if (ssl->options.dtls && IsAtLeastTLSv1_3(ssl->version)) {
  2062. doDtlsTimeout =
  2063. doDtlsTimeout || ssl->dtls13Rtx.rtxRecords != NULL ||
  2064. (ssl->dtls13FastTimeout && ssl->dtls13Rtx.seenRecords != NULL);
  2065. }
  2066. #endif /* WOLFSSL_DTLS13 */
  2067. if (!doDtlsTimeout)
  2068. dtls_timeout = 0;
  2069. if (!wolfSSL_dtls_get_using_nonblock(ssl)) {
  2070. /* needs timeout in milliseconds */
  2071. #ifdef WOLFSSL_DTLS13
  2072. if (wolfSSL_dtls13_use_quick_timeout(ssl) &&
  2073. IsAtLeastTLSv1_3(ssl->version)) {
  2074. dtls_timeout = (1000 * dtls_timeout) / 4;
  2075. } else
  2076. #endif /* WOLFSSL_DTLS13 */
  2077. dtls_timeout = 1000 * dtls_timeout;
  2078. NetSock_CfgTimeoutRxQ_Set(sd, dtls_timeout, &err);
  2079. if (err != NET_SOCK_ERR_NONE) {
  2080. WOLFSSL_MSG("NetSock_CfgTimeoutRxQ_Set failed");
  2081. }
  2082. }
  2083. }
  2084. #endif /* WOLFSSL_DTLS */
  2085. ret = NetSock_RxDataFrom(sd, buf, sz, ssl->rflags, &peer, &peerSz,
  2086. 0, 0, 0, &err);
  2087. if (ret < 0) {
  2088. WOLFSSL_MSG("Embed Receive From error");
  2089. if (err == NET_ERR_RX || err == NET_SOCK_ERR_RX_Q_EMPTY ||
  2090. err == NET_ERR_FAULT_LOCK_ACQUIRE) {
  2091. if (wolfSSL_dtls_get_using_nonblock(ssl)) {
  2092. WOLFSSL_MSG("\tWould block");
  2093. return WOLFSSL_CBIO_ERR_WANT_READ;
  2094. }
  2095. else {
  2096. WOLFSSL_MSG("\tSocket timeout");
  2097. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2098. }
  2099. } else {
  2100. WOLFSSL_MSG("\tGeneral error");
  2101. return WOLFSSL_CBIO_ERR_GENERAL;
  2102. }
  2103. }
  2104. else {
  2105. if (dtlsCtx->peer.sz > 0
  2106. && peerSz != (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz
  2107. && XMEMCMP(&peer, dtlsCtx->peer.sa, peerSz) != 0) {
  2108. WOLFSSL_MSG("\tIgnored packet from invalid peer");
  2109. return WOLFSSL_CBIO_ERR_WANT_READ;
  2110. }
  2111. }
  2112. return ret;
  2113. }
  2114. /* The Micrium uTCP/IP sendto callback
  2115. * return : nb bytes sent, or error
  2116. */
  2117. int MicriumSendTo(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  2118. {
  2119. WOLFSSL_DTLS_CTX* dtlsCtx = (WOLFSSL_DTLS_CTX*)ctx;
  2120. NET_SOCK_ID sd = dtlsCtx->wfd;
  2121. NET_SOCK_RTN_CODE ret;
  2122. NET_ERR err;
  2123. WOLFSSL_ENTER("MicriumSendTo");
  2124. ret = NetSock_TxDataTo(sd, buf, sz, ssl->wflags,
  2125. (NET_SOCK_ADDR*)dtlsCtx->peer.sa,
  2126. (NET_SOCK_ADDR_LEN)dtlsCtx->peer.sz,
  2127. &err);
  2128. if (err < 0) {
  2129. WOLFSSL_MSG("Embed Send To error");
  2130. if (err == NET_ERR_TX) {
  2131. WOLFSSL_MSG("\tWould block");
  2132. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2133. } else {
  2134. WOLFSSL_MSG("\tGeneral error");
  2135. return WOLFSSL_CBIO_ERR_GENERAL;
  2136. }
  2137. }
  2138. return ret;
  2139. }
  2140. /* Micrium DTLS Generate Cookie callback
  2141. * return : number of bytes copied into buf, or error
  2142. */
  2143. #if defined(NO_SHA) && !defined(NO_SHA256)
  2144. #define MICRIUM_COOKIE_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
  2145. #elif !defined(NO_SHA)
  2146. #define MICRIUM_COOKIE_DIGEST_SIZE WC_SHA_DIGEST_SIZE
  2147. #else
  2148. #error Must enable either SHA-1 or SHA256 (or both) for Micrium.
  2149. #endif
  2150. int MicriumGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *ctx)
  2151. {
  2152. NET_SOCK_ADDR peer;
  2153. NET_SOCK_ADDR_LEN peerSz = sizeof(peer);
  2154. byte digest[MICRIUM_COOKIE_DIGEST_SIZE];
  2155. int ret = 0;
  2156. (void)ctx;
  2157. XMEMSET(&peer, 0, sizeof(peer));
  2158. if (wolfSSL_dtls_get_peer(ssl, (void*)&peer,
  2159. (unsigned int*)&peerSz) != WOLFSSL_SUCCESS) {
  2160. WOLFSSL_MSG("getpeername failed in MicriumGenerateCookie");
  2161. return GEN_COOKIE_E;
  2162. }
  2163. #if defined(NO_SHA) && !defined(NO_SHA256)
  2164. ret = wc_Sha256Hash((byte*)&peer, peerSz, digest);
  2165. #else
  2166. ret = wc_ShaHash((byte*)&peer, peerSz, digest);
  2167. #endif
  2168. if (ret != 0)
  2169. return ret;
  2170. if (sz > MICRIUM_COOKIE_DIGEST_SIZE)
  2171. sz = MICRIUM_COOKIE_DIGEST_SIZE;
  2172. XMEMCPY(buf, digest, sz);
  2173. return sz;
  2174. }
  2175. #endif /* MICRIUM */
  2176. #if defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP)
  2177. #include <os/os_error.h>
  2178. #include <os/os_mbuf.h>
  2179. #include <os/os_mempool.h>
  2180. #define MB_NAME "wolfssl_mb"
  2181. typedef struct Mynewt_Ctx {
  2182. struct mn_socket *mnSocket; /* send/recv socket handler */
  2183. struct mn_sockaddr_in mnSockAddrIn; /* socket address */
  2184. struct os_mbuf *mnPacket; /* incoming packet handle
  2185. for short reads */
  2186. int reading; /* reading flag */
  2187. /* private */
  2188. void *mnMemBuffer; /* memory buffer for mempool */
  2189. struct os_mempool mnMempool; /* mempool */
  2190. struct os_mbuf_pool mnMbufpool; /* mbuf pool */
  2191. } Mynewt_Ctx;
  2192. void mynewt_ctx_clear(void *ctx) {
  2193. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  2194. if(!mynewt_ctx) return;
  2195. if(mynewt_ctx->mnPacket) {
  2196. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  2197. mynewt_ctx->mnPacket = NULL;
  2198. }
  2199. os_mempool_clear(&mynewt_ctx->mnMempool);
  2200. XFREE(mynewt_ctx->mnMemBuffer, 0, 0);
  2201. XFREE(mynewt_ctx, 0, 0);
  2202. }
  2203. /* return Mynewt_Ctx instance */
  2204. void* mynewt_ctx_new() {
  2205. int rc = 0;
  2206. Mynewt_Ctx *mynewt_ctx;
  2207. int mem_buf_count = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_COUNT);
  2208. int mem_buf_size = MYNEWT_VAL(WOLFSSL_MNSOCK_MEM_BUF_SIZE);
  2209. int mempool_bytes = OS_MEMPOOL_BYTES(mem_buf_count, mem_buf_size);
  2210. mynewt_ctx = (Mynewt_Ctx *)XMALLOC(sizeof(struct Mynewt_Ctx),
  2211. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2212. if(!mynewt_ctx) return NULL;
  2213. XMEMSET(mynewt_ctx, 0, sizeof(Mynewt_Ctx));
  2214. mynewt_ctx->mnMemBuffer = (void *)XMALLOC(mempool_bytes, 0, 0);
  2215. if(!mynewt_ctx->mnMemBuffer) {
  2216. mynewt_ctx_clear((void*)mynewt_ctx);
  2217. return NULL;
  2218. }
  2219. rc = os_mempool_init(&mynewt_ctx->mnMempool,
  2220. mem_buf_count, mem_buf_size,
  2221. mynewt_ctx->mnMemBuffer, MB_NAME);
  2222. if(rc != 0) {
  2223. mynewt_ctx_clear((void*)mynewt_ctx);
  2224. return NULL;
  2225. }
  2226. rc = os_mbuf_pool_init(&mynewt_ctx->mnMbufpool, &mynewt_ctx->mnMempool,
  2227. mem_buf_count, mem_buf_size);
  2228. if(rc != 0) {
  2229. mynewt_ctx_clear((void*)mynewt_ctx);
  2230. return NULL;
  2231. }
  2232. return mynewt_ctx;
  2233. }
  2234. static void mynewt_sock_writable(void *arg, int err);
  2235. static void mynewt_sock_readable(void *arg, int err);
  2236. static const union mn_socket_cb mynewt_sock_cbs = {
  2237. .socket.writable = mynewt_sock_writable,
  2238. .socket.readable = mynewt_sock_readable,
  2239. };
  2240. static void mynewt_sock_writable(void *arg, int err)
  2241. {
  2242. /* do nothing */
  2243. }
  2244. static void mynewt_sock_readable(void *arg, int err)
  2245. {
  2246. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)arg;
  2247. if (err && mynewt_ctx->reading) {
  2248. mynewt_ctx->reading = 0;
  2249. }
  2250. }
  2251. /* The Mynewt receive callback
  2252. * return : bytes read, or error
  2253. */
  2254. int Mynewt_Receive(WOLFSSL *ssl, char *buf, int sz, void *ctx)
  2255. {
  2256. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  2257. int rc = 0;
  2258. struct mn_sockaddr_in from;
  2259. struct os_mbuf *m;
  2260. int read_sz = 0;
  2261. word16 total;
  2262. if (mynewt_ctx == NULL || mynewt_ctx->mnSocket == NULL) {
  2263. WOLFSSL_MSG("Mynewt Recv NULL parameters");
  2264. return WOLFSSL_CBIO_ERR_GENERAL;
  2265. }
  2266. if(mynewt_ctx->mnPacket == NULL) {
  2267. mynewt_ctx->mnPacket = os_mbuf_get_pkthdr(&mynewt_ctx->mnMbufpool, 0);
  2268. if(mynewt_ctx->mnPacket == NULL) {
  2269. return MEMORY_E;
  2270. }
  2271. mynewt_ctx->reading = 1;
  2272. while(mynewt_ctx->reading && rc == 0) {
  2273. rc = mn_recvfrom(mynewt_ctx->mnSocket, &m, (struct mn_sockaddr *) &from);
  2274. if(rc == MN_ECONNABORTED) {
  2275. rc = 0;
  2276. mynewt_ctx->reading = 0;
  2277. break;
  2278. }
  2279. if (!(rc == 0 || rc == MN_EAGAIN)) {
  2280. WOLFSSL_MSG("Mynewt Recv receive error");
  2281. mynewt_ctx->reading = 0;
  2282. break;
  2283. }
  2284. if(rc == 0) {
  2285. int len = OS_MBUF_PKTLEN(m);
  2286. if(len == 0) {
  2287. break;
  2288. }
  2289. rc = os_mbuf_appendfrom(mynewt_ctx->mnPacket, m, 0, len);
  2290. if(rc != 0) {
  2291. WOLFSSL_MSG("Mynewt Recv os_mbuf_appendfrom error");
  2292. break;
  2293. }
  2294. os_mbuf_free_chain(m);
  2295. m = NULL;
  2296. } else if(rc == MN_EAGAIN) {
  2297. /* continue to until reading all of packet data. */
  2298. rc = 0;
  2299. break;
  2300. }
  2301. }
  2302. if(rc != 0) {
  2303. mynewt_ctx->reading = 0;
  2304. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  2305. mynewt_ctx->mnPacket = NULL;
  2306. return rc;
  2307. }
  2308. }
  2309. if(mynewt_ctx->mnPacket) {
  2310. total = OS_MBUF_PKTLEN(mynewt_ctx->mnPacket);
  2311. read_sz = (total >= sz)? sz : total;
  2312. os_mbuf_copydata(mynewt_ctx->mnPacket, 0, read_sz, (void*)buf);
  2313. os_mbuf_adj(mynewt_ctx->mnPacket, read_sz);
  2314. if (read_sz == total) {
  2315. WOLFSSL_MSG("Mynewt Recv Drained packet");
  2316. os_mbuf_free_chain(mynewt_ctx->mnPacket);
  2317. mynewt_ctx->mnPacket = NULL;
  2318. }
  2319. }
  2320. return read_sz;
  2321. }
  2322. /* The Mynewt send callback
  2323. * return : bytes sent, or error
  2324. */
  2325. int Mynewt_Send(WOLFSSL* ssl, char *buf, int sz, void *ctx)
  2326. {
  2327. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx*)ctx;
  2328. int rc = 0;
  2329. struct os_mbuf *m;
  2330. int write_sz = 0;
  2331. m = os_msys_get_pkthdr(sz, 0);
  2332. if (!m) {
  2333. WOLFSSL_MSG("Mynewt Send os_msys_get_pkthdr error");
  2334. return WOLFSSL_CBIO_ERR_GENERAL;
  2335. }
  2336. rc = os_mbuf_copyinto(m, 0, buf, sz);
  2337. if (rc != 0) {
  2338. WOLFSSL_MSG("Mynewt Send os_mbuf_copyinto error");
  2339. os_mbuf_free_chain(m);
  2340. return rc;
  2341. }
  2342. rc = mn_sendto(mynewt_ctx->mnSocket, m, (struct mn_sockaddr *)&mynewt_ctx->mnSockAddrIn);
  2343. if(rc != 0) {
  2344. WOLFSSL_MSG("Mynewt Send mn_sendto error");
  2345. os_mbuf_free_chain(m);
  2346. return rc;
  2347. }
  2348. write_sz = sz;
  2349. return write_sz;
  2350. }
  2351. /* like set_fd, but for default NetX context */
  2352. void wolfSSL_SetIO_Mynewt(WOLFSSL* ssl, struct mn_socket* mnSocket, struct mn_sockaddr_in* mnSockAddrIn)
  2353. {
  2354. if (ssl && ssl->mnCtx) {
  2355. Mynewt_Ctx *mynewt_ctx = (Mynewt_Ctx *)ssl->mnCtx;
  2356. mynewt_ctx->mnSocket = mnSocket;
  2357. XMEMCPY(&mynewt_ctx->mnSockAddrIn, mnSockAddrIn, sizeof(struct mn_sockaddr_in));
  2358. mn_socket_set_cbs(mynewt_ctx->mnSocket, mnSocket, &mynewt_sock_cbs);
  2359. }
  2360. }
  2361. #endif /* defined(WOLFSSL_APACHE_MYNEWT) && !defined(WOLFSSL_LWIP) */
  2362. #ifdef WOLFSSL_UIP
  2363. #include <uip.h>
  2364. #include <stdio.h>
  2365. /* uIP TCP/IP port, using the native tcp/udp socket api.
  2366. * TCP and UDP are currently supported with the callbacks below.
  2367. *
  2368. */
  2369. /* The uIP tcp send callback
  2370. * return : bytes sent, or error
  2371. */
  2372. int uIPSend(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2373. {
  2374. uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
  2375. int total_written = 0;
  2376. (void)ssl;
  2377. do {
  2378. int ret;
  2379. unsigned int bytes_left = sz - total_written;
  2380. unsigned int max_sendlen = tcp_socket_max_sendlen(&ctx->conn.tcp);
  2381. if (bytes_left > max_sendlen) {
  2382. fprintf(stderr, "uIPSend: Send limited by buffer\r\n");
  2383. bytes_left = max_sendlen;
  2384. }
  2385. if (bytes_left == 0) {
  2386. fprintf(stderr, "uIPSend: Buffer full!\r\n");
  2387. break;
  2388. }
  2389. ret = tcp_socket_send(&ctx->conn.tcp, (unsigned char *)buf + total_written, bytes_left);
  2390. if (ret <= 0)
  2391. break;
  2392. total_written += ret;
  2393. } while(total_written < sz);
  2394. if (total_written == 0)
  2395. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2396. return total_written;
  2397. }
  2398. int uIPSendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2399. {
  2400. uip_wolfssl_ctx *ctx = (struct uip_wolfssl_ctx *)_ctx;
  2401. int ret = 0;
  2402. (void)ssl;
  2403. ret = udp_socket_sendto(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr, ctx->peer_port );
  2404. if (ret == 0)
  2405. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2406. return ret;
  2407. }
  2408. /* The uIP uTCP/IP receive callback
  2409. * return : nb bytes read, or error
  2410. */
  2411. int uIPReceive(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
  2412. {
  2413. uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
  2414. if (!ctx || !ctx->ssl_rx_databuf)
  2415. return -1;
  2416. (void)ssl;
  2417. if (ctx->ssl_rb_len > 0) {
  2418. if (sz > ctx->ssl_rb_len - ctx->ssl_rb_off)
  2419. sz = ctx->ssl_rb_len - ctx->ssl_rb_off;
  2420. XMEMCPY(buf, ctx->ssl_rx_databuf + ctx->ssl_rb_off, sz);
  2421. ctx->ssl_rb_off += sz;
  2422. if (ctx->ssl_rb_off >= ctx->ssl_rb_len) {
  2423. ctx->ssl_rb_len = 0;
  2424. ctx->ssl_rb_off = 0;
  2425. }
  2426. return sz;
  2427. } else {
  2428. return WOLFSSL_CBIO_ERR_WANT_READ;
  2429. }
  2430. }
  2431. /* uIP DTLS Generate Cookie callback
  2432. * return : number of bytes copied into buf, or error
  2433. */
  2434. #if defined(NO_SHA) && !defined(NO_SHA256)
  2435. #define UIP_COOKIE_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
  2436. #elif !defined(NO_SHA)
  2437. #define UIP_COOKIE_DIGEST_SIZE WC_SHA_DIGEST_SIZE
  2438. #else
  2439. #error Must enable either SHA-1 or SHA256 (or both) for uIP.
  2440. #endif
  2441. int uIPGenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
  2442. {
  2443. uip_wolfssl_ctx *ctx = (uip_wolfssl_ctx *)_ctx;
  2444. byte token[32];
  2445. byte digest[UIP_COOKIE_DIGEST_SIZE];
  2446. int ret = 0;
  2447. XMEMSET(token, 0, sizeof(token));
  2448. XMEMCPY(token, &ctx->peer_addr, sizeof(uip_ipaddr_t));
  2449. XMEMCPY(token + sizeof(uip_ipaddr_t), &ctx->peer_port, sizeof(word16));
  2450. #if defined(NO_SHA) && !defined(NO_SHA256)
  2451. ret = wc_Sha256Hash(token, sizeof(uip_ipaddr_t) + sizeof(word16), digest);
  2452. #else
  2453. ret = wc_ShaHash(token, sizeof(uip_ipaddr_t) + sizeof(word16), digest);
  2454. #endif
  2455. if (ret != 0)
  2456. return ret;
  2457. if (sz > UIP_COOKIE_DIGEST_SIZE)
  2458. sz = UIP_COOKIE_DIGEST_SIZE;
  2459. XMEMCPY(buf, digest, sz);
  2460. return sz;
  2461. }
  2462. #endif /* WOLFSSL_UIP */
  2463. #ifdef WOLFSSL_GNRC
  2464. #include <net/sock.h>
  2465. #include <net/sock/tcp.h>
  2466. #include <stdio.h>
  2467. /* GNRC TCP/IP port, using the native tcp/udp socket api.
  2468. * TCP and UDP are currently supported with the callbacks below.
  2469. *
  2470. */
  2471. /* The GNRC tcp send callback
  2472. * return : bytes sent, or error
  2473. */
  2474. int GNRC_SendTo(WOLFSSL* ssl, char* buf, int sz, void* _ctx)
  2475. {
  2476. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2477. int ret = 0;
  2478. (void)ssl;
  2479. if (!ctx)
  2480. return WOLFSSL_CBIO_ERR_GENERAL;
  2481. ret = sock_udp_send(&ctx->conn.udp, (unsigned char *)buf, sz, &ctx->peer_addr);
  2482. if (ret == 0)
  2483. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2484. return ret;
  2485. }
  2486. /* The GNRC TCP/IP receive callback
  2487. * return : nb bytes read, or error
  2488. */
  2489. int GNRC_ReceiveFrom(WOLFSSL *ssl, char *buf, int sz, void *_ctx)
  2490. {
  2491. sock_udp_ep_t ep;
  2492. int ret;
  2493. word32 timeout = wolfSSL_dtls_get_current_timeout(ssl) * 1000000;
  2494. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2495. if (!ctx)
  2496. return WOLFSSL_CBIO_ERR_GENERAL;
  2497. (void)ssl;
  2498. if (wolfSSL_get_using_nonblock(ctx->ssl)) {
  2499. timeout = 0;
  2500. }
  2501. ret = sock_udp_recv(&ctx->conn.udp, buf, sz, timeout, &ep);
  2502. if (ret > 0) {
  2503. if (ctx->peer_addr.port == 0)
  2504. XMEMCPY(&ctx->peer_addr, &ep, sizeof(sock_udp_ep_t));
  2505. }
  2506. if (ret == -ETIMEDOUT) {
  2507. return WOLFSSL_CBIO_ERR_WANT_READ;
  2508. }
  2509. return ret;
  2510. }
  2511. /* GNRC DTLS Generate Cookie callback
  2512. * return : number of bytes copied into buf, or error
  2513. */
  2514. #define GNRC_MAX_TOKEN_SIZE (32)
  2515. #if defined(NO_SHA) && !defined(NO_SHA256)
  2516. #define GNRC_COOKIE_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
  2517. #elif !defined(NO_SHA)
  2518. #define GNRC_COOKIE_DIGEST_SIZE WC_SHA_DIGEST_SIZE
  2519. #else
  2520. #error Must enable either SHA-1 or SHA256 (or both) for GNRC.
  2521. #endif
  2522. int GNRC_GenerateCookie(WOLFSSL* ssl, byte *buf, int sz, void *_ctx)
  2523. {
  2524. sock_tls_t *ctx = (sock_tls_t *)_ctx;
  2525. if (!ctx)
  2526. return WOLFSSL_CBIO_ERR_GENERAL;
  2527. byte token[GNRC_MAX_TOKEN_SIZE];
  2528. byte digest[GNRC_COOKIE_DIGEST_SIZE];
  2529. int ret = 0;
  2530. size_t token_size = sizeof(sock_udp_ep_t);
  2531. (void)ssl;
  2532. if (token_size > GNRC_MAX_TOKEN_SIZE)
  2533. token_size = GNRC_MAX_TOKEN_SIZE;
  2534. XMEMSET(token, 0, GNRC_MAX_TOKEN_SIZE);
  2535. XMEMCPY(token, &ctx->peer_addr, token_size);
  2536. #if defined(NO_SHA) && !defined(NO_SHA256)
  2537. ret = wc_Sha256Hash(token, token_size, digest);
  2538. #else
  2539. ret = wc_ShaHash(token, token_size, digest);
  2540. #endif
  2541. if (ret != 0)
  2542. return ret;
  2543. if (sz > GNRC_COOKIE_DIGEST_SIZE)
  2544. sz = GNRC_COOKIE_DIGEST_SIZE;
  2545. XMEMCPY(buf, digest, sz);
  2546. return sz;
  2547. }
  2548. #endif /* WOLFSSL_GNRC */
  2549. #ifdef WOLFSSL_LWIP_NATIVE
  2550. int LwIPNativeSend(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  2551. {
  2552. err_t ret;
  2553. WOLFSSL_LWIP_NATIVE_STATE* nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)ctx;
  2554. ret = tcp_write(nlwip->pcb, buf, sz, TCP_WRITE_FLAG_COPY);
  2555. if (ret != ERR_OK) {
  2556. sz = -1;
  2557. }
  2558. return sz;
  2559. }
  2560. int LwIPNativeReceive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  2561. {
  2562. struct pbuf *current, *head;
  2563. WOLFSSL_LWIP_NATIVE_STATE* nlwip;
  2564. int ret = 0;
  2565. if (ctx == NULL) {
  2566. return WOLFSSL_CBIO_ERR_GENERAL;
  2567. }
  2568. nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)ctx;
  2569. current = nlwip->pbuf;
  2570. if (current == NULL || sz > current->tot_len) {
  2571. WOLFSSL_MSG("LwIP native pbuf list is null or not enough data, want read");
  2572. ret = WOLFSSL_CBIO_ERR_WANT_READ;
  2573. }
  2574. else {
  2575. int read = 0; /* total amount read */
  2576. head = nlwip->pbuf; /* save pointer to current head */
  2577. /* loop through buffers reading data */
  2578. while (current != NULL) {
  2579. int len; /* current amount to be read */
  2580. len = (current->len - nlwip->pulled < sz) ?
  2581. (current->len - nlwip->pulled) : sz;
  2582. if (read + len > sz) {
  2583. /* should never be hit but have sanity check before use */
  2584. return WOLFSSL_CBIO_ERR_GENERAL;
  2585. }
  2586. /* check if is a partial read from before */
  2587. XMEMCPY(&buf[read],
  2588. (const char *)&(((char *)(current->payload))[nlwip->pulled]),
  2589. len);
  2590. nlwip->pulled = nlwip->pulled + len;
  2591. if (nlwip->pulled >= current->len) {
  2592. WOLFSSL_MSG("Native LwIP read full pbuf");
  2593. nlwip->pbuf = current->next;
  2594. current = nlwip->pbuf;
  2595. nlwip->pulled = 0;
  2596. }
  2597. read = read + len;
  2598. ret = read;
  2599. /* read enough break out */
  2600. if (read >= sz) {
  2601. /* if more pbuf's are left in the chain then increment the
  2602. * ref count for next in chain and free all from beginning till
  2603. * next */
  2604. if (current != NULL) {
  2605. pbuf_ref(current);
  2606. }
  2607. /* ack and start free'ing from the current head of the chain */
  2608. pbuf_free(head);
  2609. break;
  2610. }
  2611. }
  2612. }
  2613. WOLFSSL_LEAVE("LwIPNativeReceive", ret);
  2614. return ret;
  2615. }
  2616. static err_t LwIPNativeReceiveCB(void* cb, struct tcp_pcb* pcb,
  2617. struct pbuf* pbuf, err_t err)
  2618. {
  2619. WOLFSSL_LWIP_NATIVE_STATE* nlwip;
  2620. if (cb == NULL || pcb == NULL) {
  2621. WOLFSSL_MSG("Expected callback was null, abort");
  2622. return ERR_ABRT;
  2623. }
  2624. nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)cb;
  2625. if (pbuf == NULL && err == ERR_OK) {
  2626. return ERR_OK;
  2627. }
  2628. if (nlwip->pbuf == NULL) {
  2629. nlwip->pbuf = pbuf;
  2630. }
  2631. else {
  2632. if (nlwip->pbuf != pbuf) {
  2633. tcp_recved(nlwip->pcb, pbuf->tot_len);
  2634. pbuf_cat(nlwip->pbuf, pbuf); /* add chain to head */
  2635. }
  2636. }
  2637. if (nlwip->recv_fn) {
  2638. return nlwip->recv_fn(nlwip->arg, pcb, pbuf, err);
  2639. }
  2640. WOLFSSL_LEAVE("LwIPNativeReceiveCB", nlwip->pbuf->tot_len);
  2641. return ERR_OK;
  2642. }
  2643. static err_t LwIPNativeSentCB(void* cb, struct tcp_pcb* pcb, u16_t len)
  2644. {
  2645. WOLFSSL_LWIP_NATIVE_STATE* nlwip;
  2646. if (cb == NULL || pcb == NULL) {
  2647. WOLFSSL_MSG("Expected callback was null, abort");
  2648. return ERR_ABRT;
  2649. }
  2650. nlwip = (WOLFSSL_LWIP_NATIVE_STATE*)cb;
  2651. if (nlwip->sent_fn) {
  2652. return nlwip->sent_fn(nlwip->arg, pcb, len);
  2653. }
  2654. return ERR_OK;
  2655. }
  2656. int wolfSSL_SetIO_LwIP(WOLFSSL* ssl, void* pcb,
  2657. tcp_recv_fn recv_fn, tcp_sent_fn sent_fn, void *arg)
  2658. {
  2659. if (ssl == NULL || pcb == NULL)
  2660. return BAD_FUNC_ARG;
  2661. ssl->lwipCtx.pcb = (struct tcp_pcb *)pcb;
  2662. ssl->lwipCtx.recv_fn = recv_fn; /* recv user callback */
  2663. ssl->lwipCtx.sent_fn = sent_fn; /* sent user callback */
  2664. ssl->lwipCtx.arg = arg;
  2665. ssl->lwipCtx.pbuf = 0;
  2666. ssl->lwipCtx.pulled = 0;
  2667. ssl->lwipCtx.wait = 0;
  2668. /* wolfSSL_LwIP_recv/sent_cb invokes recv/sent user callback in them. */
  2669. tcp_recv(pcb, LwIPNativeReceiveCB);
  2670. tcp_sent(pcb, LwIPNativeSentCB);
  2671. tcp_arg (pcb, (void *)&ssl->lwipCtx);
  2672. wolfSSL_SetIOReadCtx(ssl, &ssl->lwipCtx);
  2673. wolfSSL_SetIOWriteCtx(ssl, &ssl->lwipCtx);
  2674. return ERR_OK;
  2675. }
  2676. #endif
  2677. #ifdef WOLFSSL_ISOTP
  2678. static int isotp_send_single_frame(struct isotp_wolfssl_ctx *ctx, char *buf,
  2679. word16 length)
  2680. {
  2681. /* Length will be at most 7 bytes to get here. Packet is length and type
  2682. * for the first byte, then up to 7 bytes of data */
  2683. ctx->frame.data[0] = ((byte)length) | (ISOTP_FRAME_TYPE_SINGLE << 4);
  2684. XMEMCPY(&ctx->frame.data[1], buf, length);
  2685. ctx->frame.length = length + 1;
  2686. return ctx->send_fn(&ctx->frame, ctx->arg);
  2687. }
  2688. static int isotp_send_flow_control(struct isotp_wolfssl_ctx *ctx,
  2689. byte overflow)
  2690. {
  2691. int ret;
  2692. /* Overflow is set it if we have been asked to receive more data than the
  2693. * user allocated a buffer for */
  2694. if (overflow) {
  2695. ctx->frame.data[0] = ISOTP_FLOW_CONTROL_ABORT |
  2696. (ISOTP_FRAME_TYPE_CONTROL << 4);
  2697. } else {
  2698. ctx->frame.data[0] = ISOTP_FLOW_CONTROL_CTS |
  2699. (ISOTP_FRAME_TYPE_CONTROL << 4);
  2700. }
  2701. /* Set the number of frames between flow control to infinite */
  2702. ctx->frame.data[1] = ISOTP_FLOW_CONTROL_FRAMES;
  2703. /* User specified frame delay */
  2704. ctx->frame.data[2] = ctx->receive_delay;
  2705. ctx->frame.length = ISOTP_FLOW_CONTROL_PACKET_SIZE;
  2706. ret = ctx->send_fn(&ctx->frame, ctx->arg);
  2707. return ret;
  2708. }
  2709. static int isotp_receive_flow_control(struct isotp_wolfssl_ctx *ctx)
  2710. {
  2711. int ret;
  2712. enum isotp_frame_type type;
  2713. enum isotp_flow_control flow_control;
  2714. ret = ctx->recv_fn(&ctx->frame, ctx->arg, ISOTP_DEFAULT_TIMEOUT);
  2715. if (ret == 0) {
  2716. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2717. } else if (ret < 0) {
  2718. WOLFSSL_MSG("ISO-TP error receiving flow control packet");
  2719. return WOLFSSL_CBIO_ERR_GENERAL;
  2720. }
  2721. /* Flow control is the frame type and flow response for the first byte,
  2722. * number of frames until the next flow control packet for the second
  2723. * byte, time between frames for the third byte */
  2724. type = ctx->frame.data[0] >> 4;
  2725. if (type != ISOTP_FRAME_TYPE_CONTROL) {
  2726. WOLFSSL_MSG("ISO-TP frames out of sequence");
  2727. return WOLFSSL_CBIO_ERR_GENERAL;
  2728. }
  2729. flow_control = ctx->frame.data[0] & 0xf;
  2730. ctx->flow_counter = 0;
  2731. ctx->flow_packets = ctx->frame.data[1];
  2732. ctx->frame_delay = ctx->frame.data[2];
  2733. return flow_control;
  2734. }
  2735. static int isotp_send_consecutive_frame(struct isotp_wolfssl_ctx *ctx)
  2736. {
  2737. /* Sequence is 0 - 15 and then starts again, the first frame has an
  2738. * implied sequence of '0' */
  2739. ctx->sequence += 1;
  2740. if (ctx->sequence > ISOTP_MAX_SEQUENCE_COUNTER) {
  2741. ctx->sequence = 0;
  2742. }
  2743. ctx->flow_counter++;
  2744. /* First byte it type and sequence number, up to 7 bytes of data */
  2745. ctx->frame.data[0] = ctx->sequence | (ISOTP_FRAME_TYPE_CONSECUTIVE << 4);
  2746. if (ctx->buf_length > ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE) {
  2747. XMEMCPY(&ctx->frame.data[1], ctx->buf_ptr,
  2748. ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE);
  2749. ctx->buf_ptr += ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE;
  2750. ctx->buf_length -= ISOTP_MAX_CONSECUTIVE_FRAME_DATA_SIZE;
  2751. ctx->frame.length = ISOTP_CAN_BUS_PAYLOAD_SIZE;
  2752. } else {
  2753. XMEMCPY(&ctx->frame.data[1], ctx->buf_ptr, ctx->buf_length);
  2754. ctx->frame.length = ctx->buf_length + 1;
  2755. ctx->buf_length = 0;
  2756. }
  2757. return ctx->send_fn(&ctx->frame, ctx->arg);
  2758. }
  2759. static int isotp_send_first_frame(struct isotp_wolfssl_ctx *ctx, char *buf,
  2760. word16 length)
  2761. {
  2762. int ret;
  2763. ctx->sequence = 0;
  2764. /* Set to 1 to trigger a flow control straight away, the flow control
  2765. * packet will set these properly */
  2766. ctx->flow_packets = ctx->flow_counter = 1;
  2767. /* First frame has 1 nibble for type, 3 nibbles for length followed by
  2768. * 6 bytes for data*/
  2769. ctx->frame.data[0] = (length >> 8) | (ISOTP_FRAME_TYPE_FIRST << 4);
  2770. ctx->frame.data[1] = length & 0xff;
  2771. XMEMCPY(&ctx->frame.data[2], buf, ISOTP_FIRST_FRAME_DATA_SIZE);
  2772. ctx->buf_ptr = buf + ISOTP_FIRST_FRAME_DATA_SIZE;
  2773. ctx->buf_length = length - ISOTP_FIRST_FRAME_DATA_SIZE;
  2774. ctx->frame.length = ISOTP_CAN_BUS_PAYLOAD_SIZE;
  2775. ret = ctx->send_fn(&ctx->frame, ctx->arg);
  2776. if (ret <= 0) {
  2777. WOLFSSL_MSG("ISO-TP error sending first frame");
  2778. return WOLFSSL_CBIO_ERR_GENERAL;
  2779. }
  2780. while(ctx->buf_length) {
  2781. /* The receiver can set how often to get a flow control packet. If it
  2782. * is time, then get the packet. Note that this will always happen
  2783. * after the first packet */
  2784. if ((ctx->flow_packets > 0) &&
  2785. (ctx->flow_counter == ctx->flow_packets)) {
  2786. ret = isotp_receive_flow_control(ctx);
  2787. }
  2788. /* Frame delay <= 0x7f is in ms, 0xfX is X * 100 us */
  2789. if (ctx->frame_delay) {
  2790. if (ctx->frame_delay <= ISOTP_MAX_MS_FRAME_DELAY) {
  2791. ctx->delay_fn(ctx->frame_delay * 1000);
  2792. } else {
  2793. ctx->delay_fn((ctx->frame_delay & 0xf) * 100);
  2794. }
  2795. }
  2796. switch (ret) {
  2797. /* Clear to send */
  2798. case ISOTP_FLOW_CONTROL_CTS:
  2799. if (isotp_send_consecutive_frame(ctx) < 0) {
  2800. WOLFSSL_MSG("ISO-TP error sending consecutive frame");
  2801. return WOLFSSL_CBIO_ERR_GENERAL;
  2802. }
  2803. break;
  2804. /* Receiver says "WAIT", so we wait for another flow control
  2805. * packet, or abort if we have waited too long */
  2806. case ISOTP_FLOW_CONTROL_WAIT:
  2807. ctx->wait_counter += 1;
  2808. if (ctx->wait_counter > ISOTP_DEFAULT_WAIT_COUNT) {
  2809. WOLFSSL_MSG("ISO-TP receiver told us to wait too many"
  2810. " times");
  2811. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2812. }
  2813. break;
  2814. /* Receiver is not ready to receive packet, so abort */
  2815. case ISOTP_FLOW_CONTROL_ABORT:
  2816. WOLFSSL_MSG("ISO-TP receiver aborted transmission");
  2817. return WOLFSSL_CBIO_ERR_WANT_WRITE;
  2818. default:
  2819. WOLFSSL_MSG("ISO-TP got unexpected flow control packet");
  2820. return WOLFSSL_CBIO_ERR_GENERAL;
  2821. }
  2822. }
  2823. return 0;
  2824. }
  2825. int ISOTP_Send(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  2826. {
  2827. int ret;
  2828. struct isotp_wolfssl_ctx *isotp_ctx;
  2829. (void) ssl;
  2830. if (!ctx) {
  2831. WOLFSSL_MSG("ISO-TP requires wolfSSL_SetIO_ISOTP to be called first");
  2832. return WOLFSSL_CBIO_ERR_GENERAL;
  2833. }
  2834. isotp_ctx = (struct isotp_wolfssl_ctx*) ctx;
  2835. /* ISO-TP cannot send more than 4095 bytes, this limits the packet size
  2836. * and wolfSSL will try again with the remaining data */
  2837. if (sz > ISOTP_MAX_DATA_SIZE) {
  2838. sz = ISOTP_MAX_DATA_SIZE;
  2839. }
  2840. /* Can't send whilst we are receiving */
  2841. if (isotp_ctx->state != ISOTP_CONN_STATE_IDLE) {
  2842. return WOLFSSL_ERROR_WANT_WRITE;
  2843. }
  2844. isotp_ctx->state = ISOTP_CONN_STATE_SENDING;
  2845. /* Assuming normal addressing */
  2846. if (sz <= ISOTP_SINGLE_FRAME_DATA_SIZE) {
  2847. ret = isotp_send_single_frame(isotp_ctx, buf, (word16)sz);
  2848. } else {
  2849. ret = isotp_send_first_frame(isotp_ctx, buf, (word16)sz);
  2850. }
  2851. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2852. if (ret == 0) {
  2853. return sz;
  2854. }
  2855. return ret;
  2856. }
  2857. static int isotp_receive_single_frame(struct isotp_wolfssl_ctx *ctx)
  2858. {
  2859. byte data_size;
  2860. /* 1 nibble for data size which will be 1 - 7 in a regular 8 byte CAN
  2861. * packet */
  2862. data_size = (byte)ctx->frame.data[0] & 0xf;
  2863. if (ctx->receive_buffer_size < (int)data_size) {
  2864. WOLFSSL_MSG("ISO-TP buffer is too small to receive data");
  2865. return BUFFER_E;
  2866. }
  2867. XMEMCPY(ctx->receive_buffer, &ctx->frame.data[1], data_size);
  2868. return data_size;
  2869. }
  2870. static int isotp_receive_multi_frame(struct isotp_wolfssl_ctx *ctx)
  2871. {
  2872. int ret;
  2873. word16 data_size;
  2874. byte delay = 0;
  2875. /* Increase receive timeout for enforced ms delay */
  2876. if (ctx->receive_delay <= ISOTP_MAX_MS_FRAME_DELAY) {
  2877. delay = ctx->receive_delay;
  2878. }
  2879. /* Still processing first frame.
  2880. * Full data size is lower nibble of first byte for the most significant
  2881. * followed by the second byte for the rest. Last 6 bytes are data */
  2882. data_size = ((ctx->frame.data[0] & 0xf) << 8) + ctx->frame.data[1];
  2883. XMEMCPY(ctx->receive_buffer, &ctx->frame.data[2], ISOTP_FIRST_FRAME_DATA_SIZE);
  2884. /* Need to send a flow control packet to either cancel or continue
  2885. * transmission of data */
  2886. if (ctx->receive_buffer_size < data_size) {
  2887. isotp_send_flow_control(ctx, TRUE);
  2888. WOLFSSL_MSG("ISO-TP buffer is too small to receive data");
  2889. return BUFFER_E;
  2890. }
  2891. isotp_send_flow_control(ctx, FALSE);
  2892. ctx->buf_length = ISOTP_FIRST_FRAME_DATA_SIZE;
  2893. ctx->buf_ptr = ctx->receive_buffer + ISOTP_FIRST_FRAME_DATA_SIZE;
  2894. data_size -= ISOTP_FIRST_FRAME_DATA_SIZE;
  2895. ctx->sequence = 1;
  2896. while(data_size) {
  2897. enum isotp_frame_type type;
  2898. byte sequence;
  2899. byte frame_len;
  2900. ret = ctx->recv_fn(&ctx->frame, ctx->arg, ISOTP_DEFAULT_TIMEOUT +
  2901. (delay / 1000));
  2902. if (ret == 0) {
  2903. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2904. }
  2905. type = ctx->frame.data[0] >> 4;
  2906. /* Consecutive frames have sequence number as lower nibble */
  2907. sequence = ctx->frame.data[0] & 0xf;
  2908. if (type != ISOTP_FRAME_TYPE_CONSECUTIVE) {
  2909. WOLFSSL_MSG("ISO-TP frames out of sequence");
  2910. return WOLFSSL_CBIO_ERR_GENERAL;
  2911. }
  2912. if (sequence != ctx->sequence) {
  2913. WOLFSSL_MSG("ISO-TP frames out of sequence");
  2914. return WOLFSSL_CBIO_ERR_GENERAL;
  2915. }
  2916. /* Last 7 bytes or whatever we got after the first byte is data */
  2917. frame_len = ctx->frame.length - 1;
  2918. XMEMCPY(ctx->buf_ptr, &ctx->frame.data[1], frame_len);
  2919. ctx->buf_ptr += frame_len;
  2920. ctx->buf_length += frame_len;
  2921. data_size -= frame_len;
  2922. /* Sequence is 0 - 15 (first 0 is implied for first packet */
  2923. ctx->sequence++;
  2924. if (ctx->sequence > ISOTP_MAX_SEQUENCE_COUNTER) {
  2925. ctx->sequence = 0;
  2926. }
  2927. }
  2928. return ctx->buf_length;
  2929. }
  2930. /* The wolfSSL receive callback, needs to buffer because we need to grab all
  2931. * incoming data, even if wolfSSL doesn't want it all yet */
  2932. int ISOTP_Receive(WOLFSSL* ssl, char* buf, int sz, void* ctx)
  2933. {
  2934. enum isotp_frame_type type;
  2935. int ret;
  2936. struct isotp_wolfssl_ctx *isotp_ctx;
  2937. (void) ssl;
  2938. if (!ctx) {
  2939. WOLFSSL_MSG("ISO-TP requires wolfSSL_SetIO_ISOTP to be called first");
  2940. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2941. }
  2942. isotp_ctx = (struct isotp_wolfssl_ctx*)ctx;
  2943. /* Is buffer empty? If so, fill it */
  2944. if (!isotp_ctx->receive_buffer_len) {
  2945. /* Can't send whilst we are receiving */
  2946. if (isotp_ctx->state != ISOTP_CONN_STATE_IDLE) {
  2947. return WOLFSSL_ERROR_WANT_READ;
  2948. }
  2949. isotp_ctx->state = ISOTP_CONN_STATE_RECEIVING;
  2950. do {
  2951. ret = isotp_ctx->recv_fn(&isotp_ctx->frame, isotp_ctx->arg,
  2952. ISOTP_DEFAULT_TIMEOUT);
  2953. } while (ret == 0);
  2954. if (ret == 0) {
  2955. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2956. return WOLFSSL_CBIO_ERR_TIMEOUT;
  2957. } else if (ret < 0) {
  2958. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2959. WOLFSSL_MSG("ISO-TP receive error");
  2960. return WOLFSSL_CBIO_ERR_GENERAL;
  2961. }
  2962. type = (enum isotp_frame_type) isotp_ctx->frame.data[0] >> 4;
  2963. if (type == ISOTP_FRAME_TYPE_SINGLE) {
  2964. isotp_ctx->receive_buffer_len =
  2965. isotp_receive_single_frame(isotp_ctx);
  2966. } else if (type == ISOTP_FRAME_TYPE_FIRST) {
  2967. isotp_ctx->receive_buffer_len =
  2968. isotp_receive_multi_frame(isotp_ctx);
  2969. } else {
  2970. /* Should never get here */
  2971. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2972. WOLFSSL_MSG("ISO-TP frames out of sequence");
  2973. return WOLFSSL_CBIO_ERR_GENERAL;
  2974. }
  2975. if (isotp_ctx->receive_buffer_len <= 1) {
  2976. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2977. return isotp_ctx->receive_buffer_len;
  2978. } else {
  2979. isotp_ctx->receive_buffer_ptr = isotp_ctx->receive_buffer;
  2980. }
  2981. isotp_ctx->state = ISOTP_CONN_STATE_IDLE;
  2982. }
  2983. /* Return from the buffer */
  2984. if (isotp_ctx->receive_buffer_len >= sz) {
  2985. XMEMCPY(buf, isotp_ctx->receive_buffer_ptr, sz);
  2986. isotp_ctx->receive_buffer_ptr+= sz;
  2987. isotp_ctx->receive_buffer_len-= sz;
  2988. return sz;
  2989. } else {
  2990. XMEMCPY(buf, isotp_ctx->receive_buffer_ptr,
  2991. isotp_ctx->receive_buffer_len);
  2992. sz = isotp_ctx->receive_buffer_len;
  2993. isotp_ctx->receive_buffer_len = 0;
  2994. return sz;
  2995. }
  2996. }
  2997. int wolfSSL_SetIO_ISOTP(WOLFSSL *ssl, isotp_wolfssl_ctx *ctx,
  2998. can_recv_fn recv_fn, can_send_fn send_fn, can_delay_fn delay_fn,
  2999. word32 receive_delay, char *receive_buffer, int receive_buffer_size,
  3000. void *arg)
  3001. {
  3002. if (!ctx || !recv_fn || !send_fn || !delay_fn || !receive_buffer) {
  3003. WOLFSSL_MSG("ISO-TP has missing required parameter");
  3004. return WOLFSSL_CBIO_ERR_GENERAL;
  3005. }
  3006. ctx->recv_fn = recv_fn;
  3007. ctx->send_fn = send_fn;
  3008. ctx->arg = arg;
  3009. ctx->delay_fn = delay_fn;
  3010. ctx->frame_delay = 0;
  3011. ctx->receive_buffer = receive_buffer;
  3012. ctx->receive_buffer_size = receive_buffer_size;
  3013. ctx->receive_buffer_len = 0;
  3014. ctx->state = ISOTP_CONN_STATE_IDLE;
  3015. wolfSSL_SetIOReadCtx(ssl, ctx);
  3016. wolfSSL_SetIOWriteCtx(ssl, ctx);
  3017. /* Delay of 100 - 900us is 0xfX where X is value / 100. Delay of
  3018. * >= 1000 is divided by 1000. > 127ms is invalid */
  3019. if (receive_delay < 1000) {
  3020. ctx->receive_delay = 0xf0 + (receive_delay / 100);
  3021. } else if (receive_delay <= ISOTP_MAX_MS_FRAME_DELAY * 1000) {
  3022. ctx->receive_delay = receive_delay / 1000;
  3023. } else {
  3024. WOLFSSL_MSG("ISO-TP delay parameter out of bounds");
  3025. return WOLFSSL_CBIO_ERR_GENERAL;
  3026. }
  3027. return 0;
  3028. }
  3029. #endif
  3030. #endif /* WOLFCRYPT_ONLY */