Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

socket_ops.ipp 95KB

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