socket_ops.ipp 96 KB

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