socket_ops.ipp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047
  1. //
  2. // detail/impl/socket_ops.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2025 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_DETAIL_SOCKET_OPS_IPP
  11. #define BOOST_ASIO_DETAIL_SOCKET_OPS_IPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #include <cctype>
  17. #include <cstdio>
  18. #include <cstdlib>
  19. #include <cstring>
  20. #include <cerrno>
  21. #include <new>
  22. #include <boost/asio/detail/assert.hpp>
  23. #include <boost/asio/detail/socket_ops.hpp>
  24. #include <boost/asio/error.hpp>
  25. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  26. # include <codecvt>
  27. # include <locale>
  28. # include <string>
  29. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  30. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__) \
  31. || defined(__MACH__) && defined(__APPLE__)
  32. # if defined(BOOST_ASIO_HAS_PTHREADS)
  33. # include <pthread.h>
  34. # endif // defined(BOOST_ASIO_HAS_PTHREADS)
  35. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  36. // || defined(__MACH__) && defined(__APPLE__)
  37. #if defined(_MSC_VER) && (_MSC_VER >= 1800)
  38. # include <malloc.h>
  39. #endif // defined(_MSC_VER) && (_MSC_VER >= 1800)
  40. #include <boost/asio/detail/push_options.hpp>
  41. namespace boost {
  42. namespace asio {
  43. namespace detail {
  44. namespace socket_ops {
  45. #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  46. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  47. struct msghdr { int msg_namelen; };
  48. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  49. #if defined(__hpux)
  50. // HP-UX doesn't declare these functions extern "C", so they are declared again
  51. // here to avoid linker errors about undefined symbols.
  52. extern "C" char* if_indextoname(unsigned int, char*);
  53. extern "C" unsigned int if_nametoindex(const char*);
  54. #endif // defined(__hpux)
  55. #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  56. inline void clear_last_error()
  57. {
  58. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  59. WSASetLastError(0);
  60. #else
  61. errno = 0;
  62. #endif
  63. }
  64. #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  65. inline void get_last_error(
  66. boost::system::error_code& ec, bool is_error_condition)
  67. {
  68. if (!is_error_condition)
  69. {
  70. boost::asio::error::clear(ec);
  71. }
  72. else
  73. {
  74. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  75. ec = boost::system::error_code(WSAGetLastError(),
  76. boost::asio::error::get_system_category());
  77. #else
  78. ec = boost::system::error_code(errno,
  79. boost::asio::error::get_system_category());
  80. #endif
  81. }
  82. }
  83. template <typename SockLenType>
  84. inline socket_type call_accept(SockLenType msghdr::*,
  85. socket_type s, void* addr, std::size_t* addrlen)
  86. {
  87. SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0;
  88. socket_type result = ::accept(s,
  89. static_cast<socket_addr_type*>(addr),
  90. addrlen ? &tmp_addrlen : 0);
  91. if (addrlen)
  92. *addrlen = (std::size_t)tmp_addrlen;
  93. return result;
  94. }
  95. socket_type accept(socket_type s, void* addr,
  96. std::size_t* addrlen, boost::system::error_code& ec)
  97. {
  98. if (s == invalid_socket)
  99. {
  100. ec = boost::asio::error::bad_descriptor;
  101. return invalid_socket;
  102. }
  103. socket_type new_s = call_accept(&msghdr::msg_namelen, s, addr, addrlen);
  104. get_last_error(ec, new_s == invalid_socket);
  105. if (new_s == invalid_socket)
  106. return new_s;
  107. #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
  108. int optval = 1;
  109. int result = ::setsockopt(new_s, SOL_SOCKET,
  110. SO_NOSIGPIPE, &optval, sizeof(optval));
  111. get_last_error(ec, result != 0);
  112. if (result != 0)
  113. {
  114. ::close(new_s);
  115. return invalid_socket;
  116. }
  117. #endif
  118. boost::asio::error::clear(ec);
  119. return new_s;
  120. }
  121. socket_type sync_accept(socket_type s, state_type state,
  122. void* addr, std::size_t* addrlen, boost::system::error_code& ec)
  123. {
  124. // Accept a socket.
  125. for (;;)
  126. {
  127. // Try to complete the operation without blocking.
  128. socket_type new_socket = socket_ops::accept(s, addr, addrlen, ec);
  129. // Check if operation succeeded.
  130. if (new_socket != invalid_socket)
  131. return new_socket;
  132. // Operation failed.
  133. if (ec == boost::asio::error::would_block
  134. || ec == boost::asio::error::try_again)
  135. {
  136. if (state & user_set_non_blocking)
  137. return invalid_socket;
  138. // Fall through to retry operation.
  139. }
  140. else if (ec == boost::asio::error::connection_aborted)
  141. {
  142. if (state & enable_connection_aborted)
  143. return invalid_socket;
  144. // Fall through to retry operation.
  145. }
  146. #if defined(EPROTO)
  147. else if (ec.value() == EPROTO)
  148. {
  149. if (state & enable_connection_aborted)
  150. return invalid_socket;
  151. // Fall through to retry operation.
  152. }
  153. #endif // defined(EPROTO)
  154. else
  155. return invalid_socket;
  156. // Wait for socket to become ready.
  157. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  158. return invalid_socket;
  159. }
  160. }
  161. #if defined(BOOST_ASIO_HAS_IOCP)
  162. void complete_iocp_accept(socket_type s, void* output_buffer,
  163. DWORD address_length, void* addr, std::size_t* addrlen,
  164. socket_type new_socket, boost::system::error_code& ec)
  165. {
  166. // Map non-portable errors to their portable counterparts.
  167. if (ec.value() == ERROR_NETNAME_DELETED)
  168. ec = boost::asio::error::connection_aborted;
  169. if (!ec)
  170. {
  171. // Get the address of the peer.
  172. if (addr && addrlen)
  173. {
  174. LPSOCKADDR local_addr = 0;
  175. int local_addr_length = 0;
  176. LPSOCKADDR remote_addr = 0;
  177. int remote_addr_length = 0;
  178. GetAcceptExSockaddrs(output_buffer, 0, address_length,
  179. address_length, &local_addr, &local_addr_length,
  180. &remote_addr, &remote_addr_length);
  181. if (static_cast<std::size_t>(remote_addr_length) > *addrlen)
  182. {
  183. ec = boost::asio::error::invalid_argument;
  184. }
  185. else
  186. {
  187. using namespace std; // For memcpy.
  188. memcpy(addr, remote_addr, remote_addr_length);
  189. *addrlen = static_cast<std::size_t>(remote_addr_length);
  190. }
  191. }
  192. // Need to set the SO_UPDATE_ACCEPT_CONTEXT option so that getsockname
  193. // and getpeername will work on the accepted socket.
  194. SOCKET update_ctx_param = s;
  195. socket_ops::state_type state = 0;
  196. socket_ops::setsockopt(new_socket, state,
  197. SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
  198. &update_ctx_param, sizeof(SOCKET), ec);
  199. }
  200. }
  201. #else // defined(BOOST_ASIO_HAS_IOCP)
  202. bool non_blocking_accept(socket_type s,
  203. state_type state, void* addr, std::size_t* addrlen,
  204. boost::system::error_code& ec, socket_type& new_socket)
  205. {
  206. for (;;)
  207. {
  208. // Accept the waiting connection.
  209. new_socket = socket_ops::accept(s, addr, addrlen, ec);
  210. // Check if operation succeeded.
  211. if (new_socket != invalid_socket)
  212. return true;
  213. // Retry operation if interrupted by signal.
  214. if (ec == boost::asio::error::interrupted)
  215. continue;
  216. // Operation failed.
  217. if (ec == boost::asio::error::would_block
  218. || ec == boost::asio::error::try_again)
  219. {
  220. // Fall through to retry operation.
  221. }
  222. else if (ec == boost::asio::error::connection_aborted)
  223. {
  224. if (state & enable_connection_aborted)
  225. return true;
  226. // Fall through to retry operation.
  227. }
  228. #if defined(EPROTO)
  229. else if (ec.value() == EPROTO)
  230. {
  231. if (state & enable_connection_aborted)
  232. return true;
  233. // Fall through to retry operation.
  234. }
  235. #endif // defined(EPROTO)
  236. else
  237. return true;
  238. return false;
  239. }
  240. }
  241. #endif // defined(BOOST_ASIO_HAS_IOCP)
  242. template <typename SockLenType>
  243. inline int call_bind(SockLenType msghdr::*,
  244. socket_type s, const void* addr, std::size_t addrlen)
  245. {
  246. return ::bind(s, static_cast<const socket_addr_type*>(addr),
  247. (SockLenType)addrlen);
  248. }
  249. int bind(socket_type s, const void* addr,
  250. std::size_t addrlen, boost::system::error_code& ec)
  251. {
  252. if (s == invalid_socket)
  253. {
  254. ec = boost::asio::error::bad_descriptor;
  255. return socket_error_retval;
  256. }
  257. int result = call_bind(&msghdr::msg_namelen, s, addr, addrlen);
  258. get_last_error(ec, result != 0);
  259. return result;
  260. }
  261. int close(socket_type s, state_type& state,
  262. bool destruction, boost::system::error_code& ec)
  263. {
  264. int result = 0;
  265. if (s != invalid_socket)
  266. {
  267. // We don't want the destructor to block, so set the socket to linger in
  268. // the background. If the user doesn't like this behaviour then they need
  269. // to explicitly close the socket.
  270. if (destruction && (state & user_set_linger))
  271. {
  272. ::linger opt;
  273. opt.l_onoff = 0;
  274. opt.l_linger = 0;
  275. boost::system::error_code ignored_ec;
  276. socket_ops::setsockopt(s, state, SOL_SOCKET,
  277. SO_LINGER, &opt, sizeof(opt), ignored_ec);
  278. }
  279. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  280. result = ::closesocket(s);
  281. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  282. result = ::close(s);
  283. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  284. get_last_error(ec, result != 0);
  285. if (result != 0
  286. && (ec == boost::asio::error::would_block
  287. || ec == boost::asio::error::try_again))
  288. {
  289. // According to UNIX Network Programming Vol. 1, it is possible for
  290. // close() to fail with EWOULDBLOCK under certain circumstances. What
  291. // isn't clear is the state of the descriptor after this error. The one
  292. // current OS where this behaviour is seen, Windows, says that the socket
  293. // remains open. Therefore we'll put the descriptor back into blocking
  294. // mode and have another attempt at closing it.
  295. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  296. ioctl_arg_type arg = 0;
  297. ::ioctlsocket(s, FIONBIO, &arg);
  298. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  299. # if defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  300. int flags = ::fcntl(s, F_GETFL, 0);
  301. if (flags >= 0)
  302. ::fcntl(s, F_SETFL, flags & ~O_NONBLOCK);
  303. # else // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  304. ioctl_arg_type arg = 0;
  305. if ((state & possible_dup) == 0)
  306. {
  307. result = ::ioctl(s, FIONBIO, &arg);
  308. get_last_error(ec, result < 0);
  309. }
  310. if ((state & possible_dup) != 0
  311. # if defined(ENOTTY)
  312. || ec.value() == ENOTTY
  313. # endif // defined(ENOTTY)
  314. # if defined(ENOTCAPABLE)
  315. || ec.value() == ENOTCAPABLE
  316. # endif // defined(ENOTCAPABLE)
  317. )
  318. {
  319. int flags = ::fcntl(s, F_GETFL, 0);
  320. if (flags >= 0)
  321. ::fcntl(s, F_SETFL, flags & ~O_NONBLOCK);
  322. }
  323. # endif // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  324. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  325. state &= ~non_blocking;
  326. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  327. result = ::closesocket(s);
  328. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  329. result = ::close(s);
  330. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  331. get_last_error(ec, result != 0);
  332. }
  333. }
  334. return result;
  335. }
  336. bool set_user_non_blocking(socket_type s,
  337. state_type& state, bool value, boost::system::error_code& ec)
  338. {
  339. if (s == invalid_socket)
  340. {
  341. ec = boost::asio::error::bad_descriptor;
  342. return false;
  343. }
  344. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  345. ioctl_arg_type arg = (value ? 1 : 0);
  346. int result = ::ioctlsocket(s, FIONBIO, &arg);
  347. get_last_error(ec, result < 0);
  348. #elif defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  349. int result = ::fcntl(s, F_GETFL, 0);
  350. get_last_error(ec, result < 0);
  351. if (result >= 0)
  352. {
  353. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  354. result = (flag != result) ? ::fcntl(s, F_SETFL, flag) : 0;
  355. get_last_error(ec, result < 0);
  356. }
  357. #else // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  358. ioctl_arg_type arg = (value ? 1 : 0);
  359. int result = 0;
  360. if ((state & possible_dup) == 0)
  361. {
  362. result = ::ioctl(s, FIONBIO, &arg);
  363. get_last_error(ec, result < 0);
  364. }
  365. if ((state & possible_dup) != 0
  366. # if defined(ENOTTY)
  367. || ec.value() == ENOTTY
  368. # endif // defined(ENOTTY)
  369. # if defined(ENOTCAPABLE)
  370. || ec.value() == ENOTCAPABLE
  371. # endif // defined(ENOTCAPABLE)
  372. )
  373. {
  374. result = ::fcntl(s, F_GETFL, 0);
  375. get_last_error(ec, result < 0);
  376. if (result >= 0)
  377. {
  378. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  379. result = (flag != result) ? ::fcntl(s, F_SETFL, flag) : 0;
  380. get_last_error(ec, result < 0);
  381. }
  382. }
  383. #endif // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  384. if (result >= 0)
  385. {
  386. if (value)
  387. state |= user_set_non_blocking;
  388. else
  389. {
  390. // Clearing the user-set non-blocking mode always overrides any
  391. // internally-set non-blocking flag. Any subsequent asynchronous
  392. // operations will need to re-enable non-blocking I/O.
  393. state &= ~(user_set_non_blocking | internal_non_blocking);
  394. }
  395. return true;
  396. }
  397. return false;
  398. }
  399. bool set_internal_non_blocking(socket_type s,
  400. state_type& state, bool value, boost::system::error_code& ec)
  401. {
  402. if (s == invalid_socket)
  403. {
  404. ec = boost::asio::error::bad_descriptor;
  405. return false;
  406. }
  407. if (!value && (state & user_set_non_blocking))
  408. {
  409. // It does not make sense to clear the internal non-blocking flag if the
  410. // user still wants non-blocking behaviour. Return an error and let the
  411. // caller figure out whether to update the user-set non-blocking flag.
  412. ec = boost::asio::error::invalid_argument;
  413. return false;
  414. }
  415. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  416. ioctl_arg_type arg = (value ? 1 : 0);
  417. int result = ::ioctlsocket(s, FIONBIO, &arg);
  418. get_last_error(ec, result < 0);
  419. #elif defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  420. int result = ::fcntl(s, F_GETFL, 0);
  421. get_last_error(ec, result < 0);
  422. if (result >= 0)
  423. {
  424. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  425. result = (flag != result) ? ::fcntl(s, F_SETFL, flag) : 0;
  426. get_last_error(ec, result < 0);
  427. }
  428. #else // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  429. ioctl_arg_type arg = (value ? 1 : 0);
  430. int result = 0;
  431. if ((state & possible_dup) == 0)
  432. {
  433. result = ::ioctl(s, FIONBIO, &arg);
  434. get_last_error(ec, result < 0);
  435. }
  436. if ((state & possible_dup) != 0
  437. # if defined(ENOTTY)
  438. || ec.value() == ENOTTY
  439. # endif // defined(ENOTTY)
  440. # if defined(ENOTCAPABLE)
  441. || ec.value() == ENOTCAPABLE
  442. # endif // defined(ENOTCAPABLE)
  443. )
  444. {
  445. result = ::fcntl(s, F_GETFL, 0);
  446. get_last_error(ec, result < 0);
  447. if (result >= 0)
  448. {
  449. int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
  450. result = (flag != result) ? ::fcntl(s, F_SETFL, flag) : 0;
  451. get_last_error(ec, result < 0);
  452. }
  453. }
  454. #endif // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
  455. if (result >= 0)
  456. {
  457. if (value)
  458. state |= internal_non_blocking;
  459. else
  460. state &= ~internal_non_blocking;
  461. return true;
  462. }
  463. return false;
  464. }
  465. int shutdown(socket_type s, int what, boost::system::error_code& ec)
  466. {
  467. if (s == invalid_socket)
  468. {
  469. ec = boost::asio::error::bad_descriptor;
  470. return socket_error_retval;
  471. }
  472. int result = ::shutdown(s, what);
  473. get_last_error(ec, result != 0);
  474. return result;
  475. }
  476. template <typename SockLenType>
  477. inline int call_connect(SockLenType msghdr::*,
  478. socket_type s, const void* addr, std::size_t addrlen)
  479. {
  480. return ::connect(s, static_cast<const socket_addr_type*>(addr),
  481. (SockLenType)addrlen);
  482. }
  483. int connect(socket_type s, const void* addr,
  484. std::size_t addrlen, boost::system::error_code& ec)
  485. {
  486. if (s == invalid_socket)
  487. {
  488. ec = boost::asio::error::bad_descriptor;
  489. return socket_error_retval;
  490. }
  491. int result = call_connect(&msghdr::msg_namelen, s, addr, addrlen);
  492. get_last_error(ec, result != 0);
  493. #if defined(__linux__)
  494. if (result != 0 && ec == boost::asio::error::try_again)
  495. {
  496. if (static_cast<const socket_addr_type*>(addr)->sa_family == AF_UNIX)
  497. ec = boost::asio::error::in_progress;
  498. else
  499. ec = boost::asio::error::no_buffer_space;
  500. }
  501. #endif // defined(__linux__)
  502. return result;
  503. }
  504. void sync_connect(socket_type s, const void* addr,
  505. std::size_t addrlen, boost::system::error_code& ec)
  506. {
  507. // Perform the connect operation.
  508. socket_ops::connect(s, addr, addrlen, ec);
  509. if (ec != boost::asio::error::in_progress
  510. && ec != boost::asio::error::would_block)
  511. {
  512. // The connect operation finished immediately.
  513. return;
  514. }
  515. // Wait for socket to become ready.
  516. if (socket_ops::poll_connect(s, -1, ec) < 0)
  517. return;
  518. // Get the error code from the connect operation.
  519. int connect_error = 0;
  520. size_t connect_error_len = sizeof(connect_error);
  521. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
  522. &connect_error, &connect_error_len, ec) == socket_error_retval)
  523. return;
  524. // Return the result of the connect operation.
  525. ec = boost::system::error_code(connect_error,
  526. boost::asio::error::get_system_category());
  527. }
  528. #if defined(BOOST_ASIO_HAS_IOCP)
  529. void complete_iocp_connect(socket_type s, boost::system::error_code& ec)
  530. {
  531. // Map non-portable errors to their portable counterparts.
  532. switch (ec.value())
  533. {
  534. case ERROR_CONNECTION_REFUSED:
  535. ec = boost::asio::error::connection_refused;
  536. break;
  537. case ERROR_NETWORK_UNREACHABLE:
  538. ec = boost::asio::error::network_unreachable;
  539. break;
  540. case ERROR_HOST_UNREACHABLE:
  541. ec = boost::asio::error::host_unreachable;
  542. break;
  543. case ERROR_SEM_TIMEOUT:
  544. ec = boost::asio::error::timed_out;
  545. break;
  546. default:
  547. break;
  548. }
  549. if (!ec)
  550. {
  551. // Need to set the SO_UPDATE_CONNECT_CONTEXT option so that getsockname
  552. // and getpeername will work on the connected socket.
  553. socket_ops::state_type state = 0;
  554. const int so_update_connect_context = 0x7010;
  555. socket_ops::setsockopt(s, state, SOL_SOCKET,
  556. so_update_connect_context, 0, 0, ec);
  557. }
  558. }
  559. #endif // defined(BOOST_ASIO_HAS_IOCP)
  560. bool non_blocking_connect(socket_type s, boost::system::error_code& ec)
  561. {
  562. // Check if the connect operation has finished. This is required since we may
  563. // get spurious readiness notifications from the reactor.
  564. #if defined(BOOST_ASIO_WINDOWS) \
  565. || defined(__CYGWIN__) \
  566. || defined(__SYMBIAN32__)
  567. fd_set write_fds;
  568. FD_ZERO(&write_fds);
  569. FD_SET(s, &write_fds);
  570. fd_set except_fds;
  571. FD_ZERO(&except_fds);
  572. FD_SET(s, &except_fds);
  573. timeval zero_timeout;
  574. zero_timeout.tv_sec = 0;
  575. zero_timeout.tv_usec = 0;
  576. int ready = ::select(s + 1, 0, &write_fds, &except_fds, &zero_timeout);
  577. #else // defined(BOOST_ASIO_WINDOWS)
  578. // || defined(__CYGWIN__)
  579. // || defined(__SYMBIAN32__)
  580. pollfd fds;
  581. fds.fd = s;
  582. fds.events = POLLOUT;
  583. fds.revents = 0;
  584. int ready = ::poll(&fds, 1, 0);
  585. #endif // defined(BOOST_ASIO_WINDOWS)
  586. // || defined(__CYGWIN__)
  587. // || defined(__SYMBIAN32__)
  588. if (ready == 0)
  589. {
  590. // The asynchronous connect operation is still in progress.
  591. return false;
  592. }
  593. // Get the error code from the connect operation.
  594. int connect_error = 0;
  595. size_t connect_error_len = sizeof(connect_error);
  596. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
  597. &connect_error, &connect_error_len, ec) == 0)
  598. {
  599. if (connect_error)
  600. {
  601. ec = boost::system::error_code(connect_error,
  602. boost::asio::error::get_system_category());
  603. }
  604. else
  605. boost::asio::error::clear(ec);
  606. }
  607. return true;
  608. }
  609. int socketpair(int af, int type, int protocol,
  610. socket_type sv[2], boost::system::error_code& ec)
  611. {
  612. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  613. (void)(af);
  614. (void)(type);
  615. (void)(protocol);
  616. (void)(sv);
  617. ec = boost::asio::error::operation_not_supported;
  618. return socket_error_retval;
  619. #else
  620. int result = ::socketpair(af, type, protocol, sv);
  621. get_last_error(ec, result != 0);
  622. return result;
  623. #endif
  624. }
  625. bool sockatmark(socket_type s, boost::system::error_code& ec)
  626. {
  627. if (s == invalid_socket)
  628. {
  629. ec = boost::asio::error::bad_descriptor;
  630. return false;
  631. }
  632. #if defined(SIOCATMARK)
  633. ioctl_arg_type value = 0;
  634. # if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  635. int result = ::ioctlsocket(s, SIOCATMARK, &value);
  636. # else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  637. int result = ::ioctl(s, SIOCATMARK, &value);
  638. # endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  639. get_last_error(ec, result < 0);
  640. # if defined(ENOTTY)
  641. if (ec.value() == ENOTTY)
  642. ec = boost::asio::error::not_socket;
  643. # endif // defined(ENOTTY)
  644. #else // defined(SIOCATMARK)
  645. int value = ::sockatmark(s);
  646. get_last_error(ec, value < 0);
  647. #endif // defined(SIOCATMARK)
  648. return ec ? false : value != 0;
  649. }
  650. size_t available(socket_type s, boost::system::error_code& ec)
  651. {
  652. if (s == invalid_socket)
  653. {
  654. ec = boost::asio::error::bad_descriptor;
  655. return 0;
  656. }
  657. ioctl_arg_type value = 0;
  658. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  659. int result = ::ioctlsocket(s, FIONREAD, &value);
  660. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  661. int result = ::ioctl(s, FIONREAD, &value);
  662. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  663. get_last_error(ec, result < 0);
  664. #if defined(ENOTTY)
  665. if (ec.value() == ENOTTY)
  666. ec = boost::asio::error::not_socket;
  667. #endif // defined(ENOTTY)
  668. return ec ? static_cast<size_t>(0) : static_cast<size_t>(value);
  669. }
  670. int listen(socket_type s, int backlog, boost::system::error_code& ec)
  671. {
  672. if (s == invalid_socket)
  673. {
  674. ec = boost::asio::error::bad_descriptor;
  675. return socket_error_retval;
  676. }
  677. int result = ::listen(s, backlog);
  678. get_last_error(ec, result != 0);
  679. return result;
  680. }
  681. inline void init_buf_iov_base(void*& base, void* addr)
  682. {
  683. base = addr;
  684. }
  685. template <typename T>
  686. inline void init_buf_iov_base(T& base, void* addr)
  687. {
  688. base = static_cast<T>(addr);
  689. }
  690. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  691. typedef WSABUF buf;
  692. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  693. typedef iovec buf;
  694. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  695. void init_buf(buf& b, void* data, size_t size)
  696. {
  697. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  698. b.buf = static_cast<char*>(data);
  699. b.len = static_cast<u_long>(size);
  700. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  701. init_buf_iov_base(b.iov_base, data);
  702. b.iov_len = size;
  703. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  704. }
  705. void init_buf(buf& b, const void* data, size_t size)
  706. {
  707. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  708. b.buf = static_cast<char*>(const_cast<void*>(data));
  709. b.len = static_cast<u_long>(size);
  710. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  711. init_buf_iov_base(b.iov_base, const_cast<void*>(data));
  712. b.iov_len = size;
  713. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  714. }
  715. inline void init_msghdr_msg_name(void*& name, void* addr)
  716. {
  717. name = static_cast<socket_addr_type*>(addr);
  718. }
  719. inline void init_msghdr_msg_name(void*& name, const socket_addr_type* addr)
  720. {
  721. name = const_cast<socket_addr_type*>(addr);
  722. }
  723. template <typename T>
  724. inline void init_msghdr_msg_name(T& name, void* addr)
  725. {
  726. name = static_cast<T>(addr);
  727. }
  728. template <typename T>
  729. inline void init_msghdr_msg_name(T& name, const void* addr)
  730. {
  731. name = static_cast<T>(const_cast<void*>(addr));
  732. }
  733. signed_size_type recv(socket_type s, buf* bufs, size_t count,
  734. int flags, boost::system::error_code& ec)
  735. {
  736. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  737. // Receive some data.
  738. DWORD recv_buf_count = static_cast<DWORD>(count);
  739. DWORD bytes_transferred = 0;
  740. DWORD recv_flags = flags;
  741. int result = ::WSARecv(s, bufs, recv_buf_count,
  742. &bytes_transferred, &recv_flags, 0, 0);
  743. get_last_error(ec, true);
  744. if (ec.value() == ERROR_NETNAME_DELETED)
  745. ec = boost::asio::error::connection_reset;
  746. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  747. ec = boost::asio::error::connection_refused;
  748. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  749. result = 0;
  750. if (result != 0)
  751. return socket_error_retval;
  752. boost::asio::error::clear(ec);
  753. return bytes_transferred;
  754. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  755. msghdr msg = msghdr();
  756. msg.msg_iov = bufs;
  757. msg.msg_iovlen = static_cast<int>(count);
  758. signed_size_type result = ::recvmsg(s, &msg, flags);
  759. get_last_error(ec, result < 0);
  760. return result;
  761. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  762. }
  763. signed_size_type recv1(socket_type s, void* data, size_t size,
  764. int flags, boost::system::error_code& ec)
  765. {
  766. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  767. // Receive some data.
  768. WSABUF buf;
  769. buf.buf = const_cast<char*>(static_cast<const char*>(data));
  770. buf.len = static_cast<ULONG>(size);
  771. DWORD bytes_transferred = 0;
  772. DWORD recv_flags = flags;
  773. int result = ::WSARecv(s, &buf, 1,
  774. &bytes_transferred, &recv_flags, 0, 0);
  775. get_last_error(ec, true);
  776. if (ec.value() == ERROR_NETNAME_DELETED)
  777. ec = boost::asio::error::connection_reset;
  778. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  779. ec = boost::asio::error::connection_refused;
  780. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  781. result = 0;
  782. if (result != 0)
  783. return socket_error_retval;
  784. boost::asio::error::clear(ec);
  785. return bytes_transferred;
  786. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  787. signed_size_type result = ::recv(s, static_cast<char*>(data), size, flags);
  788. get_last_error(ec, result < 0);
  789. return result;
  790. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  791. }
  792. size_t sync_recv(socket_type s, state_type state, buf* bufs,
  793. size_t count, int flags, bool all_empty, boost::system::error_code& ec)
  794. {
  795. if (s == invalid_socket)
  796. {
  797. ec = boost::asio::error::bad_descriptor;
  798. return 0;
  799. }
  800. // A request to read 0 bytes on a stream is a no-op.
  801. if (all_empty && (state & stream_oriented))
  802. {
  803. boost::asio::error::clear(ec);
  804. return 0;
  805. }
  806. // Read some data.
  807. for (;;)
  808. {
  809. // Try to complete the operation without blocking.
  810. signed_size_type bytes = socket_ops::recv(s, bufs, count, flags, ec);
  811. // Check for EOF.
  812. if ((state & stream_oriented) && bytes == 0)
  813. {
  814. ec = boost::asio::error::eof;
  815. return 0;
  816. }
  817. // Check if operation succeeded.
  818. if (bytes >= 0)
  819. return bytes;
  820. // Operation failed.
  821. if ((state & user_set_non_blocking)
  822. || (ec != boost::asio::error::would_block
  823. && ec != boost::asio::error::try_again))
  824. return 0;
  825. // Wait for socket to become ready.
  826. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  827. return 0;
  828. }
  829. }
  830. size_t sync_recv1(socket_type s, state_type state, void* data,
  831. size_t size, int flags, boost::system::error_code& ec)
  832. {
  833. if (s == invalid_socket)
  834. {
  835. ec = boost::asio::error::bad_descriptor;
  836. return 0;
  837. }
  838. // A request to read 0 bytes on a stream is a no-op.
  839. if (size == 0 && (state & stream_oriented))
  840. {
  841. boost::asio::error::clear(ec);
  842. return 0;
  843. }
  844. // Read some data.
  845. for (;;)
  846. {
  847. // Try to complete the operation without blocking.
  848. signed_size_type bytes = socket_ops::recv1(s, data, size, flags, ec);
  849. // Check for EOF.
  850. if ((state & stream_oriented) && bytes == 0)
  851. {
  852. ec = boost::asio::error::eof;
  853. return 0;
  854. }
  855. // Check if operation succeeded.
  856. if (bytes >= 0)
  857. return bytes;
  858. // Operation failed.
  859. if ((state & user_set_non_blocking)
  860. || (ec != boost::asio::error::would_block
  861. && ec != boost::asio::error::try_again))
  862. return 0;
  863. // Wait for socket to become ready.
  864. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  865. return 0;
  866. }
  867. }
  868. #if defined(BOOST_ASIO_HAS_IOCP)
  869. void complete_iocp_recv(state_type state,
  870. const weak_cancel_token_type& cancel_token, bool all_empty,
  871. boost::system::error_code& ec, size_t bytes_transferred)
  872. {
  873. // Map non-portable errors to their portable counterparts.
  874. if (ec.value() == ERROR_NETNAME_DELETED)
  875. {
  876. if (cancel_token.expired())
  877. ec = boost::asio::error::operation_aborted;
  878. else
  879. ec = boost::asio::error::connection_reset;
  880. }
  881. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  882. {
  883. ec = boost::asio::error::connection_refused;
  884. }
  885. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  886. {
  887. boost::asio::error::clear(ec);
  888. }
  889. // Check for connection closed.
  890. else if (!ec && bytes_transferred == 0
  891. && (state & stream_oriented) != 0
  892. && !all_empty)
  893. {
  894. ec = boost::asio::error::eof;
  895. }
  896. }
  897. #else // defined(BOOST_ASIO_HAS_IOCP)
  898. bool non_blocking_recv(socket_type s,
  899. buf* bufs, size_t count, int flags, bool is_stream,
  900. boost::system::error_code& ec, size_t& bytes_transferred)
  901. {
  902. for (;;)
  903. {
  904. // Read some data.
  905. signed_size_type bytes = socket_ops::recv(s, bufs, count, flags, ec);
  906. // Check for end of stream.
  907. if (is_stream && bytes == 0)
  908. {
  909. ec = boost::asio::error::eof;
  910. return true;
  911. }
  912. // Check if operation succeeded.
  913. if (bytes >= 0)
  914. {
  915. bytes_transferred = bytes;
  916. return true;
  917. }
  918. // Retry operation if interrupted by signal.
  919. if (ec == boost::asio::error::interrupted)
  920. continue;
  921. // Check if we need to run the operation again.
  922. if (ec == boost::asio::error::would_block
  923. || ec == boost::asio::error::try_again)
  924. return false;
  925. // Operation failed.
  926. bytes_transferred = 0;
  927. return true;
  928. }
  929. }
  930. bool non_blocking_recv1(socket_type s,
  931. void* data, size_t size, int flags, bool is_stream,
  932. boost::system::error_code& ec, size_t& bytes_transferred)
  933. {
  934. for (;;)
  935. {
  936. // Read some data.
  937. signed_size_type bytes = socket_ops::recv1(s, data, size, flags, ec);
  938. // Check for end of stream.
  939. if (is_stream && bytes == 0)
  940. {
  941. ec = boost::asio::error::eof;
  942. return true;
  943. }
  944. // Check if operation succeeded.
  945. if (bytes >= 0)
  946. {
  947. bytes_transferred = bytes;
  948. return true;
  949. }
  950. // Retry operation if interrupted by signal.
  951. if (ec == boost::asio::error::interrupted)
  952. continue;
  953. // Check if we need to run the operation again.
  954. if (ec == boost::asio::error::would_block
  955. || ec == boost::asio::error::try_again)
  956. return false;
  957. // Operation failed.
  958. bytes_transferred = 0;
  959. return true;
  960. }
  961. }
  962. #endif // defined(BOOST_ASIO_HAS_IOCP)
  963. signed_size_type recvfrom(socket_type s, buf* bufs, size_t count,
  964. int flags, void* addr, std::size_t* addrlen, boost::system::error_code& ec)
  965. {
  966. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  967. // Receive some data.
  968. DWORD recv_buf_count = static_cast<DWORD>(count);
  969. DWORD bytes_transferred = 0;
  970. DWORD recv_flags = flags;
  971. int tmp_addrlen = (int)*addrlen;
  972. int result = ::WSARecvFrom(s, bufs, recv_buf_count, &bytes_transferred,
  973. &recv_flags, static_cast<socket_addr_type*>(addr), &tmp_addrlen, 0, 0);
  974. get_last_error(ec, true);
  975. *addrlen = (std::size_t)tmp_addrlen;
  976. if (ec.value() == ERROR_NETNAME_DELETED)
  977. ec = boost::asio::error::connection_reset;
  978. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  979. ec = boost::asio::error::connection_refused;
  980. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  981. result = 0;
  982. if (result != 0)
  983. return socket_error_retval;
  984. boost::asio::error::clear(ec);
  985. return bytes_transferred;
  986. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  987. msghdr msg = msghdr();
  988. init_msghdr_msg_name(msg.msg_name, addr);
  989. msg.msg_namelen = static_cast<int>(*addrlen);
  990. msg.msg_iov = bufs;
  991. msg.msg_iovlen = static_cast<int>(count);
  992. signed_size_type result = ::recvmsg(s, &msg, flags);
  993. get_last_error(ec, result < 0);
  994. *addrlen = msg.msg_namelen;
  995. return result;
  996. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  997. }
  998. template <typename SockLenType>
  999. inline signed_size_type call_recvfrom(SockLenType msghdr::*, socket_type s,
  1000. void* data, size_t size, int flags, void* addr, std::size_t* addrlen)
  1001. {
  1002. SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0;
  1003. signed_size_type result = ::recvfrom(s, static_cast<char*>(data), size,
  1004. flags, static_cast<socket_addr_type*>(addr), addrlen ? &tmp_addrlen : 0);
  1005. if (addrlen)
  1006. *addrlen = (std::size_t)tmp_addrlen;
  1007. return result;
  1008. }
  1009. signed_size_type recvfrom1(socket_type s, void* data, size_t size,
  1010. int flags, void* addr, std::size_t* addrlen, boost::system::error_code& ec)
  1011. {
  1012. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1013. // Receive some data.
  1014. WSABUF buf;
  1015. buf.buf = static_cast<char*>(data);
  1016. buf.len = static_cast<ULONG>(size);
  1017. DWORD bytes_transferred = 0;
  1018. DWORD recv_flags = flags;
  1019. int tmp_addrlen = (int)*addrlen;
  1020. int result = ::WSARecvFrom(s, &buf, 1, &bytes_transferred, &recv_flags,
  1021. static_cast<socket_addr_type*>(addr), &tmp_addrlen, 0, 0);
  1022. get_last_error(ec, true);
  1023. *addrlen = (std::size_t)tmp_addrlen;
  1024. if (ec.value() == ERROR_NETNAME_DELETED)
  1025. ec = boost::asio::error::connection_reset;
  1026. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1027. ec = boost::asio::error::connection_refused;
  1028. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  1029. result = 0;
  1030. if (result != 0)
  1031. return socket_error_retval;
  1032. boost::asio::error::clear(ec);
  1033. return bytes_transferred;
  1034. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1035. signed_size_type result = call_recvfrom(&msghdr::msg_namelen,
  1036. s, data, size, flags, addr, addrlen);
  1037. get_last_error(ec, result < 0);
  1038. return result;
  1039. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1040. }
  1041. size_t sync_recvfrom(socket_type s, state_type state, buf* bufs, size_t count,
  1042. int flags, void* addr, std::size_t* addrlen, boost::system::error_code& ec)
  1043. {
  1044. if (s == invalid_socket)
  1045. {
  1046. ec = boost::asio::error::bad_descriptor;
  1047. return 0;
  1048. }
  1049. // Read some data.
  1050. for (;;)
  1051. {
  1052. // Try to complete the operation without blocking.
  1053. signed_size_type bytes = socket_ops::recvfrom(
  1054. s, bufs, count, flags, addr, addrlen, ec);
  1055. // Check if operation succeeded.
  1056. if (bytes >= 0)
  1057. return bytes;
  1058. // Operation failed.
  1059. if ((state & user_set_non_blocking)
  1060. || (ec != boost::asio::error::would_block
  1061. && ec != boost::asio::error::try_again))
  1062. return 0;
  1063. // Wait for socket to become ready.
  1064. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  1065. return 0;
  1066. }
  1067. }
  1068. size_t sync_recvfrom1(socket_type s, state_type state, void* data, size_t size,
  1069. int flags, void* addr, std::size_t* addrlen, boost::system::error_code& ec)
  1070. {
  1071. if (s == invalid_socket)
  1072. {
  1073. ec = boost::asio::error::bad_descriptor;
  1074. return 0;
  1075. }
  1076. // Read some data.
  1077. for (;;)
  1078. {
  1079. // Try to complete the operation without blocking.
  1080. signed_size_type bytes = socket_ops::recvfrom1(
  1081. s, data, size, flags, addr, addrlen, ec);
  1082. // Check if operation succeeded.
  1083. if (bytes >= 0)
  1084. return bytes;
  1085. // Operation failed.
  1086. if ((state & user_set_non_blocking)
  1087. || (ec != boost::asio::error::would_block
  1088. && ec != boost::asio::error::try_again))
  1089. return 0;
  1090. // Wait for socket to become ready.
  1091. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  1092. return 0;
  1093. }
  1094. }
  1095. #if defined(BOOST_ASIO_HAS_IOCP)
  1096. void complete_iocp_recvfrom(
  1097. const weak_cancel_token_type& cancel_token,
  1098. boost::system::error_code& ec)
  1099. {
  1100. // Map non-portable errors to their portable counterparts.
  1101. if (ec.value() == ERROR_NETNAME_DELETED)
  1102. {
  1103. if (cancel_token.expired())
  1104. ec = boost::asio::error::operation_aborted;
  1105. else
  1106. ec = boost::asio::error::connection_reset;
  1107. }
  1108. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1109. {
  1110. ec = boost::asio::error::connection_refused;
  1111. }
  1112. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  1113. {
  1114. boost::asio::error::clear(ec);
  1115. }
  1116. }
  1117. #else // defined(BOOST_ASIO_HAS_IOCP)
  1118. bool non_blocking_recvfrom(socket_type s, buf* bufs,
  1119. size_t count, int flags, void* addr, std::size_t* addrlen,
  1120. boost::system::error_code& ec, size_t& bytes_transferred)
  1121. {
  1122. for (;;)
  1123. {
  1124. // Read some data.
  1125. signed_size_type bytes = socket_ops::recvfrom(
  1126. s, bufs, count, flags, addr, addrlen, ec);
  1127. // Check if operation succeeded.
  1128. if (bytes >= 0)
  1129. {
  1130. bytes_transferred = bytes;
  1131. return true;
  1132. }
  1133. // Retry operation if interrupted by signal.
  1134. if (ec == boost::asio::error::interrupted)
  1135. continue;
  1136. // Check if we need to run the operation again.
  1137. if (ec == boost::asio::error::would_block
  1138. || ec == boost::asio::error::try_again)
  1139. return false;
  1140. // Operation failed.
  1141. bytes_transferred = 0;
  1142. return true;
  1143. }
  1144. }
  1145. bool non_blocking_recvfrom1(socket_type s, void* data,
  1146. size_t size, int flags, void* addr, std::size_t* addrlen,
  1147. boost::system::error_code& ec, size_t& bytes_transferred)
  1148. {
  1149. for (;;)
  1150. {
  1151. // Read some data.
  1152. signed_size_type bytes = socket_ops::recvfrom1(
  1153. s, data, size, flags, addr, addrlen, ec);
  1154. // Check if operation succeeded.
  1155. if (bytes >= 0)
  1156. {
  1157. bytes_transferred = bytes;
  1158. return true;
  1159. }
  1160. // Retry operation if interrupted by signal.
  1161. if (ec == boost::asio::error::interrupted)
  1162. continue;
  1163. // Check if we need to run the operation again.
  1164. if (ec == boost::asio::error::would_block
  1165. || ec == boost::asio::error::try_again)
  1166. return false;
  1167. // Operation failed.
  1168. bytes_transferred = 0;
  1169. return true;
  1170. }
  1171. }
  1172. #endif // defined(BOOST_ASIO_HAS_IOCP)
  1173. signed_size_type recvmsg(socket_type s, buf* bufs, size_t count,
  1174. int in_flags, int& out_flags, boost::system::error_code& ec)
  1175. {
  1176. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1177. out_flags = 0;
  1178. return socket_ops::recv(s, bufs, count, in_flags, ec);
  1179. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1180. msghdr msg = msghdr();
  1181. msg.msg_iov = bufs;
  1182. msg.msg_iovlen = static_cast<int>(count);
  1183. signed_size_type result = ::recvmsg(s, &msg, in_flags);
  1184. get_last_error(ec, result < 0);
  1185. if (result >= 0)
  1186. out_flags = msg.msg_flags;
  1187. else
  1188. out_flags = 0;
  1189. return result;
  1190. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1191. }
  1192. size_t sync_recvmsg(socket_type s, state_type state,
  1193. buf* bufs, size_t count, int in_flags, int& out_flags,
  1194. boost::system::error_code& ec)
  1195. {
  1196. if (s == invalid_socket)
  1197. {
  1198. ec = boost::asio::error::bad_descriptor;
  1199. return 0;
  1200. }
  1201. // Read some data.
  1202. for (;;)
  1203. {
  1204. // Try to complete the operation without blocking.
  1205. signed_size_type bytes = socket_ops::recvmsg(
  1206. s, bufs, count, in_flags, out_flags, ec);
  1207. // Check if operation succeeded.
  1208. if (bytes >= 0)
  1209. return bytes;
  1210. // Operation failed.
  1211. if ((state & user_set_non_blocking)
  1212. || (ec != boost::asio::error::would_block
  1213. && ec != boost::asio::error::try_again))
  1214. return 0;
  1215. // Wait for socket to become ready.
  1216. if (socket_ops::poll_read(s, 0, -1, ec) < 0)
  1217. return 0;
  1218. }
  1219. }
  1220. #if defined(BOOST_ASIO_HAS_IOCP)
  1221. void complete_iocp_recvmsg(
  1222. const weak_cancel_token_type& cancel_token,
  1223. boost::system::error_code& ec)
  1224. {
  1225. // Map non-portable errors to their portable counterparts.
  1226. if (ec.value() == ERROR_NETNAME_DELETED)
  1227. {
  1228. if (cancel_token.expired())
  1229. ec = boost::asio::error::operation_aborted;
  1230. else
  1231. ec = boost::asio::error::connection_reset;
  1232. }
  1233. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1234. {
  1235. ec = boost::asio::error::connection_refused;
  1236. }
  1237. else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
  1238. {
  1239. boost::asio::error::clear(ec);
  1240. }
  1241. }
  1242. #else // defined(BOOST_ASIO_HAS_IOCP)
  1243. bool non_blocking_recvmsg(socket_type s,
  1244. buf* bufs, size_t count, int in_flags, int& out_flags,
  1245. boost::system::error_code& ec, size_t& bytes_transferred)
  1246. {
  1247. for (;;)
  1248. {
  1249. // Read some data.
  1250. signed_size_type bytes = socket_ops::recvmsg(
  1251. s, bufs, count, in_flags, out_flags, ec);
  1252. // Check if operation succeeded.
  1253. if (bytes >= 0)
  1254. {
  1255. bytes_transferred = bytes;
  1256. return true;
  1257. }
  1258. // Retry operation if interrupted by signal.
  1259. if (ec == boost::asio::error::interrupted)
  1260. continue;
  1261. // Check if we need to run the operation again.
  1262. if (ec == boost::asio::error::would_block
  1263. || ec == boost::asio::error::try_again)
  1264. return false;
  1265. // Operation failed.
  1266. bytes_transferred = 0;
  1267. return true;
  1268. }
  1269. }
  1270. #endif // defined(BOOST_ASIO_HAS_IOCP)
  1271. signed_size_type send(socket_type s, const buf* bufs, size_t count,
  1272. int flags, boost::system::error_code& ec)
  1273. {
  1274. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1275. // Send the data.
  1276. DWORD send_buf_count = static_cast<DWORD>(count);
  1277. DWORD bytes_transferred = 0;
  1278. DWORD send_flags = flags;
  1279. int result = ::WSASend(s, const_cast<buf*>(bufs),
  1280. send_buf_count, &bytes_transferred, send_flags, 0, 0);
  1281. get_last_error(ec, true);
  1282. if (ec.value() == ERROR_NETNAME_DELETED)
  1283. ec = boost::asio::error::connection_reset;
  1284. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1285. ec = boost::asio::error::connection_refused;
  1286. if (result != 0)
  1287. return socket_error_retval;
  1288. boost::asio::error::clear(ec);
  1289. return bytes_transferred;
  1290. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1291. msghdr msg = msghdr();
  1292. msg.msg_iov = const_cast<buf*>(bufs);
  1293. msg.msg_iovlen = static_cast<int>(count);
  1294. #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1295. flags |= MSG_NOSIGNAL;
  1296. #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1297. signed_size_type result = ::sendmsg(s, &msg, flags);
  1298. get_last_error(ec, result < 0);
  1299. return result;
  1300. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1301. }
  1302. signed_size_type send1(socket_type s, const void* data, size_t size,
  1303. int flags, boost::system::error_code& ec)
  1304. {
  1305. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1306. // Send the data.
  1307. WSABUF buf;
  1308. buf.buf = const_cast<char*>(static_cast<const char*>(data));
  1309. buf.len = static_cast<ULONG>(size);
  1310. DWORD bytes_transferred = 0;
  1311. DWORD send_flags = flags;
  1312. int result = ::WSASend(s, &buf, 1,
  1313. &bytes_transferred, send_flags, 0, 0);
  1314. get_last_error(ec, true);
  1315. if (ec.value() == ERROR_NETNAME_DELETED)
  1316. ec = boost::asio::error::connection_reset;
  1317. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1318. ec = boost::asio::error::connection_refused;
  1319. if (result != 0)
  1320. return socket_error_retval;
  1321. boost::asio::error::clear(ec);
  1322. return bytes_transferred;
  1323. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1324. #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1325. flags |= MSG_NOSIGNAL;
  1326. #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1327. signed_size_type result = ::send(s,
  1328. static_cast<const char*>(data), size, flags);
  1329. get_last_error(ec, result < 0);
  1330. return result;
  1331. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1332. }
  1333. size_t sync_send(socket_type s, state_type state, const buf* bufs,
  1334. size_t count, int flags, bool all_empty, boost::system::error_code& ec)
  1335. {
  1336. if (s == invalid_socket)
  1337. {
  1338. ec = boost::asio::error::bad_descriptor;
  1339. return 0;
  1340. }
  1341. // A request to write 0 bytes to a stream is a no-op.
  1342. if (all_empty && (state & stream_oriented))
  1343. {
  1344. boost::asio::error::clear(ec);
  1345. return 0;
  1346. }
  1347. // Read some data.
  1348. for (;;)
  1349. {
  1350. // Try to complete the operation without blocking.
  1351. signed_size_type bytes = socket_ops::send(s, bufs, count, flags, ec);
  1352. // Check if operation succeeded.
  1353. if (bytes >= 0)
  1354. return bytes;
  1355. // Operation failed.
  1356. if ((state & user_set_non_blocking)
  1357. || (ec != boost::asio::error::would_block
  1358. && ec != boost::asio::error::try_again))
  1359. return 0;
  1360. // Wait for socket to become ready.
  1361. if (socket_ops::poll_write(s, 0, -1, ec) < 0)
  1362. return 0;
  1363. }
  1364. }
  1365. size_t sync_send1(socket_type s, state_type state, const void* data,
  1366. size_t size, int flags, boost::system::error_code& ec)
  1367. {
  1368. if (s == invalid_socket)
  1369. {
  1370. ec = boost::asio::error::bad_descriptor;
  1371. return 0;
  1372. }
  1373. // A request to write 0 bytes to a stream is a no-op.
  1374. if (size == 0 && (state & stream_oriented))
  1375. {
  1376. boost::asio::error::clear(ec);
  1377. return 0;
  1378. }
  1379. // Read some data.
  1380. for (;;)
  1381. {
  1382. // Try to complete the operation without blocking.
  1383. signed_size_type bytes = socket_ops::send1(s, data, size, flags, ec);
  1384. // Check if operation succeeded.
  1385. if (bytes >= 0)
  1386. return bytes;
  1387. // Operation failed.
  1388. if ((state & user_set_non_blocking)
  1389. || (ec != boost::asio::error::would_block
  1390. && ec != boost::asio::error::try_again))
  1391. return 0;
  1392. // Wait for socket to become ready.
  1393. if (socket_ops::poll_write(s, 0, -1, ec) < 0)
  1394. return 0;
  1395. }
  1396. }
  1397. #if defined(BOOST_ASIO_HAS_IOCP)
  1398. void complete_iocp_send(
  1399. const weak_cancel_token_type& cancel_token,
  1400. boost::system::error_code& ec)
  1401. {
  1402. // Map non-portable errors to their portable counterparts.
  1403. if (ec.value() == ERROR_NETNAME_DELETED)
  1404. {
  1405. if (cancel_token.expired())
  1406. ec = boost::asio::error::operation_aborted;
  1407. else
  1408. ec = boost::asio::error::connection_reset;
  1409. }
  1410. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1411. {
  1412. ec = boost::asio::error::connection_refused;
  1413. }
  1414. }
  1415. #else // defined(BOOST_ASIO_HAS_IOCP)
  1416. bool non_blocking_send(socket_type s,
  1417. const buf* bufs, size_t count, int flags,
  1418. boost::system::error_code& ec, size_t& bytes_transferred)
  1419. {
  1420. for (;;)
  1421. {
  1422. // Write some data.
  1423. signed_size_type bytes = socket_ops::send(s, bufs, count, flags, ec);
  1424. // Check if operation succeeded.
  1425. if (bytes >= 0)
  1426. {
  1427. bytes_transferred = bytes;
  1428. return true;
  1429. }
  1430. // Retry operation if interrupted by signal.
  1431. if (ec == boost::asio::error::interrupted)
  1432. continue;
  1433. // Check if we need to run the operation again.
  1434. if (ec == boost::asio::error::would_block
  1435. || ec == boost::asio::error::try_again)
  1436. return false;
  1437. // Operation failed.
  1438. bytes_transferred = 0;
  1439. return true;
  1440. }
  1441. }
  1442. bool non_blocking_send1(socket_type s,
  1443. const void* data, size_t size, int flags,
  1444. boost::system::error_code& ec, size_t& bytes_transferred)
  1445. {
  1446. for (;;)
  1447. {
  1448. // Write some data.
  1449. signed_size_type bytes = socket_ops::send1(s, data, size, flags, ec);
  1450. // Check if operation succeeded.
  1451. if (bytes >= 0)
  1452. {
  1453. bytes_transferred = bytes;
  1454. return true;
  1455. }
  1456. // Retry operation if interrupted by signal.
  1457. if (ec == boost::asio::error::interrupted)
  1458. continue;
  1459. // Check if we need to run the operation again.
  1460. if (ec == boost::asio::error::would_block
  1461. || ec == boost::asio::error::try_again)
  1462. return false;
  1463. // Operation failed.
  1464. bytes_transferred = 0;
  1465. return true;
  1466. }
  1467. }
  1468. #endif // defined(BOOST_ASIO_HAS_IOCP)
  1469. signed_size_type sendto(socket_type s, const buf* bufs,
  1470. size_t count, int flags, const void* addr,
  1471. std::size_t addrlen, boost::system::error_code& ec)
  1472. {
  1473. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1474. // Send the data.
  1475. DWORD send_buf_count = static_cast<DWORD>(count);
  1476. DWORD bytes_transferred = 0;
  1477. int result = ::WSASendTo(s, const_cast<buf*>(bufs),
  1478. send_buf_count, &bytes_transferred, flags,
  1479. static_cast<const socket_addr_type*>(addr),
  1480. static_cast<int>(addrlen), 0, 0);
  1481. get_last_error(ec, true);
  1482. if (ec.value() == ERROR_NETNAME_DELETED)
  1483. ec = boost::asio::error::connection_reset;
  1484. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1485. ec = boost::asio::error::connection_refused;
  1486. if (result != 0)
  1487. return socket_error_retval;
  1488. boost::asio::error::clear(ec);
  1489. return bytes_transferred;
  1490. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1491. msghdr msg = msghdr();
  1492. init_msghdr_msg_name(msg.msg_name, addr);
  1493. msg.msg_namelen = static_cast<int>(addrlen);
  1494. msg.msg_iov = const_cast<buf*>(bufs);
  1495. msg.msg_iovlen = static_cast<int>(count);
  1496. #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1497. flags |= MSG_NOSIGNAL;
  1498. #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1499. signed_size_type result = ::sendmsg(s, &msg, flags);
  1500. get_last_error(ec, result < 0);
  1501. return result;
  1502. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1503. }
  1504. template <typename SockLenType>
  1505. inline signed_size_type call_sendto(SockLenType msghdr::*,
  1506. socket_type s, const void* data, size_t size, int flags,
  1507. const void* addr, std::size_t addrlen)
  1508. {
  1509. return ::sendto(s, static_cast<char*>(const_cast<void*>(data)), size, flags,
  1510. static_cast<const socket_addr_type*>(addr), (SockLenType)addrlen);
  1511. }
  1512. signed_size_type sendto1(socket_type s, const void* data,
  1513. size_t size, int flags, const void* addr,
  1514. std::size_t addrlen, boost::system::error_code& ec)
  1515. {
  1516. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1517. // Send the data.
  1518. WSABUF buf;
  1519. buf.buf = const_cast<char*>(static_cast<const char*>(data));
  1520. buf.len = static_cast<ULONG>(size);
  1521. DWORD bytes_transferred = 0;
  1522. int result = ::WSASendTo(s, &buf, 1, &bytes_transferred, flags,
  1523. static_cast<const socket_addr_type*>(addr),
  1524. static_cast<int>(addrlen), 0, 0);
  1525. get_last_error(ec, true);
  1526. if (ec.value() == ERROR_NETNAME_DELETED)
  1527. ec = boost::asio::error::connection_reset;
  1528. else if (ec.value() == ERROR_PORT_UNREACHABLE)
  1529. ec = boost::asio::error::connection_refused;
  1530. if (result != 0)
  1531. return socket_error_retval;
  1532. boost::asio::error::clear(ec);
  1533. return bytes_transferred;
  1534. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1535. #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1536. flags |= MSG_NOSIGNAL;
  1537. #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
  1538. signed_size_type result = call_sendto(&msghdr::msg_namelen,
  1539. s, data, size, flags, addr, addrlen);
  1540. get_last_error(ec, result < 0);
  1541. return result;
  1542. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1543. }
  1544. size_t sync_sendto(socket_type s, state_type state,
  1545. const buf* bufs, size_t count, int flags, const void* addr,
  1546. std::size_t addrlen, boost::system::error_code& ec)
  1547. {
  1548. if (s == invalid_socket)
  1549. {
  1550. ec = boost::asio::error::bad_descriptor;
  1551. return 0;
  1552. }
  1553. // Write some data.
  1554. for (;;)
  1555. {
  1556. // Try to complete the operation without blocking.
  1557. signed_size_type bytes = socket_ops::sendto(
  1558. s, bufs, count, flags, addr, addrlen, ec);
  1559. // Check if operation succeeded.
  1560. if (bytes >= 0)
  1561. return bytes;
  1562. // Operation failed.
  1563. if ((state & user_set_non_blocking)
  1564. || (ec != boost::asio::error::would_block
  1565. && ec != boost::asio::error::try_again))
  1566. return 0;
  1567. // Wait for socket to become ready.
  1568. if (socket_ops::poll_write(s, 0, -1, ec) < 0)
  1569. return 0;
  1570. }
  1571. }
  1572. size_t sync_sendto1(socket_type s, state_type state,
  1573. const void* data, size_t size, int flags, const void* addr,
  1574. std::size_t addrlen, boost::system::error_code& ec)
  1575. {
  1576. if (s == invalid_socket)
  1577. {
  1578. ec = boost::asio::error::bad_descriptor;
  1579. return 0;
  1580. }
  1581. // Write some data.
  1582. for (;;)
  1583. {
  1584. // Try to complete the operation without blocking.
  1585. signed_size_type bytes = socket_ops::sendto1(
  1586. s, data, size, flags, addr, addrlen, ec);
  1587. // Check if operation succeeded.
  1588. if (bytes >= 0)
  1589. return bytes;
  1590. // Operation failed.
  1591. if ((state & user_set_non_blocking)
  1592. || (ec != boost::asio::error::would_block
  1593. && ec != boost::asio::error::try_again))
  1594. return 0;
  1595. // Wait for socket to become ready.
  1596. if (socket_ops::poll_write(s, 0, -1, ec) < 0)
  1597. return 0;
  1598. }
  1599. }
  1600. #if !defined(BOOST_ASIO_HAS_IOCP)
  1601. bool non_blocking_sendto(socket_type s,
  1602. const buf* bufs, size_t count, int flags,
  1603. const void* addr, std::size_t addrlen,
  1604. boost::system::error_code& ec, size_t& bytes_transferred)
  1605. {
  1606. for (;;)
  1607. {
  1608. // Write some data.
  1609. signed_size_type bytes = socket_ops::sendto(
  1610. s, bufs, count, flags, addr, addrlen, ec);
  1611. // Check if operation succeeded.
  1612. if (bytes >= 0)
  1613. {
  1614. bytes_transferred = bytes;
  1615. return true;
  1616. }
  1617. // Retry operation if interrupted by signal.
  1618. if (ec == boost::asio::error::interrupted)
  1619. continue;
  1620. // Check if we need to run the operation again.
  1621. if (ec == boost::asio::error::would_block
  1622. || ec == boost::asio::error::try_again)
  1623. return false;
  1624. // Operation failed.
  1625. bytes_transferred = 0;
  1626. return true;
  1627. }
  1628. }
  1629. bool non_blocking_sendto1(socket_type s,
  1630. const void* data, size_t size, int flags,
  1631. const void* addr, std::size_t addrlen,
  1632. boost::system::error_code& ec, size_t& bytes_transferred)
  1633. {
  1634. for (;;)
  1635. {
  1636. // Write some data.
  1637. signed_size_type bytes = socket_ops::sendto1(
  1638. s, data, size, flags, addr, addrlen, ec);
  1639. // Check if operation succeeded.
  1640. if (bytes >= 0)
  1641. {
  1642. bytes_transferred = bytes;
  1643. return true;
  1644. }
  1645. // Retry operation if interrupted by signal.
  1646. if (ec == boost::asio::error::interrupted)
  1647. continue;
  1648. // Check if we need to run the operation again.
  1649. if (ec == boost::asio::error::would_block
  1650. || ec == boost::asio::error::try_again)
  1651. return false;
  1652. // Operation failed.
  1653. bytes_transferred = 0;
  1654. return true;
  1655. }
  1656. }
  1657. #endif // !defined(BOOST_ASIO_HAS_IOCP)
  1658. socket_type socket(int af, int type, int protocol,
  1659. boost::system::error_code& ec)
  1660. {
  1661. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1662. socket_type s = ::WSASocketW(af, type, protocol, 0, 0, WSA_FLAG_OVERLAPPED);
  1663. get_last_error(ec, s == invalid_socket);
  1664. if (s == invalid_socket)
  1665. return s;
  1666. if (af == BOOST_ASIO_OS_DEF(AF_INET6))
  1667. {
  1668. // Try to enable the POSIX default behaviour of having IPV6_V6ONLY set to
  1669. // false. This will only succeed on Windows Vista and later versions of
  1670. // Windows, where a dual-stack IPv4/v6 implementation is available.
  1671. DWORD optval = 0;
  1672. ::setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
  1673. reinterpret_cast<const char*>(&optval), sizeof(optval));
  1674. }
  1675. return s;
  1676. #elif defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
  1677. socket_type s = ::socket(af, type, protocol);
  1678. get_last_error(ec, s == invalid_socket);
  1679. if (s == invalid_socket)
  1680. return s;
  1681. int optval = 1;
  1682. int result = ::setsockopt(s, SOL_SOCKET,
  1683. SO_NOSIGPIPE, &optval, sizeof(optval));
  1684. get_last_error(ec, result != 0);
  1685. if (result != 0)
  1686. {
  1687. ::close(s);
  1688. return invalid_socket;
  1689. }
  1690. return s;
  1691. #else
  1692. int s = ::socket(af, type, protocol);
  1693. get_last_error(ec, s < 0);
  1694. return s;
  1695. #endif
  1696. }
  1697. template <typename SockLenType>
  1698. inline int call_setsockopt(SockLenType msghdr::*,
  1699. socket_type s, int level, int optname,
  1700. const void* optval, std::size_t optlen)
  1701. {
  1702. return ::setsockopt(s, level, optname,
  1703. (const char*)optval, (SockLenType)optlen);
  1704. }
  1705. int setsockopt(socket_type s, state_type& state, int level, int optname,
  1706. const void* optval, std::size_t optlen, boost::system::error_code& ec)
  1707. {
  1708. if (s == invalid_socket)
  1709. {
  1710. ec = boost::asio::error::bad_descriptor;
  1711. return socket_error_retval;
  1712. }
  1713. if (level == custom_socket_option_level && optname == always_fail_option)
  1714. {
  1715. ec = boost::asio::error::invalid_argument;
  1716. return socket_error_retval;
  1717. }
  1718. if (level == custom_socket_option_level
  1719. && optname == enable_connection_aborted_option)
  1720. {
  1721. if (optlen != sizeof(int))
  1722. {
  1723. ec = boost::asio::error::invalid_argument;
  1724. return socket_error_retval;
  1725. }
  1726. if (*static_cast<const int*>(optval))
  1727. state |= enable_connection_aborted;
  1728. else
  1729. state &= ~enable_connection_aborted;
  1730. boost::asio::error::clear(ec);
  1731. return 0;
  1732. }
  1733. if (level == SOL_SOCKET && optname == SO_LINGER)
  1734. state |= user_set_linger;
  1735. #if defined(__BORLANDC__)
  1736. // Mysteriously, using the getsockopt and setsockopt functions directly with
  1737. // Borland C++ results in incorrect values being set and read. The bug can be
  1738. // worked around by using function addresses resolved with GetProcAddress.
  1739. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  1740. {
  1741. typedef int (WSAAPI *sso_t)(SOCKET, int, int, const char*, int);
  1742. if (sso_t sso = (sso_t)::GetProcAddress(winsock_module, "setsockopt"))
  1743. {
  1744. int result = sso(s, level, optname,
  1745. reinterpret_cast<const char*>(optval),
  1746. static_cast<int>(optlen));
  1747. get_last_error(ec, result != 0);
  1748. return result;
  1749. }
  1750. }
  1751. ec = boost::asio::error::fault;
  1752. return socket_error_retval;
  1753. #else // defined(__BORLANDC__)
  1754. int result = call_setsockopt(&msghdr::msg_namelen,
  1755. s, level, optname, optval, optlen);
  1756. get_last_error(ec, result != 0);
  1757. if (result == 0)
  1758. {
  1759. #if defined(__MACH__) && defined(__APPLE__) \
  1760. || defined(__NetBSD__) || defined(__FreeBSD__) \
  1761. || defined(__OpenBSD__) || defined(__QNX__)
  1762. // To implement portable behaviour for SO_REUSEADDR with UDP sockets we
  1763. // need to also set SO_REUSEPORT on BSD-based platforms.
  1764. if ((state & datagram_oriented)
  1765. && level == SOL_SOCKET && optname == SO_REUSEADDR)
  1766. {
  1767. call_setsockopt(&msghdr::msg_namelen, s,
  1768. SOL_SOCKET, SO_REUSEPORT, optval, optlen);
  1769. }
  1770. #endif
  1771. }
  1772. return result;
  1773. #endif // defined(__BORLANDC__)
  1774. }
  1775. template <typename SockLenType>
  1776. inline int call_getsockopt(SockLenType msghdr::*,
  1777. socket_type s, int level, int optname,
  1778. void* optval, std::size_t* optlen)
  1779. {
  1780. SockLenType tmp_optlen = (SockLenType)*optlen;
  1781. int result = ::getsockopt(s, level, optname, (char*)optval, &tmp_optlen);
  1782. *optlen = (std::size_t)tmp_optlen;
  1783. return result;
  1784. }
  1785. int getsockopt(socket_type s, state_type state, int level, int optname,
  1786. void* optval, size_t* optlen, boost::system::error_code& ec)
  1787. {
  1788. if (s == invalid_socket)
  1789. {
  1790. ec = boost::asio::error::bad_descriptor;
  1791. return socket_error_retval;
  1792. }
  1793. if (level == custom_socket_option_level && optname == always_fail_option)
  1794. {
  1795. ec = boost::asio::error::invalid_argument;
  1796. return socket_error_retval;
  1797. }
  1798. if (level == custom_socket_option_level
  1799. && optname == enable_connection_aborted_option)
  1800. {
  1801. if (*optlen != sizeof(int))
  1802. {
  1803. ec = boost::asio::error::invalid_argument;
  1804. return socket_error_retval;
  1805. }
  1806. *static_cast<int*>(optval) = (state & enable_connection_aborted) ? 1 : 0;
  1807. boost::asio::error::clear(ec);
  1808. return 0;
  1809. }
  1810. #if defined(__BORLANDC__)
  1811. // Mysteriously, using the getsockopt and setsockopt functions directly with
  1812. // Borland C++ results in incorrect values being set and read. The bug can be
  1813. // worked around by using function addresses resolved with GetProcAddress.
  1814. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  1815. {
  1816. typedef int (WSAAPI *gso_t)(SOCKET, int, int, char*, int*);
  1817. if (gso_t gso = (gso_t)::GetProcAddress(winsock_module, "getsockopt"))
  1818. {
  1819. int tmp_optlen = static_cast<int>(*optlen);
  1820. int result = gso(s, level, optname,
  1821. reinterpret_cast<char*>(optval), &tmp_optlen);
  1822. get_last_error(ec, result != 0);
  1823. *optlen = static_cast<size_t>(tmp_optlen);
  1824. if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
  1825. && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
  1826. {
  1827. // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are
  1828. // only supported on Windows Vista and later. To simplify program logic
  1829. // we will fake success of getting this option and specify that the
  1830. // value is non-zero (i.e. true). This corresponds to the behavior of
  1831. // IPv6 sockets on Windows platforms pre-Vista.
  1832. *static_cast<DWORD*>(optval) = 1;
  1833. boost::asio::error::clear(ec);
  1834. }
  1835. return result;
  1836. }
  1837. }
  1838. ec = boost::asio::error::fault;
  1839. return socket_error_retval;
  1840. #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1841. int result = call_getsockopt(&msghdr::msg_namelen,
  1842. s, level, optname, optval, optlen);
  1843. get_last_error(ec, result != 0);
  1844. if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
  1845. && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
  1846. {
  1847. // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are only
  1848. // supported on Windows Vista and later. To simplify program logic we will
  1849. // fake success of getting this option and specify that the value is
  1850. // non-zero (i.e. true). This corresponds to the behavior of IPv6 sockets
  1851. // on Windows platforms pre-Vista.
  1852. *static_cast<DWORD*>(optval) = 1;
  1853. boost::asio::error::clear(ec);
  1854. }
  1855. return result;
  1856. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1857. int result = call_getsockopt(&msghdr::msg_namelen,
  1858. s, level, optname, optval, optlen);
  1859. get_last_error(ec, result != 0);
  1860. #if defined(__linux__)
  1861. if (result == 0 && level == SOL_SOCKET && *optlen == sizeof(int)
  1862. && (optname == SO_SNDBUF || optname == SO_RCVBUF))
  1863. {
  1864. // On Linux, setting SO_SNDBUF or SO_RCVBUF to N actually causes the kernel
  1865. // to set the buffer size to N*2. Linux puts additional stuff into the
  1866. // buffers so that only about half is actually available to the application.
  1867. // The retrieved value is divided by 2 here to make it appear as though the
  1868. // correct value has been set.
  1869. *static_cast<int*>(optval) /= 2;
  1870. }
  1871. #endif // defined(__linux__)
  1872. return result;
  1873. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1874. }
  1875. template <typename SockLenType>
  1876. inline int call_getpeername(SockLenType msghdr::*,
  1877. socket_type s, void* addr, std::size_t* addrlen)
  1878. {
  1879. SockLenType tmp_addrlen = (SockLenType)*addrlen;
  1880. int result = ::getpeername(s,
  1881. static_cast<socket_addr_type*>(addr), &tmp_addrlen);
  1882. *addrlen = (std::size_t)tmp_addrlen;
  1883. return result;
  1884. }
  1885. int getpeername(socket_type s, void* addr, std::size_t* addrlen,
  1886. bool cached, boost::system::error_code& ec)
  1887. {
  1888. if (s == invalid_socket)
  1889. {
  1890. ec = boost::asio::error::bad_descriptor;
  1891. return socket_error_retval;
  1892. }
  1893. #if defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP) \
  1894. || defined(__CYGWIN__)
  1895. if (cached)
  1896. {
  1897. // Check if socket is still connected.
  1898. DWORD connect_time = 0;
  1899. size_t connect_time_len = sizeof(connect_time);
  1900. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_CONNECT_TIME,
  1901. &connect_time, &connect_time_len, ec) == socket_error_retval)
  1902. {
  1903. return socket_error_retval;
  1904. }
  1905. if (connect_time == 0xFFFFFFFF)
  1906. {
  1907. ec = boost::asio::error::not_connected;
  1908. return socket_error_retval;
  1909. }
  1910. // The cached value is still valid.
  1911. boost::asio::error::clear(ec);
  1912. return 0;
  1913. }
  1914. #else // defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP)
  1915. // || defined(__CYGWIN__)
  1916. (void)cached;
  1917. #endif // defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP)
  1918. // || defined(__CYGWIN__)
  1919. int result = call_getpeername(&msghdr::msg_namelen, s, addr, addrlen);
  1920. get_last_error(ec, result != 0);
  1921. return result;
  1922. }
  1923. template <typename SockLenType>
  1924. inline int call_getsockname(SockLenType msghdr::*,
  1925. socket_type s, void* addr, std::size_t* addrlen)
  1926. {
  1927. SockLenType tmp_addrlen = (SockLenType)*addrlen;
  1928. int result = ::getsockname(s,
  1929. static_cast<socket_addr_type*>(addr), &tmp_addrlen);
  1930. *addrlen = (std::size_t)tmp_addrlen;
  1931. return result;
  1932. }
  1933. int getsockname(socket_type s, void* addr,
  1934. std::size_t* addrlen, boost::system::error_code& ec)
  1935. {
  1936. if (s == invalid_socket)
  1937. {
  1938. ec = boost::asio::error::bad_descriptor;
  1939. return socket_error_retval;
  1940. }
  1941. int result = call_getsockname(&msghdr::msg_namelen, s, addr, addrlen);
  1942. get_last_error(ec, result != 0);
  1943. return result;
  1944. }
  1945. int ioctl(socket_type s, state_type& state, int cmd,
  1946. ioctl_arg_type* arg, boost::system::error_code& ec)
  1947. {
  1948. if (s == invalid_socket)
  1949. {
  1950. ec = boost::asio::error::bad_descriptor;
  1951. return socket_error_retval;
  1952. }
  1953. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1954. int result = ::ioctlsocket(s, cmd, arg);
  1955. #elif defined(__MACH__) && defined(__APPLE__) \
  1956. || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1957. int result = ::ioctl(s, static_cast<unsigned int>(cmd), arg);
  1958. #else
  1959. int result = ::ioctl(s, cmd, arg);
  1960. #endif
  1961. get_last_error(ec, result < 0);
  1962. if (result >= 0)
  1963. {
  1964. // When updating the non-blocking mode we always perform the ioctl syscall,
  1965. // even if the flags would otherwise indicate that the socket is already in
  1966. // the correct state. This ensures that the underlying socket is put into
  1967. // the state that has been requested by the user. If the ioctl syscall was
  1968. // successful then we need to update the flags to match.
  1969. if (cmd == static_cast<int>(FIONBIO))
  1970. {
  1971. if (*arg)
  1972. {
  1973. state |= user_set_non_blocking;
  1974. }
  1975. else
  1976. {
  1977. // Clearing the non-blocking mode always overrides any internally-set
  1978. // non-blocking flag. Any subsequent asynchronous operations will need
  1979. // to re-enable non-blocking I/O.
  1980. state &= ~(user_set_non_blocking | internal_non_blocking);
  1981. }
  1982. }
  1983. }
  1984. return result;
  1985. }
  1986. int select(int nfds, fd_set* readfds, fd_set* writefds,
  1987. fd_set* exceptfds, timeval* timeout, boost::system::error_code& ec)
  1988. {
  1989. #if defined(__EMSCRIPTEN__)
  1990. exceptfds = 0;
  1991. #endif // defined(__EMSCRIPTEN__)
  1992. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  1993. if (!readfds && !writefds && !exceptfds && timeout)
  1994. {
  1995. DWORD milliseconds = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
  1996. if (milliseconds == 0)
  1997. milliseconds = 1; // Force context switch.
  1998. ::Sleep(milliseconds);
  1999. boost::asio::error::clear(ec);
  2000. return 0;
  2001. }
  2002. // The select() call allows timeout values measured in microseconds, but the
  2003. // system clock (as wrapped by boost::posix_time::microsec_clock) typically
  2004. // has a resolution of 10 milliseconds. This can lead to a spinning select
  2005. // reactor, meaning increased CPU usage, when waiting for the earliest
  2006. // scheduled timeout if it's less than 10 milliseconds away. To avoid a tight
  2007. // spin we'll use a minimum timeout of 1 millisecond.
  2008. if (timeout && timeout->tv_sec == 0
  2009. && timeout->tv_usec > 0 && timeout->tv_usec < 1000)
  2010. timeout->tv_usec = 1000;
  2011. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2012. #if defined(__hpux) && defined(__SELECT)
  2013. timespec ts;
  2014. ts.tv_sec = timeout ? timeout->tv_sec : 0;
  2015. ts.tv_nsec = timeout ? timeout->tv_usec * 1000 : 0;
  2016. int result = ::pselect(nfds, readfds,
  2017. writefds, exceptfds, timeout ? &ts : 0, 0);
  2018. #else
  2019. int result = ::select(nfds, readfds, writefds, exceptfds, timeout);
  2020. #endif
  2021. get_last_error(ec, result < 0);
  2022. return result;
  2023. }
  2024. int poll_read(socket_type s, state_type state,
  2025. int msec, boost::system::error_code& ec)
  2026. {
  2027. if (s == invalid_socket)
  2028. {
  2029. ec = boost::asio::error::bad_descriptor;
  2030. return socket_error_retval;
  2031. }
  2032. #if defined(BOOST_ASIO_WINDOWS) \
  2033. || defined(__CYGWIN__) \
  2034. || defined(__SYMBIAN32__)
  2035. fd_set fds;
  2036. FD_ZERO(&fds);
  2037. FD_SET(s, &fds);
  2038. timeval timeout_obj;
  2039. timeval* timeout;
  2040. if (state & user_set_non_blocking)
  2041. {
  2042. timeout_obj.tv_sec = 0;
  2043. timeout_obj.tv_usec = 0;
  2044. timeout = &timeout_obj;
  2045. }
  2046. else if (msec >= 0)
  2047. {
  2048. timeout_obj.tv_sec = msec / 1000;
  2049. timeout_obj.tv_usec = (msec % 1000) * 1000;
  2050. timeout = &timeout_obj;
  2051. }
  2052. else
  2053. timeout = 0;
  2054. int result = ::select(s + 1, &fds, 0, 0, timeout);
  2055. get_last_error(ec, result < 0);
  2056. #else // defined(BOOST_ASIO_WINDOWS)
  2057. // || defined(__CYGWIN__)
  2058. // || defined(__SYMBIAN32__)
  2059. pollfd fds;
  2060. fds.fd = s;
  2061. fds.events = POLLIN;
  2062. fds.revents = 0;
  2063. int timeout = (state & user_set_non_blocking) ? 0 : msec;
  2064. int result = ::poll(&fds, 1, timeout);
  2065. get_last_error(ec, result < 0);
  2066. #endif // defined(BOOST_ASIO_WINDOWS)
  2067. // || defined(__CYGWIN__)
  2068. // || defined(__SYMBIAN32__)
  2069. if (result == 0)
  2070. if (state & user_set_non_blocking)
  2071. ec = boost::asio::error::would_block;
  2072. return result;
  2073. }
  2074. int poll_write(socket_type s, state_type state,
  2075. int msec, boost::system::error_code& ec)
  2076. {
  2077. if (s == invalid_socket)
  2078. {
  2079. ec = boost::asio::error::bad_descriptor;
  2080. return socket_error_retval;
  2081. }
  2082. #if defined(BOOST_ASIO_WINDOWS) \
  2083. || defined(__CYGWIN__) \
  2084. || defined(__SYMBIAN32__)
  2085. fd_set fds;
  2086. FD_ZERO(&fds);
  2087. FD_SET(s, &fds);
  2088. timeval timeout_obj;
  2089. timeval* timeout;
  2090. if (state & user_set_non_blocking)
  2091. {
  2092. timeout_obj.tv_sec = 0;
  2093. timeout_obj.tv_usec = 0;
  2094. timeout = &timeout_obj;
  2095. }
  2096. else if (msec >= 0)
  2097. {
  2098. timeout_obj.tv_sec = msec / 1000;
  2099. timeout_obj.tv_usec = (msec % 1000) * 1000;
  2100. timeout = &timeout_obj;
  2101. }
  2102. else
  2103. timeout = 0;
  2104. int result = ::select(s + 1, 0, &fds, 0, timeout);
  2105. get_last_error(ec, result < 0);
  2106. #else // defined(BOOST_ASIO_WINDOWS)
  2107. // || defined(__CYGWIN__)
  2108. // || defined(__SYMBIAN32__)
  2109. pollfd fds;
  2110. fds.fd = s;
  2111. fds.events = POLLOUT;
  2112. fds.revents = 0;
  2113. int timeout = (state & user_set_non_blocking) ? 0 : msec;
  2114. int result = ::poll(&fds, 1, timeout);
  2115. get_last_error(ec, result < 0);
  2116. #endif // defined(BOOST_ASIO_WINDOWS)
  2117. // || defined(__CYGWIN__)
  2118. // || defined(__SYMBIAN32__)
  2119. if (result == 0)
  2120. if (state & user_set_non_blocking)
  2121. ec = boost::asio::error::would_block;
  2122. return result;
  2123. }
  2124. int poll_error(socket_type s, state_type state,
  2125. int msec, boost::system::error_code& ec)
  2126. {
  2127. if (s == invalid_socket)
  2128. {
  2129. ec = boost::asio::error::bad_descriptor;
  2130. return socket_error_retval;
  2131. }
  2132. #if defined(BOOST_ASIO_WINDOWS) \
  2133. || defined(__CYGWIN__) \
  2134. || defined(__SYMBIAN32__)
  2135. fd_set fds;
  2136. FD_ZERO(&fds);
  2137. FD_SET(s, &fds);
  2138. timeval timeout_obj;
  2139. timeval* timeout;
  2140. if (state & user_set_non_blocking)
  2141. {
  2142. timeout_obj.tv_sec = 0;
  2143. timeout_obj.tv_usec = 0;
  2144. timeout = &timeout_obj;
  2145. }
  2146. else if (msec >= 0)
  2147. {
  2148. timeout_obj.tv_sec = msec / 1000;
  2149. timeout_obj.tv_usec = (msec % 1000) * 1000;
  2150. timeout = &timeout_obj;
  2151. }
  2152. else
  2153. timeout = 0;
  2154. int result = ::select(s + 1, 0, 0, &fds, timeout);
  2155. get_last_error(ec, result < 0);
  2156. #else // defined(BOOST_ASIO_WINDOWS)
  2157. // || defined(__CYGWIN__)
  2158. // || defined(__SYMBIAN32__)
  2159. pollfd fds;
  2160. fds.fd = s;
  2161. fds.events = POLLPRI | POLLERR | POLLHUP;
  2162. fds.revents = 0;
  2163. int timeout = (state & user_set_non_blocking) ? 0 : msec;
  2164. int result = ::poll(&fds, 1, timeout);
  2165. get_last_error(ec, result < 0);
  2166. #endif // defined(BOOST_ASIO_WINDOWS)
  2167. // || defined(__CYGWIN__)
  2168. // || defined(__SYMBIAN32__)
  2169. if (result == 0)
  2170. if (state & user_set_non_blocking)
  2171. ec = boost::asio::error::would_block;
  2172. return result;
  2173. }
  2174. int poll_connect(socket_type s, int msec, boost::system::error_code& ec)
  2175. {
  2176. if (s == invalid_socket)
  2177. {
  2178. ec = boost::asio::error::bad_descriptor;
  2179. return socket_error_retval;
  2180. }
  2181. #if defined(BOOST_ASIO_WINDOWS) \
  2182. || defined(__CYGWIN__) \
  2183. || defined(__SYMBIAN32__)
  2184. fd_set write_fds;
  2185. FD_ZERO(&write_fds);
  2186. FD_SET(s, &write_fds);
  2187. fd_set except_fds;
  2188. FD_ZERO(&except_fds);
  2189. FD_SET(s, &except_fds);
  2190. timeval timeout_obj;
  2191. timeval* timeout;
  2192. if (msec >= 0)
  2193. {
  2194. timeout_obj.tv_sec = msec / 1000;
  2195. timeout_obj.tv_usec = (msec % 1000) * 1000;
  2196. timeout = &timeout_obj;
  2197. }
  2198. else
  2199. timeout = 0;
  2200. int result = ::select(s + 1, 0, &write_fds, &except_fds, timeout);
  2201. get_last_error(ec, result < 0);
  2202. return result;
  2203. #else // defined(BOOST_ASIO_WINDOWS)
  2204. // || defined(__CYGWIN__)
  2205. // || defined(__SYMBIAN32__)
  2206. pollfd fds;
  2207. fds.fd = s;
  2208. fds.events = POLLOUT;
  2209. fds.revents = 0;
  2210. int result = ::poll(&fds, 1, msec);
  2211. get_last_error(ec, result < 0);
  2212. return result;
  2213. #endif // defined(BOOST_ASIO_WINDOWS)
  2214. // || defined(__CYGWIN__)
  2215. // || defined(__SYMBIAN32__)
  2216. }
  2217. #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2218. const char* inet_ntop(int af, const void* src, char* dest, size_t length,
  2219. unsigned long scope_id, boost::system::error_code& ec)
  2220. {
  2221. clear_last_error();
  2222. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2223. using namespace std; // For sprintf.
  2224. const unsigned char* bytes = static_cast<const unsigned char*>(src);
  2225. if (af == BOOST_ASIO_OS_DEF(AF_INET))
  2226. {
  2227. sprintf_s(dest, length, "%u.%u.%u.%u",
  2228. bytes[0], bytes[1], bytes[2], bytes[3]);
  2229. return dest;
  2230. }
  2231. else if (af == BOOST_ASIO_OS_DEF(AF_INET6))
  2232. {
  2233. size_t n = 0, b = 0, z = 0;
  2234. while (n < length && b < 16)
  2235. {
  2236. if (bytes[b] == 0 && bytes[b + 1] == 0 && z == 0)
  2237. {
  2238. do b += 2; while (b < 16 && bytes[b] == 0 && bytes[b + 1] == 0);
  2239. n += sprintf_s(dest + n, length - n, ":%s", b < 16 ? "" : ":"), ++z;
  2240. }
  2241. else
  2242. {
  2243. n += sprintf_s(dest + n, length - n, "%s%x", b ? ":" : "",
  2244. (static_cast<u_long_type>(bytes[b]) << 8) | bytes[b + 1]);
  2245. b += 2;
  2246. }
  2247. }
  2248. if (scope_id)
  2249. n += sprintf_s(dest + n, length - n, "%%%lu", scope_id);
  2250. return dest;
  2251. }
  2252. else
  2253. {
  2254. ec = boost::asio::error::address_family_not_supported;
  2255. return 0;
  2256. }
  2257. #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2258. using namespace std; // For memcpy.
  2259. if (af != BOOST_ASIO_OS_DEF(AF_INET) && af != BOOST_ASIO_OS_DEF(AF_INET6))
  2260. {
  2261. ec = boost::asio::error::address_family_not_supported;
  2262. return 0;
  2263. }
  2264. union
  2265. {
  2266. socket_addr_type base;
  2267. sockaddr_storage_type storage;
  2268. sockaddr_in4_type v4;
  2269. sockaddr_in6_type v6;
  2270. } address;
  2271. DWORD address_length;
  2272. if (af == BOOST_ASIO_OS_DEF(AF_INET))
  2273. {
  2274. address_length = sizeof(sockaddr_in4_type);
  2275. address.v4.sin_family = BOOST_ASIO_OS_DEF(AF_INET);
  2276. address.v4.sin_port = 0;
  2277. memcpy(&address.v4.sin_addr, src, sizeof(in4_addr_type));
  2278. }
  2279. else // AF_INET6
  2280. {
  2281. address_length = sizeof(sockaddr_in6_type);
  2282. address.v6.sin6_family = BOOST_ASIO_OS_DEF(AF_INET6);
  2283. address.v6.sin6_port = 0;
  2284. address.v6.sin6_flowinfo = 0;
  2285. address.v6.sin6_scope_id = scope_id;
  2286. memcpy(&address.v6.sin6_addr, src, sizeof(in6_addr_type));
  2287. }
  2288. DWORD string_length = static_cast<DWORD>(length);
  2289. #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
  2290. LPWSTR string_buffer = (LPWSTR)_alloca(length * sizeof(WCHAR));
  2291. int result = ::WSAAddressToStringW(&address.base,
  2292. address_length, 0, string_buffer, &string_length);
  2293. get_last_error(ec, true);
  2294. ::WideCharToMultiByte(CP_ACP, 0, string_buffer, -1,
  2295. dest, static_cast<int>(length), 0, 0);
  2296. #else
  2297. int result = ::WSAAddressToStringA(&address.base,
  2298. address_length, 0, dest, &string_length);
  2299. get_last_error(ec, true);
  2300. #endif
  2301. // Windows may set error code on success.
  2302. if (result != socket_error_retval)
  2303. boost::asio::error::clear(ec);
  2304. // Windows may not set an error code on failure.
  2305. else if (result == socket_error_retval && !ec)
  2306. ec = boost::asio::error::invalid_argument;
  2307. return result == socket_error_retval ? 0 : dest;
  2308. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2309. const char* result = ::inet_ntop(af, src, dest, static_cast<int>(length));
  2310. get_last_error(ec, true);
  2311. if (result == 0 && !ec)
  2312. ec = boost::asio::error::invalid_argument;
  2313. if (result != 0 && af == BOOST_ASIO_OS_DEF(AF_INET6) && scope_id != 0)
  2314. {
  2315. using namespace std; // For strcat and sprintf.
  2316. char if_name[(IF_NAMESIZE > 21 ? IF_NAMESIZE : 21) + 1] = "%";
  2317. const in6_addr_type* ipv6_address = static_cast<const in6_addr_type*>(src);
  2318. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  2319. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  2320. bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
  2321. && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
  2322. if ((!is_link_local && !is_multicast_link_local)
  2323. || if_indextoname(static_cast<unsigned>(scope_id), if_name + 1) == 0)
  2324. #if defined(BOOST_ASIO_HAS_SNPRINTF)
  2325. snprintf(if_name + 1, sizeof(if_name) - 1, "%lu", scope_id);
  2326. #elif defined(BOOST_ASIO_HAS_SECURE_RTL)
  2327. sprintf_s(if_name + 1, sizeof(if_name) -1, "%lu", scope_id);
  2328. #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
  2329. sprintf(if_name + 1, "%lu", scope_id);
  2330. #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
  2331. strcat(dest, if_name);
  2332. }
  2333. return result;
  2334. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2335. }
  2336. int inet_pton(int af, const char* src, void* dest,
  2337. unsigned long* scope_id, boost::system::error_code& ec)
  2338. {
  2339. clear_last_error();
  2340. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2341. using namespace std; // For sscanf.
  2342. unsigned char* bytes = static_cast<unsigned char*>(dest);
  2343. if (af == BOOST_ASIO_OS_DEF(AF_INET))
  2344. {
  2345. unsigned int b0, b1, b2, b3;
  2346. if (sscanf_s(src, "%u.%u.%u.%u", &b0, &b1, &b2, &b3) != 4)
  2347. {
  2348. ec = boost::asio::error::invalid_argument;
  2349. return -1;
  2350. }
  2351. if (b0 > 255 || b1 > 255 || b2 > 255 || b3 > 255)
  2352. {
  2353. ec = boost::asio::error::invalid_argument;
  2354. return -1;
  2355. }
  2356. bytes[0] = static_cast<unsigned char>(b0);
  2357. bytes[1] = static_cast<unsigned char>(b1);
  2358. bytes[2] = static_cast<unsigned char>(b2);
  2359. bytes[3] = static_cast<unsigned char>(b3);
  2360. boost::asio::error::clear(ec);
  2361. return 1;
  2362. }
  2363. else if (af == BOOST_ASIO_OS_DEF(AF_INET6))
  2364. {
  2365. unsigned char* bytes = static_cast<unsigned char*>(dest);
  2366. std::memset(bytes, 0, 16);
  2367. unsigned char back_bytes[16] = { 0 };
  2368. int num_front_bytes = 0, num_back_bytes = 0;
  2369. const char* p = src;
  2370. enum { fword, fcolon, bword, scope, done } state = fword;
  2371. unsigned long current_word = 0;
  2372. while (state != done)
  2373. {
  2374. if (current_word > 0xFFFF)
  2375. {
  2376. ec = boost::asio::error::invalid_argument;
  2377. return -1;
  2378. }
  2379. switch (state)
  2380. {
  2381. case fword:
  2382. if (*p >= '0' && *p <= '9')
  2383. current_word = current_word * 16 + *p++ - '0';
  2384. else if (*p >= 'a' && *p <= 'f')
  2385. current_word = current_word * 16 + *p++ - 'a' + 10;
  2386. else if (*p >= 'A' && *p <= 'F')
  2387. current_word = current_word * 16 + *p++ - 'A' + 10;
  2388. else
  2389. {
  2390. if (num_front_bytes == 16)
  2391. {
  2392. ec = boost::asio::error::invalid_argument;
  2393. return -1;
  2394. }
  2395. bytes[num_front_bytes++] = (current_word >> 8) & 0xFF;
  2396. bytes[num_front_bytes++] = current_word & 0xFF;
  2397. current_word = 0;
  2398. if (*p == ':')
  2399. state = fcolon, ++p;
  2400. else if (*p == '%')
  2401. state = scope, ++p;
  2402. else if (*p == 0)
  2403. state = done;
  2404. else
  2405. {
  2406. ec = boost::asio::error::invalid_argument;
  2407. return -1;
  2408. }
  2409. }
  2410. break;
  2411. case fcolon:
  2412. if (*p == ':')
  2413. state = bword, ++p;
  2414. else
  2415. state = fword;
  2416. break;
  2417. case bword:
  2418. if (*p >= '0' && *p <= '9')
  2419. current_word = current_word * 16 + *p++ - '0';
  2420. else if (*p >= 'a' && *p <= 'f')
  2421. current_word = current_word * 16 + *p++ - 'a' + 10;
  2422. else if (*p >= 'A' && *p <= 'F')
  2423. current_word = current_word * 16 + *p++ - 'A' + 10;
  2424. else
  2425. {
  2426. if (num_front_bytes + num_back_bytes == 16)
  2427. {
  2428. ec = boost::asio::error::invalid_argument;
  2429. return -1;
  2430. }
  2431. back_bytes[num_back_bytes++] = (current_word >> 8) & 0xFF;
  2432. back_bytes[num_back_bytes++] = current_word & 0xFF;
  2433. current_word = 0;
  2434. if (*p == ':')
  2435. state = bword, ++p;
  2436. else if (*p == '%')
  2437. state = scope, ++p;
  2438. else if (*p == 0)
  2439. state = done;
  2440. else
  2441. {
  2442. ec = boost::asio::error::invalid_argument;
  2443. return -1;
  2444. }
  2445. }
  2446. break;
  2447. case scope:
  2448. if (*p >= '0' && *p <= '9')
  2449. current_word = current_word * 10 + *p++ - '0';
  2450. else if (*p == 0)
  2451. *scope_id = current_word, state = done;
  2452. else
  2453. {
  2454. ec = boost::asio::error::invalid_argument;
  2455. return -1;
  2456. }
  2457. break;
  2458. default:
  2459. break;
  2460. }
  2461. }
  2462. for (int i = 0; i < num_back_bytes; ++i)
  2463. bytes[16 - num_back_bytes + i] = back_bytes[i];
  2464. boost::asio::error::clear(ec);
  2465. return 1;
  2466. }
  2467. else
  2468. {
  2469. ec = boost::asio::error::address_family_not_supported;
  2470. return -1;
  2471. }
  2472. #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2473. using namespace std; // For memcpy and strcmp.
  2474. if (af != BOOST_ASIO_OS_DEF(AF_INET) && af != BOOST_ASIO_OS_DEF(AF_INET6))
  2475. {
  2476. ec = boost::asio::error::address_family_not_supported;
  2477. return -1;
  2478. }
  2479. union
  2480. {
  2481. socket_addr_type base;
  2482. sockaddr_storage_type storage;
  2483. sockaddr_in4_type v4;
  2484. sockaddr_in6_type v6;
  2485. } address;
  2486. int address_length = sizeof(sockaddr_storage_type);
  2487. #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
  2488. int num_wide_chars = static_cast<int>(strlen(src)) + 1;
  2489. LPWSTR wide_buffer = (LPWSTR)_alloca(num_wide_chars * sizeof(WCHAR));
  2490. ::MultiByteToWideChar(CP_ACP, 0, src, -1, wide_buffer, num_wide_chars);
  2491. int result = ::WSAStringToAddressW(wide_buffer,
  2492. af, 0, &address.base, &address_length);
  2493. get_last_error(ec, true);
  2494. #else
  2495. int result = ::WSAStringToAddressA(const_cast<char*>(src),
  2496. af, 0, &address.base, &address_length);
  2497. get_last_error(ec, true);
  2498. #endif
  2499. if (af == BOOST_ASIO_OS_DEF(AF_INET))
  2500. {
  2501. if (result != socket_error_retval)
  2502. {
  2503. memcpy(dest, &address.v4.sin_addr, sizeof(in4_addr_type));
  2504. boost::asio::error::clear(ec);
  2505. }
  2506. else if (strcmp(src, "255.255.255.255") == 0)
  2507. {
  2508. static_cast<in4_addr_type*>(dest)->s_addr = INADDR_NONE;
  2509. boost::asio::error::clear(ec);
  2510. }
  2511. }
  2512. else // AF_INET6
  2513. {
  2514. if (result != socket_error_retval)
  2515. {
  2516. memcpy(dest, &address.v6.sin6_addr, sizeof(in6_addr_type));
  2517. if (scope_id)
  2518. *scope_id = address.v6.sin6_scope_id;
  2519. boost::asio::error::clear(ec);
  2520. }
  2521. }
  2522. // Windows may not set an error code on failure.
  2523. if (result == socket_error_retval && !ec)
  2524. ec = boost::asio::error::invalid_argument;
  2525. if (result != socket_error_retval)
  2526. boost::asio::error::clear(ec);
  2527. return result == socket_error_retval ? -1 : 1;
  2528. #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2529. using namespace std; // For strchr, memcpy and atoi.
  2530. // On some platforms, inet_pton fails if an address string contains a scope
  2531. // id. Detect and remove the scope id before passing the string to inet_pton.
  2532. const bool is_v6 = (af == BOOST_ASIO_OS_DEF(AF_INET6));
  2533. const char* if_name = is_v6 ? strchr(src, '%') : 0;
  2534. char src_buf[max_addr_v6_str_len + 1];
  2535. const char* src_ptr = src;
  2536. if (if_name != 0)
  2537. {
  2538. if (if_name - src > max_addr_v6_str_len)
  2539. {
  2540. ec = boost::asio::error::invalid_argument;
  2541. return 0;
  2542. }
  2543. memcpy(src_buf, src, if_name - src);
  2544. src_buf[if_name - src] = 0;
  2545. src_ptr = src_buf;
  2546. }
  2547. int result = ::inet_pton(af, src_ptr, dest);
  2548. get_last_error(ec, true);
  2549. if (result <= 0 && !ec)
  2550. ec = boost::asio::error::invalid_argument;
  2551. if (result > 0 && is_v6 && scope_id)
  2552. {
  2553. using namespace std; // For strchr and atoi.
  2554. *scope_id = 0;
  2555. if (if_name != 0)
  2556. {
  2557. in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest);
  2558. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  2559. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  2560. bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
  2561. && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
  2562. if (is_link_local || is_multicast_link_local)
  2563. *scope_id = if_nametoindex(if_name + 1);
  2564. if (*scope_id == 0)
  2565. *scope_id = atoi(if_name + 1);
  2566. }
  2567. }
  2568. return result;
  2569. #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2570. }
  2571. int gethostname(char* name, int namelen, boost::system::error_code& ec)
  2572. {
  2573. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2574. try
  2575. {
  2576. using namespace Windows::Foundation::Collections;
  2577. using namespace Windows::Networking;
  2578. using namespace Windows::Networking::Connectivity;
  2579. IVectorView<HostName^>^ hostnames = NetworkInformation::GetHostNames();
  2580. for (unsigned i = 0; i < hostnames->Size; ++i)
  2581. {
  2582. HostName^ hostname = hostnames->GetAt(i);
  2583. if (hostname->Type == HostNameType::DomainName)
  2584. {
  2585. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  2586. std::string raw_name = converter.to_bytes(hostname->RawName->Data());
  2587. if (namelen > 0 && raw_name.size() < static_cast<std::size_t>(namelen))
  2588. {
  2589. strcpy_s(name, namelen, raw_name.c_str());
  2590. return 0;
  2591. }
  2592. }
  2593. }
  2594. return -1;
  2595. }
  2596. catch (Platform::Exception^ e)
  2597. {
  2598. ec = boost::system::error_code(e->HResult,
  2599. boost::system::system_category());
  2600. return -1;
  2601. }
  2602. #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2603. int result = ::gethostname(name, namelen);
  2604. get_last_error(ec, result != 0);
  2605. return result;
  2606. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2607. }
  2608. #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  2609. #if !defined(BOOST_ASIO_HAS_GETADDRINFO)
  2610. // The following functions are only needed for emulation of getaddrinfo and
  2611. // getnameinfo.
  2612. inline boost::system::error_code translate_netdb_error(int error)
  2613. {
  2614. switch (error)
  2615. {
  2616. case 0:
  2617. return boost::system::error_code();
  2618. case HOST_NOT_FOUND:
  2619. return boost::asio::error::host_not_found;
  2620. case TRY_AGAIN:
  2621. return boost::asio::error::host_not_found_try_again;
  2622. case NO_RECOVERY:
  2623. return boost::asio::error::no_recovery;
  2624. case NO_DATA:
  2625. return boost::asio::error::no_data;
  2626. default:
  2627. BOOST_ASIO_ASSERT(false);
  2628. return boost::asio::error::invalid_argument;
  2629. }
  2630. }
  2631. inline hostent* gethostbyaddr(const char* addr, int length, int af,
  2632. hostent* result, char* buffer, int buflength, boost::system::error_code& ec)
  2633. {
  2634. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2635. (void)(buffer);
  2636. (void)(buflength);
  2637. hostent* retval = ::gethostbyaddr(addr, length, af);
  2638. get_last_error(ec, !retval);
  2639. if (!retval)
  2640. return 0;
  2641. *result = *retval;
  2642. return retval;
  2643. #elif defined(__sun) || defined(__QNX__)
  2644. int error = 0;
  2645. hostent* retval = ::gethostbyaddr_r(addr, length,
  2646. af, result, buffer, buflength, &error);
  2647. get_last_error(ec, !retval);
  2648. if (error)
  2649. ec = translate_netdb_error(error);
  2650. return retval;
  2651. #elif defined(__MACH__) && defined(__APPLE__)
  2652. (void)(buffer);
  2653. (void)(buflength);
  2654. int error = 0;
  2655. hostent* retval = ::getipnodebyaddr(addr, length, af, &error);
  2656. get_last_error(ec, !retval);
  2657. if (error)
  2658. ec = translate_netdb_error(error);
  2659. if (!retval)
  2660. return 0;
  2661. *result = *retval;
  2662. return retval;
  2663. #else
  2664. hostent* retval = 0;
  2665. int error = 0;
  2666. clear_last_error();
  2667. ::gethostbyaddr_r(addr, length, af, result,
  2668. buffer, buflength, &retval, &error);
  2669. get_last_error(ec, true);
  2670. if (error)
  2671. ec = translate_netdb_error(error);
  2672. return retval;
  2673. #endif
  2674. }
  2675. inline hostent* gethostbyname(const char* name, int af, struct hostent* result,
  2676. char* buffer, int buflength, int ai_flags, boost::system::error_code& ec)
  2677. {
  2678. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  2679. (void)(buffer);
  2680. (void)(buflength);
  2681. (void)(ai_flags);
  2682. if (af != BOOST_ASIO_OS_DEF(AF_INET))
  2683. {
  2684. ec = boost::asio::error::address_family_not_supported;
  2685. return 0;
  2686. }
  2687. hostent* retval = ::gethostbyname(name);
  2688. get_last_error(ec, !retval);
  2689. if (!retval)
  2690. return 0;
  2691. *result = *retval;
  2692. return result;
  2693. #elif defined(__sun) || defined(__QNX__)
  2694. (void)(ai_flags);
  2695. if (af != BOOST_ASIO_OS_DEF(AF_INET))
  2696. {
  2697. ec = boost::asio::error::address_family_not_supported;
  2698. return 0;
  2699. }
  2700. int error = 0;
  2701. hostent* retval = ::gethostbyname_r(name, result, buffer, buflength, &error);
  2702. get_last_error(ec, !retval);
  2703. if (error)
  2704. ec = translate_netdb_error(error);
  2705. return retval;
  2706. #elif defined(__MACH__) && defined(__APPLE__)
  2707. (void)(buffer);
  2708. (void)(buflength);
  2709. int error = 0;
  2710. hostent* retval = ::getipnodebyname(name, af, ai_flags, &error);
  2711. get_last_error(ec, !retval);
  2712. if (error)
  2713. ec = translate_netdb_error(error);
  2714. if (!retval)
  2715. return 0;
  2716. *result = *retval;
  2717. return retval;
  2718. #else
  2719. (void)(ai_flags);
  2720. if (af != BOOST_ASIO_OS_DEF(AF_INET))
  2721. {
  2722. ec = boost::asio::error::address_family_not_supported;
  2723. return 0;
  2724. }
  2725. hostent* retval = 0;
  2726. int error = 0;
  2727. clear_last_error();
  2728. ::gethostbyname_r(name, result, buffer, buflength, &retval, &error);
  2729. get_last_error(ec, true);
  2730. if (error)
  2731. ec = translate_netdb_error(error);
  2732. return retval;
  2733. #endif
  2734. }
  2735. inline void freehostent(hostent* h)
  2736. {
  2737. #if defined(__MACH__) && defined(__APPLE__)
  2738. if (h)
  2739. ::freehostent(h);
  2740. #else
  2741. (void)(h);
  2742. #endif
  2743. }
  2744. // Emulation of getaddrinfo based on implementation in:
  2745. // Stevens, W. R., UNIX Network Programming Vol. 1, 2nd Ed., Prentice-Hall 1998.
  2746. struct gai_search
  2747. {
  2748. const char* host;
  2749. int family;
  2750. };
  2751. inline int gai_nsearch(const char* host,
  2752. const addrinfo_type* hints, gai_search (&search)[2])
  2753. {
  2754. int search_count = 0;
  2755. if (host == 0 || host[0] == '\0')
  2756. {
  2757. if (hints->ai_flags & AI_PASSIVE)
  2758. {
  2759. // No host and AI_PASSIVE implies wildcard bind.
  2760. switch (hints->ai_family)
  2761. {
  2762. case BOOST_ASIO_OS_DEF(AF_INET):
  2763. search[search_count].host = "0.0.0.0";
  2764. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2765. ++search_count;
  2766. break;
  2767. case BOOST_ASIO_OS_DEF(AF_INET6):
  2768. search[search_count].host = "0::0";
  2769. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2770. ++search_count;
  2771. break;
  2772. case BOOST_ASIO_OS_DEF(AF_UNSPEC):
  2773. search[search_count].host = "0::0";
  2774. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2775. ++search_count;
  2776. search[search_count].host = "0.0.0.0";
  2777. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2778. ++search_count;
  2779. break;
  2780. default:
  2781. break;
  2782. }
  2783. }
  2784. else
  2785. {
  2786. // No host and not AI_PASSIVE means connect to local host.
  2787. switch (hints->ai_family)
  2788. {
  2789. case BOOST_ASIO_OS_DEF(AF_INET):
  2790. search[search_count].host = "localhost";
  2791. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2792. ++search_count;
  2793. break;
  2794. case BOOST_ASIO_OS_DEF(AF_INET6):
  2795. search[search_count].host = "localhost";
  2796. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2797. ++search_count;
  2798. break;
  2799. case BOOST_ASIO_OS_DEF(AF_UNSPEC):
  2800. search[search_count].host = "localhost";
  2801. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2802. ++search_count;
  2803. search[search_count].host = "localhost";
  2804. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2805. ++search_count;
  2806. break;
  2807. default:
  2808. break;
  2809. }
  2810. }
  2811. }
  2812. else
  2813. {
  2814. // Host is specified.
  2815. switch (hints->ai_family)
  2816. {
  2817. case BOOST_ASIO_OS_DEF(AF_INET):
  2818. search[search_count].host = host;
  2819. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2820. ++search_count;
  2821. break;
  2822. case BOOST_ASIO_OS_DEF(AF_INET6):
  2823. search[search_count].host = host;
  2824. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2825. ++search_count;
  2826. break;
  2827. case BOOST_ASIO_OS_DEF(AF_UNSPEC):
  2828. search[search_count].host = host;
  2829. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
  2830. ++search_count;
  2831. search[search_count].host = host;
  2832. search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
  2833. ++search_count;
  2834. break;
  2835. default:
  2836. break;
  2837. }
  2838. }
  2839. return search_count;
  2840. }
  2841. template <typename T>
  2842. inline T* gai_alloc(std::size_t size = sizeof(T))
  2843. {
  2844. using namespace std;
  2845. T* p = static_cast<T*>(::operator new(size, std::nothrow));
  2846. if (p)
  2847. memset(p, 0, size);
  2848. return p;
  2849. }
  2850. inline void gai_free(void* p)
  2851. {
  2852. ::operator delete(p);
  2853. }
  2854. inline void gai_strcpy(char* target, const char* source, std::size_t max_size)
  2855. {
  2856. using namespace std;
  2857. #if defined(BOOST_ASIO_HAS_SECURE_RTL)
  2858. strcpy_s(target, max_size, source);
  2859. #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
  2860. *target = 0;
  2861. if (max_size > 0)
  2862. strncat(target, source, max_size - 1);
  2863. #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
  2864. }
  2865. enum { gai_clone_flag = 1 << 30 };
  2866. inline int gai_aistruct(addrinfo_type*** next, const addrinfo_type* hints,
  2867. const void* addr, int family)
  2868. {
  2869. using namespace std;
  2870. addrinfo_type* ai = gai_alloc<addrinfo_type>();
  2871. if (ai == 0)
  2872. return EAI_MEMORY;
  2873. ai->ai_next = 0;
  2874. **next = ai;
  2875. *next = &ai->ai_next;
  2876. ai->ai_canonname = 0;
  2877. ai->ai_socktype = hints->ai_socktype;
  2878. if (ai->ai_socktype == 0)
  2879. ai->ai_flags |= gai_clone_flag;
  2880. ai->ai_protocol = hints->ai_protocol;
  2881. ai->ai_family = family;
  2882. switch (ai->ai_family)
  2883. {
  2884. case BOOST_ASIO_OS_DEF(AF_INET):
  2885. {
  2886. sockaddr_in4_type* sinptr = gai_alloc<sockaddr_in4_type>();
  2887. if (sinptr == 0)
  2888. return EAI_MEMORY;
  2889. sinptr->sin_family = BOOST_ASIO_OS_DEF(AF_INET);
  2890. memcpy(&sinptr->sin_addr, addr, sizeof(in4_addr_type));
  2891. ai->ai_addr = reinterpret_cast<sockaddr*>(sinptr);
  2892. ai->ai_addrlen = sizeof(sockaddr_in4_type);
  2893. break;
  2894. }
  2895. case BOOST_ASIO_OS_DEF(AF_INET6):
  2896. {
  2897. sockaddr_in6_type* sin6ptr = gai_alloc<sockaddr_in6_type>();
  2898. if (sin6ptr == 0)
  2899. return EAI_MEMORY;
  2900. sin6ptr->sin6_family = BOOST_ASIO_OS_DEF(AF_INET6);
  2901. memcpy(&sin6ptr->sin6_addr, addr, sizeof(in6_addr_type));
  2902. ai->ai_addr = reinterpret_cast<sockaddr*>(sin6ptr);
  2903. ai->ai_addrlen = sizeof(sockaddr_in6_type);
  2904. break;
  2905. }
  2906. default:
  2907. break;
  2908. }
  2909. return 0;
  2910. }
  2911. inline addrinfo_type* gai_clone(addrinfo_type* ai)
  2912. {
  2913. using namespace std;
  2914. addrinfo_type* new_ai = gai_alloc<addrinfo_type>();
  2915. if (new_ai == 0)
  2916. return new_ai;
  2917. new_ai->ai_next = ai->ai_next;
  2918. ai->ai_next = new_ai;
  2919. new_ai->ai_flags = 0;
  2920. new_ai->ai_family = ai->ai_family;
  2921. new_ai->ai_socktype = ai->ai_socktype;
  2922. new_ai->ai_protocol = ai->ai_protocol;
  2923. new_ai->ai_canonname = 0;
  2924. new_ai->ai_addrlen = ai->ai_addrlen;
  2925. new_ai->ai_addr = gai_alloc<sockaddr>(ai->ai_addrlen);
  2926. memcpy(new_ai->ai_addr, ai->ai_addr, ai->ai_addrlen);
  2927. return new_ai;
  2928. }
  2929. inline int gai_port(addrinfo_type* aihead, int port, int socktype)
  2930. {
  2931. int num_found = 0;
  2932. for (addrinfo_type* ai = aihead; ai; ai = ai->ai_next)
  2933. {
  2934. if (ai->ai_flags & gai_clone_flag)
  2935. {
  2936. if (ai->ai_socktype != 0)
  2937. {
  2938. ai = gai_clone(ai);
  2939. if (ai == 0)
  2940. return -1;
  2941. // ai now points to newly cloned entry.
  2942. }
  2943. }
  2944. else if (ai->ai_socktype != socktype)
  2945. {
  2946. // Ignore if mismatch on socket type.
  2947. continue;
  2948. }
  2949. ai->ai_socktype = socktype;
  2950. switch (ai->ai_family)
  2951. {
  2952. case BOOST_ASIO_OS_DEF(AF_INET):
  2953. {
  2954. sockaddr_in4_type* sinptr =
  2955. reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
  2956. sinptr->sin_port = port;
  2957. ++num_found;
  2958. break;
  2959. }
  2960. case BOOST_ASIO_OS_DEF(AF_INET6):
  2961. {
  2962. sockaddr_in6_type* sin6ptr =
  2963. reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
  2964. sin6ptr->sin6_port = port;
  2965. ++num_found;
  2966. break;
  2967. }
  2968. default:
  2969. break;
  2970. }
  2971. }
  2972. return num_found;
  2973. }
  2974. inline int gai_serv(addrinfo_type* aihead,
  2975. const addrinfo_type* hints, const char* serv)
  2976. {
  2977. using namespace std;
  2978. int num_found = 0;
  2979. if (
  2980. #if defined(AI_NUMERICSERV)
  2981. (hints->ai_flags & AI_NUMERICSERV) ||
  2982. #endif
  2983. isdigit(static_cast<unsigned char>(serv[0])))
  2984. {
  2985. int port = htons(atoi(serv));
  2986. if (hints->ai_socktype)
  2987. {
  2988. // Caller specifies socket type.
  2989. int rc = gai_port(aihead, port, hints->ai_socktype);
  2990. if (rc < 0)
  2991. return EAI_MEMORY;
  2992. num_found += rc;
  2993. }
  2994. else
  2995. {
  2996. // Caller does not specify socket type.
  2997. int rc = gai_port(aihead, port, SOCK_STREAM);
  2998. if (rc < 0)
  2999. return EAI_MEMORY;
  3000. num_found += rc;
  3001. rc = gai_port(aihead, port, SOCK_DGRAM);
  3002. if (rc < 0)
  3003. return EAI_MEMORY;
  3004. num_found += rc;
  3005. }
  3006. }
  3007. else
  3008. {
  3009. // Try service name with TCP first, then UDP.
  3010. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_STREAM)
  3011. {
  3012. servent* sptr = getservbyname(serv, "tcp");
  3013. if (sptr != 0)
  3014. {
  3015. int rc = gai_port(aihead, sptr->s_port, SOCK_STREAM);
  3016. if (rc < 0)
  3017. return EAI_MEMORY;
  3018. num_found += rc;
  3019. }
  3020. }
  3021. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_DGRAM)
  3022. {
  3023. servent* sptr = getservbyname(serv, "udp");
  3024. if (sptr != 0)
  3025. {
  3026. int rc = gai_port(aihead, sptr->s_port, SOCK_DGRAM);
  3027. if (rc < 0)
  3028. return EAI_MEMORY;
  3029. num_found += rc;
  3030. }
  3031. }
  3032. }
  3033. if (num_found == 0)
  3034. {
  3035. if (hints->ai_socktype == 0)
  3036. {
  3037. // All calls to getservbyname() failed.
  3038. return EAI_NONAME;
  3039. }
  3040. else
  3041. {
  3042. // Service not supported for socket type.
  3043. return EAI_SERVICE;
  3044. }
  3045. }
  3046. return 0;
  3047. }
  3048. inline int gai_echeck(const char* host, const char* service,
  3049. int flags, int family, int socktype, int protocol)
  3050. {
  3051. (void)(flags);
  3052. (void)(protocol);
  3053. // Host or service must be specified.
  3054. if (host == 0 || host[0] == '\0')
  3055. if (service == 0 || service[0] == '\0')
  3056. return EAI_NONAME;
  3057. // Check combination of family and socket type.
  3058. switch (family)
  3059. {
  3060. case BOOST_ASIO_OS_DEF(AF_UNSPEC):
  3061. break;
  3062. case BOOST_ASIO_OS_DEF(AF_INET):
  3063. case BOOST_ASIO_OS_DEF(AF_INET6):
  3064. if (service != 0 && service[0] != '\0')
  3065. if (socktype != 0 && socktype != SOCK_STREAM && socktype != SOCK_DGRAM)
  3066. return EAI_SOCKTYPE;
  3067. break;
  3068. default:
  3069. return EAI_FAMILY;
  3070. }
  3071. return 0;
  3072. }
  3073. inline void freeaddrinfo_emulation(addrinfo_type* aihead)
  3074. {
  3075. addrinfo_type* ai = aihead;
  3076. while (ai)
  3077. {
  3078. gai_free(ai->ai_addr);
  3079. gai_free(ai->ai_canonname);
  3080. addrinfo_type* ainext = ai->ai_next;
  3081. gai_free(ai);
  3082. ai = ainext;
  3083. }
  3084. }
  3085. inline int getaddrinfo_emulation(const char* host, const char* service,
  3086. const addrinfo_type* hintsp, addrinfo_type** result)
  3087. {
  3088. // Set up linked list of addrinfo structures.
  3089. addrinfo_type* aihead = 0;
  3090. addrinfo_type** ainext = &aihead;
  3091. char* canon = 0;
  3092. // Supply default hints if not specified by caller.
  3093. addrinfo_type hints = addrinfo_type();
  3094. hints.ai_family = BOOST_ASIO_OS_DEF(AF_UNSPEC);
  3095. if (hintsp)
  3096. hints = *hintsp;
  3097. // If the resolution is not specifically for AF_INET6, remove the AI_V4MAPPED
  3098. // and AI_ALL flags.
  3099. #if defined(AI_V4MAPPED)
  3100. if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
  3101. hints.ai_flags &= ~AI_V4MAPPED;
  3102. #endif
  3103. #if defined(AI_ALL)
  3104. if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
  3105. hints.ai_flags &= ~AI_ALL;
  3106. #endif
  3107. // Basic error checking.
  3108. int rc = gai_echeck(host, service, hints.ai_flags, hints.ai_family,
  3109. hints.ai_socktype, hints.ai_protocol);
  3110. if (rc != 0)
  3111. {
  3112. freeaddrinfo_emulation(aihead);
  3113. return rc;
  3114. }
  3115. gai_search search[2];
  3116. int search_count = gai_nsearch(host, &hints, search);
  3117. for (gai_search* sptr = search; sptr < search + search_count; ++sptr)
  3118. {
  3119. // Check for IPv4 dotted decimal string.
  3120. in4_addr_type inaddr;
  3121. boost::system::error_code ec;
  3122. if (socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET),
  3123. sptr->host, &inaddr, 0, ec) == 1)
  3124. {
  3125. if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
  3126. && hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET))
  3127. {
  3128. freeaddrinfo_emulation(aihead);
  3129. gai_free(canon);
  3130. return EAI_FAMILY;
  3131. }
  3132. if (sptr->family == BOOST_ASIO_OS_DEF(AF_INET))
  3133. {
  3134. rc = gai_aistruct(&ainext, &hints, &inaddr, BOOST_ASIO_OS_DEF(AF_INET));
  3135. if (rc != 0)
  3136. {
  3137. freeaddrinfo_emulation(aihead);
  3138. gai_free(canon);
  3139. return rc;
  3140. }
  3141. }
  3142. continue;
  3143. }
  3144. // Check for IPv6 hex string.
  3145. in6_addr_type in6addr;
  3146. if (socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET6),
  3147. sptr->host, &in6addr, 0, ec) == 1)
  3148. {
  3149. if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
  3150. && hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
  3151. {
  3152. freeaddrinfo_emulation(aihead);
  3153. gai_free(canon);
  3154. return EAI_FAMILY;
  3155. }
  3156. if (sptr->family == BOOST_ASIO_OS_DEF(AF_INET6))
  3157. {
  3158. rc = gai_aistruct(&ainext, &hints, &in6addr,
  3159. BOOST_ASIO_OS_DEF(AF_INET6));
  3160. if (rc != 0)
  3161. {
  3162. freeaddrinfo_emulation(aihead);
  3163. gai_free(canon);
  3164. return rc;
  3165. }
  3166. }
  3167. continue;
  3168. }
  3169. // Look up hostname.
  3170. hostent hent;
  3171. char hbuf[8192] = "";
  3172. hostent* hptr = socket_ops::gethostbyname(sptr->host,
  3173. sptr->family, &hent, hbuf, sizeof(hbuf), hints.ai_flags, ec);
  3174. if (hptr == 0)
  3175. {
  3176. if (search_count == 2)
  3177. {
  3178. // Failure is OK if there are multiple searches.
  3179. continue;
  3180. }
  3181. freeaddrinfo_emulation(aihead);
  3182. gai_free(canon);
  3183. if (ec == boost::asio::error::host_not_found)
  3184. return EAI_NONAME;
  3185. if (ec == boost::asio::error::host_not_found_try_again)
  3186. return EAI_AGAIN;
  3187. if (ec == boost::asio::error::no_recovery)
  3188. return EAI_FAIL;
  3189. if (ec == boost::asio::error::no_data)
  3190. return EAI_NONAME;
  3191. return EAI_NONAME;
  3192. }
  3193. // Check for address family mismatch if one was specified.
  3194. if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
  3195. && hints.ai_family != hptr->h_addrtype)
  3196. {
  3197. freeaddrinfo_emulation(aihead);
  3198. gai_free(canon);
  3199. socket_ops::freehostent(hptr);
  3200. return EAI_FAMILY;
  3201. }
  3202. // Save canonical name first time.
  3203. if (host != 0 && host[0] != '\0' && hptr->h_name && hptr->h_name[0]
  3204. && (hints.ai_flags & AI_CANONNAME) && canon == 0)
  3205. {
  3206. std::size_t canon_len = strlen(hptr->h_name) + 1;
  3207. canon = gai_alloc<char>(canon_len);
  3208. if (canon == 0)
  3209. {
  3210. freeaddrinfo_emulation(aihead);
  3211. socket_ops::freehostent(hptr);
  3212. return EAI_MEMORY;
  3213. }
  3214. gai_strcpy(canon, hptr->h_name, canon_len);
  3215. }
  3216. // Create an addrinfo structure for each returned address.
  3217. for (char** ap = hptr->h_addr_list; *ap; ++ap)
  3218. {
  3219. rc = gai_aistruct(&ainext, &hints, *ap, hptr->h_addrtype);
  3220. if (rc != 0)
  3221. {
  3222. freeaddrinfo_emulation(aihead);
  3223. gai_free(canon);
  3224. socket_ops::freehostent(hptr);
  3225. return EAI_FAMILY;
  3226. }
  3227. }
  3228. socket_ops::freehostent(hptr);
  3229. }
  3230. // Check if we found anything.
  3231. if (aihead == 0)
  3232. {
  3233. gai_free(canon);
  3234. return EAI_NONAME;
  3235. }
  3236. // Return canonical name in first entry.
  3237. if (host != 0 && host[0] != '\0' && (hints.ai_flags & AI_CANONNAME))
  3238. {
  3239. if (canon)
  3240. {
  3241. aihead->ai_canonname = canon;
  3242. canon = 0;
  3243. }
  3244. else
  3245. {
  3246. std::size_t canonname_len = strlen(search[0].host) + 1;
  3247. aihead->ai_canonname = gai_alloc<char>(canonname_len);
  3248. if (aihead->ai_canonname == 0)
  3249. {
  3250. freeaddrinfo_emulation(aihead);
  3251. return EAI_MEMORY;
  3252. }
  3253. gai_strcpy(aihead->ai_canonname, search[0].host, canonname_len);
  3254. }
  3255. }
  3256. gai_free(canon);
  3257. // Process the service name.
  3258. if (service != 0 && service[0] != '\0')
  3259. {
  3260. rc = gai_serv(aihead, &hints, service);
  3261. if (rc != 0)
  3262. {
  3263. freeaddrinfo_emulation(aihead);
  3264. return rc;
  3265. }
  3266. }
  3267. // Return result to caller.
  3268. *result = aihead;
  3269. return 0;
  3270. }
  3271. inline boost::system::error_code getnameinfo_emulation(
  3272. const socket_addr_type* sa, std::size_t salen, char* host,
  3273. std::size_t hostlen, char* serv, std::size_t servlen, int flags,
  3274. boost::system::error_code& ec)
  3275. {
  3276. using namespace std;
  3277. const char* addr;
  3278. size_t addr_len;
  3279. unsigned short port;
  3280. switch (sa->sa_family)
  3281. {
  3282. case BOOST_ASIO_OS_DEF(AF_INET):
  3283. if (salen != sizeof(sockaddr_in4_type))
  3284. {
  3285. return ec = boost::asio::error::invalid_argument;
  3286. }
  3287. addr = reinterpret_cast<const char*>(
  3288. &reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_addr);
  3289. addr_len = sizeof(in4_addr_type);
  3290. port = reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_port;
  3291. break;
  3292. case BOOST_ASIO_OS_DEF(AF_INET6):
  3293. if (salen != sizeof(sockaddr_in6_type))
  3294. {
  3295. return ec = boost::asio::error::invalid_argument;
  3296. }
  3297. addr = reinterpret_cast<const char*>(
  3298. &reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_addr);
  3299. addr_len = sizeof(in6_addr_type);
  3300. port = reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_port;
  3301. break;
  3302. default:
  3303. return ec = boost::asio::error::address_family_not_supported;
  3304. }
  3305. if (host && hostlen > 0)
  3306. {
  3307. if (flags & NI_NUMERICHOST)
  3308. {
  3309. if (socket_ops::inet_ntop(sa->sa_family, addr, host, hostlen, 0, ec) == 0)
  3310. {
  3311. return ec;
  3312. }
  3313. }
  3314. else
  3315. {
  3316. hostent hent;
  3317. char hbuf[8192] = "";
  3318. hostent* hptr = socket_ops::gethostbyaddr(addr,
  3319. static_cast<int>(addr_len), sa->sa_family,
  3320. &hent, hbuf, sizeof(hbuf), ec);
  3321. if (hptr && hptr->h_name && hptr->h_name[0] != '\0')
  3322. {
  3323. if (flags & NI_NOFQDN)
  3324. {
  3325. char* dot = strchr(hptr->h_name, '.');
  3326. if (dot)
  3327. {
  3328. *dot = 0;
  3329. }
  3330. }
  3331. gai_strcpy(host, hptr->h_name, hostlen);
  3332. socket_ops::freehostent(hptr);
  3333. }
  3334. else
  3335. {
  3336. socket_ops::freehostent(hptr);
  3337. if (flags & NI_NAMEREQD)
  3338. {
  3339. return ec = boost::asio::error::host_not_found;
  3340. }
  3341. if (socket_ops::inet_ntop(sa->sa_family,
  3342. addr, host, hostlen, 0, ec) == 0)
  3343. {
  3344. return ec;
  3345. }
  3346. }
  3347. }
  3348. }
  3349. if (serv && servlen > 0)
  3350. {
  3351. if (flags & NI_NUMERICSERV)
  3352. {
  3353. if (servlen < 6)
  3354. {
  3355. return ec = boost::asio::error::no_buffer_space;
  3356. }
  3357. #if defined(BOOST_ASIO_HAS_SNPRINTF)
  3358. snprintf(serv, servlen, "%u", ntohs(port));
  3359. #elif defined(BOOST_ASIO_HAS_SECURE_RTL)
  3360. sprintf_s(serv, servlen, "%u", ntohs(port));
  3361. #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
  3362. sprintf(serv, "%u", ntohs(port));
  3363. #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
  3364. }
  3365. else
  3366. {
  3367. #if defined(BOOST_ASIO_HAS_PTHREADS)
  3368. static ::pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  3369. ::pthread_mutex_lock(&mutex);
  3370. #endif // defined(BOOST_ASIO_HAS_PTHREADS)
  3371. servent* sptr = ::getservbyport(port, (flags & NI_DGRAM) ? "udp" : 0);
  3372. if (sptr && sptr->s_name && sptr->s_name[0] != '\0')
  3373. {
  3374. gai_strcpy(serv, sptr->s_name, servlen);
  3375. }
  3376. else
  3377. {
  3378. if (servlen < 6)
  3379. {
  3380. return ec = boost::asio::error::no_buffer_space;
  3381. }
  3382. #if defined(BOOST_ASIO_HAS_SNPRINTF)
  3383. snprintf(serv, servlen, "%u", ntohs(port));
  3384. #elif defined(BOOST_ASIO_HAS_SECURE_RTL)
  3385. sprintf_s(serv, servlen, "%u", ntohs(port));
  3386. #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
  3387. sprintf(serv, "%u", ntohs(port));
  3388. #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
  3389. }
  3390. #if defined(BOOST_ASIO_HAS_PTHREADS)
  3391. ::pthread_mutex_unlock(&mutex);
  3392. #endif // defined(BOOST_ASIO_HAS_PTHREADS)
  3393. }
  3394. }
  3395. boost::asio::error::clear(ec);
  3396. return ec;
  3397. }
  3398. #endif // !defined(BOOST_ASIO_HAS_GETADDRINFO)
  3399. inline boost::system::error_code translate_addrinfo_error(int error)
  3400. {
  3401. switch (error)
  3402. {
  3403. case 0:
  3404. return boost::system::error_code();
  3405. case EAI_AGAIN:
  3406. return boost::asio::error::host_not_found_try_again;
  3407. case EAI_BADFLAGS:
  3408. return boost::asio::error::invalid_argument;
  3409. case EAI_FAIL:
  3410. return boost::asio::error::no_recovery;
  3411. case EAI_FAMILY:
  3412. return boost::asio::error::address_family_not_supported;
  3413. case EAI_MEMORY:
  3414. return boost::asio::error::no_memory;
  3415. case EAI_NONAME:
  3416. #if defined(EAI_ADDRFAMILY)
  3417. case EAI_ADDRFAMILY:
  3418. #endif
  3419. #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
  3420. case EAI_NODATA:
  3421. #endif
  3422. return boost::asio::error::host_not_found;
  3423. case EAI_SERVICE:
  3424. return boost::asio::error::service_not_found;
  3425. case EAI_SOCKTYPE:
  3426. return boost::asio::error::socket_type_not_supported;
  3427. default: // Possibly the non-portable EAI_SYSTEM.
  3428. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  3429. return boost::system::error_code(
  3430. WSAGetLastError(), boost::asio::error::get_system_category());
  3431. #else
  3432. return boost::system::error_code(
  3433. errno, boost::asio::error::get_system_category());
  3434. #endif
  3435. }
  3436. }
  3437. boost::system::error_code getaddrinfo(const char* host,
  3438. const char* service, const addrinfo_type& hints,
  3439. addrinfo_type** result, boost::system::error_code& ec)
  3440. {
  3441. host = (host && *host) ? host : 0;
  3442. service = (service && *service) ? service : 0;
  3443. clear_last_error();
  3444. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  3445. # if defined(BOOST_ASIO_HAS_GETADDRINFO)
  3446. // Building for Windows XP, Windows Server 2003, or later.
  3447. int error = ::getaddrinfo(host, service, &hints, result);
  3448. return ec = translate_addrinfo_error(error);
  3449. # else
  3450. // Building for Windows 2000 or earlier.
  3451. typedef int (WSAAPI *gai_t)(const char*,
  3452. const char*, const addrinfo_type*, addrinfo_type**);
  3453. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  3454. {
  3455. if (gai_t gai = (gai_t)::GetProcAddress(winsock_module, "getaddrinfo"))
  3456. {
  3457. int error = gai(host, service, &hints, result);
  3458. return ec = translate_addrinfo_error(error);
  3459. }
  3460. }
  3461. int error = getaddrinfo_emulation(host, service, &hints, result);
  3462. return ec = translate_addrinfo_error(error);
  3463. # endif
  3464. #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
  3465. int error = getaddrinfo_emulation(host, service, &hints, result);
  3466. return ec = translate_addrinfo_error(error);
  3467. #else
  3468. int error = ::getaddrinfo(host, service, &hints, result);
  3469. #if defined(__MACH__) && defined(__APPLE__)
  3470. using namespace std; // For isdigit and atoi.
  3471. if (error == 0 && service && isdigit(static_cast<unsigned char>(service[0])))
  3472. {
  3473. u_short_type port = host_to_network_short(atoi(service));
  3474. for (addrinfo_type* ai = *result; ai; ai = ai->ai_next)
  3475. {
  3476. switch (ai->ai_family)
  3477. {
  3478. case BOOST_ASIO_OS_DEF(AF_INET):
  3479. {
  3480. sockaddr_in4_type* sinptr =
  3481. reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
  3482. if (sinptr->sin_port == 0)
  3483. sinptr->sin_port = port;
  3484. break;
  3485. }
  3486. case BOOST_ASIO_OS_DEF(AF_INET6):
  3487. {
  3488. sockaddr_in6_type* sin6ptr =
  3489. reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
  3490. if (sin6ptr->sin6_port == 0)
  3491. sin6ptr->sin6_port = port;
  3492. break;
  3493. }
  3494. default:
  3495. break;
  3496. }
  3497. }
  3498. }
  3499. #endif
  3500. return ec = translate_addrinfo_error(error);
  3501. #endif
  3502. }
  3503. boost::system::error_code background_getaddrinfo(
  3504. const weak_cancel_token_type& cancel_token, const char* host,
  3505. const char* service, const addrinfo_type& hints,
  3506. addrinfo_type** result, boost::system::error_code& ec)
  3507. {
  3508. if (cancel_token.expired())
  3509. ec = boost::asio::error::operation_aborted;
  3510. else
  3511. socket_ops::getaddrinfo(host, service, hints, result, ec);
  3512. return ec;
  3513. }
  3514. void freeaddrinfo(addrinfo_type* ai)
  3515. {
  3516. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  3517. # if defined(BOOST_ASIO_HAS_GETADDRINFO)
  3518. // Building for Windows XP, Windows Server 2003, or later.
  3519. ::freeaddrinfo(ai);
  3520. # else
  3521. // Building for Windows 2000 or earlier.
  3522. typedef int (WSAAPI *fai_t)(addrinfo_type*);
  3523. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  3524. {
  3525. if (fai_t fai = (fai_t)::GetProcAddress(winsock_module, "freeaddrinfo"))
  3526. {
  3527. fai(ai);
  3528. return;
  3529. }
  3530. }
  3531. freeaddrinfo_emulation(ai);
  3532. # endif
  3533. #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
  3534. freeaddrinfo_emulation(ai);
  3535. #else
  3536. ::freeaddrinfo(ai);
  3537. #endif
  3538. }
  3539. boost::system::error_code getnameinfo(const void* addr,
  3540. std::size_t addrlen, char* host, std::size_t hostlen,
  3541. char* serv, std::size_t servlen, int flags, boost::system::error_code& ec)
  3542. {
  3543. #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  3544. # if defined(BOOST_ASIO_HAS_GETADDRINFO)
  3545. // Building for Windows XP, Windows Server 2003, or later.
  3546. clear_last_error();
  3547. int error = ::getnameinfo(static_cast<const socket_addr_type*>(addr),
  3548. static_cast<socklen_t>(addrlen), host, static_cast<DWORD>(hostlen),
  3549. serv, static_cast<DWORD>(servlen), flags);
  3550. return ec = translate_addrinfo_error(error);
  3551. # else
  3552. // Building for Windows 2000 or earlier.
  3553. typedef int (WSAAPI *gni_t)(const socket_addr_type*,
  3554. int, char*, DWORD, char*, DWORD, int);
  3555. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  3556. {
  3557. if (gni_t gni = (gni_t)::GetProcAddress(winsock_module, "getnameinfo"))
  3558. {
  3559. clear_last_error();
  3560. int error = gni(static_cast<const socket_addr_type*>(addr),
  3561. static_cast<int>(addrlen), host, static_cast<DWORD>(hostlen),
  3562. serv, static_cast<DWORD>(servlen), flags);
  3563. return ec = translate_addrinfo_error(error);
  3564. }
  3565. }
  3566. clear_last_error();
  3567. return getnameinfo_emulation(static_cast<const socket_addr_type*>(addr),
  3568. addrlen, host, hostlen, serv, servlen, flags, ec);
  3569. # endif
  3570. #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
  3571. using namespace std; // For memcpy.
  3572. sockaddr_storage_type tmp_addr;
  3573. memcpy(&tmp_addr, addr, addrlen);
  3574. addr = &tmp_addr;
  3575. clear_last_error();
  3576. return getnameinfo_emulation(static_cast<const socket_addr_type*>(addr),
  3577. addrlen, host, hostlen, serv, servlen, flags, ec);
  3578. #else
  3579. clear_last_error();
  3580. int error = ::getnameinfo(static_cast<const socket_addr_type*>(addr),
  3581. addrlen, host, hostlen, serv, servlen, flags);
  3582. return ec = translate_addrinfo_error(error);
  3583. #endif
  3584. }
  3585. boost::system::error_code sync_getnameinfo(const void* addr,
  3586. std::size_t addrlen, char* host, std::size_t hostlen, char* serv,
  3587. std::size_t servlen, int sock_type, boost::system::error_code& ec)
  3588. {
  3589. // First try resolving with the service name. If that fails try resolving
  3590. // but allow the service to be returned as a number.
  3591. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  3592. socket_ops::getnameinfo(addr, addrlen, host,
  3593. hostlen, serv, servlen, flags, ec);
  3594. if (ec)
  3595. {
  3596. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  3597. serv, servlen, flags | NI_NUMERICSERV, ec);
  3598. }
  3599. return ec;
  3600. }
  3601. boost::system::error_code background_getnameinfo(
  3602. const weak_cancel_token_type& cancel_token,
  3603. const void* addr, std::size_t addrlen,
  3604. char* host, std::size_t hostlen, char* serv,
  3605. std::size_t servlen, int sock_type, boost::system::error_code& ec)
  3606. {
  3607. if (cancel_token.expired())
  3608. {
  3609. ec = boost::asio::error::operation_aborted;
  3610. }
  3611. else
  3612. {
  3613. // First try resolving with the service name. If that fails try resolving
  3614. // but allow the service to be returned as a number.
  3615. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  3616. socket_ops::getnameinfo(addr, addrlen, host,
  3617. hostlen, serv, servlen, flags, ec);
  3618. if (ec)
  3619. {
  3620. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  3621. serv, servlen, flags | NI_NUMERICSERV, ec);
  3622. }
  3623. }
  3624. return ec;
  3625. }
  3626. #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3627. u_long_type network_to_host_long(u_long_type value)
  3628. {
  3629. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3630. unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
  3631. u_long_type result = (static_cast<u_long_type>(value_p[0]) << 24)
  3632. | (static_cast<u_long_type>(value_p[1]) << 16)
  3633. | (static_cast<u_long_type>(value_p[2]) << 8)
  3634. | static_cast<u_long_type>(value_p[3]);
  3635. return result;
  3636. #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3637. return ntohl(value);
  3638. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3639. }
  3640. u_long_type host_to_network_long(u_long_type value)
  3641. {
  3642. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3643. u_long_type result;
  3644. unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
  3645. result_p[0] = static_cast<unsigned char>((value >> 24) & 0xFF);
  3646. result_p[1] = static_cast<unsigned char>((value >> 16) & 0xFF);
  3647. result_p[2] = static_cast<unsigned char>((value >> 8) & 0xFF);
  3648. result_p[3] = static_cast<unsigned char>(value & 0xFF);
  3649. return result;
  3650. #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3651. return htonl(value);
  3652. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3653. }
  3654. u_short_type network_to_host_short(u_short_type value)
  3655. {
  3656. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3657. unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
  3658. u_short_type result = (static_cast<u_short_type>(value_p[0]) << 8)
  3659. | static_cast<u_short_type>(value_p[1]);
  3660. return result;
  3661. #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3662. return ntohs(value);
  3663. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3664. }
  3665. u_short_type host_to_network_short(u_short_type value)
  3666. {
  3667. #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3668. u_short_type result;
  3669. unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
  3670. result_p[0] = static_cast<unsigned char>((value >> 8) & 0xFF);
  3671. result_p[1] = static_cast<unsigned char>(value & 0xFF);
  3672. return result;
  3673. #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3674. return htons(value);
  3675. #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
  3676. }
  3677. } // namespace socket_ops
  3678. } // namespace detail
  3679. } // namespace asio
  3680. } // namespace boost
  3681. #include <boost/asio/detail/pop_options.hpp>
  3682. #endif // BOOST_ASIO_DETAIL_SOCKET_OPS_IPP