wolfio.c 99 KB

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