wolfio.c 102 KB

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