wolfio.c 105 KB

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