socket_ops.ipp 116 KB

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