wolfio.c 105 KB

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