socket_ops.ipp 97 KB

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