socket_ops.ipp 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433
  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(__CYGWIN__)
  1448. if (cached)
  1449. {
  1450. // Check if socket is still connected.
  1451. DWORD connect_time = 0;
  1452. size_t connect_time_len = sizeof(connect_time);
  1453. if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_CONNECT_TIME,
  1454. &connect_time, &connect_time_len, ec) == socket_error_retval)
  1455. {
  1456. return socket_error_retval;
  1457. }
  1458. if (connect_time == 0xFFFFFFFF)
  1459. {
  1460. ec = asio::error::not_connected;
  1461. return socket_error_retval;
  1462. }
  1463. // The cached value is still valid.
  1464. ec = asio::error_code();
  1465. return 0;
  1466. }
  1467. #else // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1468. (void)cached;
  1469. #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1470. clear_last_error();
  1471. int result = error_wrapper(call_getpeername(
  1472. &msghdr::msg_namelen, s, addr, addrlen), ec);
  1473. if (result == 0)
  1474. ec = asio::error_code();
  1475. return result;
  1476. }
  1477. template <typename SockLenType>
  1478. inline int call_getsockname(SockLenType msghdr::*,
  1479. socket_type s, socket_addr_type* addr, std::size_t* addrlen)
  1480. {
  1481. SockLenType tmp_addrlen = (SockLenType)*addrlen;
  1482. int result = ::getsockname(s, addr, &tmp_addrlen);
  1483. *addrlen = (std::size_t)tmp_addrlen;
  1484. return result;
  1485. }
  1486. int getsockname(socket_type s, socket_addr_type* addr,
  1487. std::size_t* addrlen, asio::error_code& ec)
  1488. {
  1489. if (s == invalid_socket)
  1490. {
  1491. ec = asio::error::bad_descriptor;
  1492. return socket_error_retval;
  1493. }
  1494. clear_last_error();
  1495. int result = error_wrapper(call_getsockname(
  1496. &msghdr::msg_namelen, s, addr, addrlen), ec);
  1497. if (result == 0)
  1498. ec = asio::error_code();
  1499. return result;
  1500. }
  1501. int ioctl(socket_type s, state_type& state, int cmd,
  1502. ioctl_arg_type* arg, asio::error_code& ec)
  1503. {
  1504. if (s == invalid_socket)
  1505. {
  1506. ec = asio::error::bad_descriptor;
  1507. return socket_error_retval;
  1508. }
  1509. clear_last_error();
  1510. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1511. int result = error_wrapper(::ioctlsocket(s, cmd, arg), ec);
  1512. #elif defined(__MACH__) && defined(__APPLE__) \
  1513. || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1514. int result = error_wrapper(::ioctl(s,
  1515. static_cast<unsigned int>(cmd), arg), ec);
  1516. #else
  1517. int result = error_wrapper(::ioctl(s, cmd, arg), ec);
  1518. #endif
  1519. if (result >= 0)
  1520. {
  1521. ec = asio::error_code();
  1522. // When updating the non-blocking mode we always perform the ioctl syscall,
  1523. // even if the flags would otherwise indicate that the socket is already in
  1524. // the correct state. This ensures that the underlying socket is put into
  1525. // the state that has been requested by the user. If the ioctl syscall was
  1526. // successful then we need to update the flags to match.
  1527. if (cmd == static_cast<int>(FIONBIO))
  1528. {
  1529. if (*arg)
  1530. {
  1531. state |= user_set_non_blocking;
  1532. }
  1533. else
  1534. {
  1535. // Clearing the non-blocking mode always overrides any internally-set
  1536. // non-blocking flag. Any subsequent asynchronous operations will need
  1537. // to re-enable non-blocking I/O.
  1538. state &= ~(user_set_non_blocking | internal_non_blocking);
  1539. }
  1540. }
  1541. }
  1542. return result;
  1543. }
  1544. int select(int nfds, fd_set* readfds, fd_set* writefds,
  1545. fd_set* exceptfds, timeval* timeout, asio::error_code& ec)
  1546. {
  1547. clear_last_error();
  1548. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1549. if (!readfds && !writefds && !exceptfds && timeout)
  1550. {
  1551. DWORD milliseconds = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
  1552. if (milliseconds == 0)
  1553. milliseconds = 1; // Force context switch.
  1554. ::Sleep(milliseconds);
  1555. ec = asio::error_code();
  1556. return 0;
  1557. }
  1558. // The select() call allows timeout values measured in microseconds, but the
  1559. // system clock (as wrapped by boost::posix_time::microsec_clock) typically
  1560. // has a resolution of 10 milliseconds. This can lead to a spinning select
  1561. // reactor, meaning increased CPU usage, when waiting for the earliest
  1562. // scheduled timeout if it's less than 10 milliseconds away. To avoid a tight
  1563. // spin we'll use a minimum timeout of 1 millisecond.
  1564. if (timeout && timeout->tv_sec == 0
  1565. && timeout->tv_usec > 0 && timeout->tv_usec < 1000)
  1566. timeout->tv_usec = 1000;
  1567. #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1568. #if defined(__hpux) && defined(__SELECT)
  1569. timespec ts;
  1570. ts.tv_sec = timeout ? timeout->tv_sec : 0;
  1571. ts.tv_nsec = timeout ? timeout->tv_usec * 1000 : 0;
  1572. return error_wrapper(::pselect(nfds, readfds,
  1573. writefds, exceptfds, timeout ? &ts : 0, 0), ec);
  1574. #else
  1575. int result = error_wrapper(::select(nfds, readfds,
  1576. writefds, exceptfds, timeout), ec);
  1577. if (result >= 0)
  1578. ec = asio::error_code();
  1579. return result;
  1580. #endif
  1581. }
  1582. int poll_read(socket_type s, state_type state, asio::error_code& ec)
  1583. {
  1584. if (s == invalid_socket)
  1585. {
  1586. ec = asio::error::bad_descriptor;
  1587. return socket_error_retval;
  1588. }
  1589. #if defined(ASIO_WINDOWS) \
  1590. || defined(__CYGWIN__) \
  1591. || defined(__SYMBIAN32__)
  1592. fd_set fds;
  1593. FD_ZERO(&fds);
  1594. FD_SET(s, &fds);
  1595. timeval zero_timeout;
  1596. zero_timeout.tv_sec = 0;
  1597. zero_timeout.tv_usec = 0;
  1598. timeval* timeout = (state & user_set_non_blocking) ? &zero_timeout : 0;
  1599. clear_last_error();
  1600. int result = error_wrapper(::select(s + 1, &fds, 0, 0, timeout), ec);
  1601. #else // defined(ASIO_WINDOWS)
  1602. // || defined(__CYGWIN__)
  1603. // || defined(__SYMBIAN32__)
  1604. pollfd fds;
  1605. fds.fd = s;
  1606. fds.events = POLLIN;
  1607. fds.revents = 0;
  1608. int timeout = (state & user_set_non_blocking) ? 0 : -1;
  1609. clear_last_error();
  1610. int result = error_wrapper(::poll(&fds, 1, timeout), ec);
  1611. #endif // defined(ASIO_WINDOWS)
  1612. // || defined(__CYGWIN__)
  1613. // || defined(__SYMBIAN32__)
  1614. if (result == 0)
  1615. ec = (state & user_set_non_blocking)
  1616. ? asio::error::would_block : asio::error_code();
  1617. else if (result > 0)
  1618. ec = asio::error_code();
  1619. return result;
  1620. }
  1621. int poll_write(socket_type s, state_type state, asio::error_code& ec)
  1622. {
  1623. if (s == invalid_socket)
  1624. {
  1625. ec = asio::error::bad_descriptor;
  1626. return socket_error_retval;
  1627. }
  1628. #if defined(ASIO_WINDOWS) \
  1629. || defined(__CYGWIN__) \
  1630. || defined(__SYMBIAN32__)
  1631. fd_set fds;
  1632. FD_ZERO(&fds);
  1633. FD_SET(s, &fds);
  1634. timeval zero_timeout;
  1635. zero_timeout.tv_sec = 0;
  1636. zero_timeout.tv_usec = 0;
  1637. timeval* timeout = (state & user_set_non_blocking) ? &zero_timeout : 0;
  1638. clear_last_error();
  1639. int result = error_wrapper(::select(s + 1, 0, &fds, 0, timeout), ec);
  1640. #else // defined(ASIO_WINDOWS)
  1641. // || defined(__CYGWIN__)
  1642. // || defined(__SYMBIAN32__)
  1643. pollfd fds;
  1644. fds.fd = s;
  1645. fds.events = POLLOUT;
  1646. fds.revents = 0;
  1647. int timeout = (state & user_set_non_blocking) ? 0 : -1;
  1648. clear_last_error();
  1649. int result = error_wrapper(::poll(&fds, 1, timeout), ec);
  1650. #endif // defined(ASIO_WINDOWS)
  1651. // || defined(__CYGWIN__)
  1652. // || defined(__SYMBIAN32__)
  1653. if (result == 0)
  1654. ec = (state & user_set_non_blocking)
  1655. ? asio::error::would_block : asio::error_code();
  1656. else if (result > 0)
  1657. ec = asio::error_code();
  1658. return result;
  1659. }
  1660. int poll_connect(socket_type s, asio::error_code& ec)
  1661. {
  1662. if (s == invalid_socket)
  1663. {
  1664. ec = asio::error::bad_descriptor;
  1665. return socket_error_retval;
  1666. }
  1667. #if defined(ASIO_WINDOWS) \
  1668. || defined(__CYGWIN__) \
  1669. || defined(__SYMBIAN32__)
  1670. fd_set write_fds;
  1671. FD_ZERO(&write_fds);
  1672. FD_SET(s, &write_fds);
  1673. fd_set except_fds;
  1674. FD_ZERO(&except_fds);
  1675. FD_SET(s, &except_fds);
  1676. clear_last_error();
  1677. int result = error_wrapper(::select(
  1678. s + 1, 0, &write_fds, &except_fds, 0), ec);
  1679. if (result >= 0)
  1680. ec = asio::error_code();
  1681. return result;
  1682. #else // defined(ASIO_WINDOWS)
  1683. // || defined(__CYGWIN__)
  1684. // || defined(__SYMBIAN32__)
  1685. pollfd fds;
  1686. fds.fd = s;
  1687. fds.events = POLLOUT;
  1688. fds.revents = 0;
  1689. clear_last_error();
  1690. int result = error_wrapper(::poll(&fds, 1, -1), ec);
  1691. if (result >= 0)
  1692. ec = asio::error_code();
  1693. return result;
  1694. #endif // defined(ASIO_WINDOWS)
  1695. // || defined(__CYGWIN__)
  1696. // || defined(__SYMBIAN32__)
  1697. }
  1698. #endif // !defined(ASIO_WINDOWS_RUNTIME)
  1699. const char* inet_ntop(int af, const void* src, char* dest, size_t length,
  1700. unsigned long scope_id, asio::error_code& ec)
  1701. {
  1702. clear_last_error();
  1703. #if defined(ASIO_WINDOWS_RUNTIME)
  1704. using namespace std; // For sprintf.
  1705. const unsigned char* bytes = static_cast<const unsigned char*>(src);
  1706. if (af == ASIO_OS_DEF(AF_INET))
  1707. {
  1708. sprintf_s(dest, length, "%u.%u.%u.%u",
  1709. bytes[0], bytes[1], bytes[2], bytes[3]);
  1710. return dest;
  1711. }
  1712. else if (af == ASIO_OS_DEF(AF_INET6))
  1713. {
  1714. size_t n = 0, b = 0, z = 0;
  1715. while (n < length && b < 16)
  1716. {
  1717. if (bytes[b] == 0 && bytes[b + 1] == 0 && z == 0)
  1718. {
  1719. do b += 2; while (b < 16 && bytes[b] == 0 && bytes[b + 1] == 0);
  1720. n += sprintf_s(dest + n, length - n, ":%s", b < 16 ? "" : ":"), ++z;
  1721. }
  1722. else
  1723. {
  1724. n += sprintf_s(dest + n, length - n, "%s%x", b ? ":" : "",
  1725. (static_cast<u_long_type>(bytes[b]) << 8) | bytes[b + 1]);
  1726. b += 2;
  1727. }
  1728. }
  1729. if (scope_id)
  1730. n += sprintf_s(dest + n, length - n, "%%%lu", scope_id);
  1731. return dest;
  1732. }
  1733. else
  1734. {
  1735. ec = asio::error::address_family_not_supported;
  1736. return 0;
  1737. }
  1738. #elif defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1739. using namespace std; // For memcpy.
  1740. if (af != ASIO_OS_DEF(AF_INET) && af != ASIO_OS_DEF(AF_INET6))
  1741. {
  1742. ec = asio::error::address_family_not_supported;
  1743. return 0;
  1744. }
  1745. union
  1746. {
  1747. socket_addr_type base;
  1748. sockaddr_storage_type storage;
  1749. sockaddr_in4_type v4;
  1750. sockaddr_in6_type v6;
  1751. } address;
  1752. DWORD address_length;
  1753. if (af == ASIO_OS_DEF(AF_INET))
  1754. {
  1755. address_length = sizeof(sockaddr_in4_type);
  1756. address.v4.sin_family = ASIO_OS_DEF(AF_INET);
  1757. address.v4.sin_port = 0;
  1758. memcpy(&address.v4.sin_addr, src, sizeof(in4_addr_type));
  1759. }
  1760. else // AF_INET6
  1761. {
  1762. address_length = sizeof(sockaddr_in6_type);
  1763. address.v6.sin6_family = ASIO_OS_DEF(AF_INET6);
  1764. address.v6.sin6_port = 0;
  1765. address.v6.sin6_flowinfo = 0;
  1766. address.v6.sin6_scope_id = scope_id;
  1767. memcpy(&address.v6.sin6_addr, src, sizeof(in6_addr_type));
  1768. }
  1769. DWORD string_length = static_cast<DWORD>(length);
  1770. #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
  1771. LPWSTR string_buffer = (LPWSTR)_alloca(length * sizeof(WCHAR));
  1772. int result = error_wrapper(::WSAAddressToStringW(&address.base,
  1773. address_length, 0, string_buffer, &string_length), ec);
  1774. ::WideCharToMultiByte(CP_ACP, 0, string_buffer, -1,
  1775. dest, static_cast<int>(length), 0, 0);
  1776. #else
  1777. int result = error_wrapper(::WSAAddressToStringA(
  1778. &address.base, address_length, 0, dest, &string_length), ec);
  1779. #endif
  1780. // Windows may set error code on success.
  1781. if (result != socket_error_retval)
  1782. ec = asio::error_code();
  1783. // Windows may not set an error code on failure.
  1784. else if (result == socket_error_retval && !ec)
  1785. ec = asio::error::invalid_argument;
  1786. return result == socket_error_retval ? 0 : dest;
  1787. #else // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1788. const char* result = error_wrapper(::inet_ntop(
  1789. af, src, dest, static_cast<int>(length)), ec);
  1790. if (result == 0 && !ec)
  1791. ec = asio::error::invalid_argument;
  1792. if (result != 0 && af == ASIO_OS_DEF(AF_INET6) && scope_id != 0)
  1793. {
  1794. using namespace std; // For strcat and sprintf.
  1795. char if_name[IF_NAMESIZE + 1] = "%";
  1796. const in6_addr_type* ipv6_address = static_cast<const in6_addr_type*>(src);
  1797. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  1798. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  1799. bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
  1800. && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
  1801. if ((!is_link_local && !is_multicast_link_local)
  1802. || if_indextoname(static_cast<unsigned>(scope_id), if_name + 1) == 0)
  1803. sprintf(if_name + 1, "%lu", scope_id);
  1804. strcat(dest, if_name);
  1805. }
  1806. return result;
  1807. #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1808. }
  1809. int inet_pton(int af, const char* src, void* dest,
  1810. unsigned long* scope_id, asio::error_code& ec)
  1811. {
  1812. clear_last_error();
  1813. #if defined(ASIO_WINDOWS_RUNTIME)
  1814. using namespace std; // For sscanf.
  1815. unsigned char* bytes = static_cast<unsigned char*>(dest);
  1816. if (af == ASIO_OS_DEF(AF_INET))
  1817. {
  1818. unsigned int b0, b1, b2, b3;
  1819. if (sscanf_s(src, "%u.%u.%u.%u", &b0, &b1, &b2, &b3) != 4)
  1820. {
  1821. ec = asio::error::invalid_argument;
  1822. return -1;
  1823. }
  1824. if (b0 > 255 || b1 > 255 || b2 > 255 || b3 > 255)
  1825. {
  1826. ec = asio::error::invalid_argument;
  1827. return -1;
  1828. }
  1829. bytes[0] = static_cast<unsigned char>(b0);
  1830. bytes[1] = static_cast<unsigned char>(b1);
  1831. bytes[2] = static_cast<unsigned char>(b2);
  1832. bytes[3] = static_cast<unsigned char>(b3);
  1833. ec = asio::error_code();
  1834. return 1;
  1835. }
  1836. else if (af == ASIO_OS_DEF(AF_INET6))
  1837. {
  1838. unsigned char* bytes = static_cast<unsigned char*>(dest);
  1839. std::memset(bytes, 0, 16);
  1840. unsigned char back_bytes[16] = { 0 };
  1841. int num_front_bytes = 0, num_back_bytes = 0;
  1842. const char* p = src;
  1843. enum { fword, fcolon, bword, scope, done } state = fword;
  1844. unsigned long current_word = 0;
  1845. while (state != done)
  1846. {
  1847. if (current_word > 0xFFFF)
  1848. {
  1849. ec = asio::error::invalid_argument;
  1850. return -1;
  1851. }
  1852. switch (state)
  1853. {
  1854. case fword:
  1855. if (*p >= '0' && *p <= '9')
  1856. current_word = current_word * 16 + *p++ - '0';
  1857. else if (*p >= 'a' && *p <= 'f')
  1858. current_word = current_word * 16 + *p++ - 'a' + 10;
  1859. else if (*p >= 'A' && *p <= 'F')
  1860. current_word = current_word * 16 + *p++ - 'A' + 10;
  1861. else
  1862. {
  1863. if (num_front_bytes == 16)
  1864. {
  1865. ec = asio::error::invalid_argument;
  1866. return -1;
  1867. }
  1868. bytes[num_front_bytes++] = (current_word >> 8) & 0xFF;
  1869. bytes[num_front_bytes++] = current_word & 0xFF;
  1870. current_word = 0;
  1871. if (*p == ':')
  1872. state = fcolon, ++p;
  1873. else if (*p == '%')
  1874. state = scope, ++p;
  1875. else if (*p == 0)
  1876. state = done;
  1877. else
  1878. {
  1879. ec = asio::error::invalid_argument;
  1880. return -1;
  1881. }
  1882. }
  1883. break;
  1884. case fcolon:
  1885. if (*p == ':')
  1886. state = bword, ++p;
  1887. else
  1888. state = fword;
  1889. break;
  1890. case bword:
  1891. if (*p >= '0' && *p <= '9')
  1892. current_word = current_word * 16 + *p++ - '0';
  1893. else if (*p >= 'a' && *p <= 'f')
  1894. current_word = current_word * 16 + *p++ - 'a' + 10;
  1895. else if (*p >= 'A' && *p <= 'F')
  1896. current_word = current_word * 16 + *p++ - 'A' + 10;
  1897. else
  1898. {
  1899. if (num_front_bytes + num_back_bytes == 16)
  1900. {
  1901. ec = asio::error::invalid_argument;
  1902. return -1;
  1903. }
  1904. back_bytes[num_back_bytes++] = (current_word >> 8) & 0xFF;
  1905. back_bytes[num_back_bytes++] = current_word & 0xFF;
  1906. current_word = 0;
  1907. if (*p == ':')
  1908. state = bword, ++p;
  1909. else if (*p == '%')
  1910. state = scope, ++p;
  1911. else if (*p == 0)
  1912. state = done;
  1913. else
  1914. {
  1915. ec = asio::error::invalid_argument;
  1916. return -1;
  1917. }
  1918. }
  1919. break;
  1920. case scope:
  1921. if (*p >= '0' && *p <= '9')
  1922. current_word = current_word * 10 + *p++ - '0';
  1923. else if (*p == 0)
  1924. *scope_id = current_word, state = done;
  1925. else
  1926. {
  1927. ec = asio::error::invalid_argument;
  1928. return -1;
  1929. }
  1930. break;
  1931. default:
  1932. break;
  1933. }
  1934. }
  1935. for (int i = 0; i < num_back_bytes; ++i)
  1936. bytes[16 - num_back_bytes + i] = back_bytes[i];
  1937. ec = asio::error_code();
  1938. return 1;
  1939. }
  1940. else
  1941. {
  1942. ec = asio::error::address_family_not_supported;
  1943. return -1;
  1944. }
  1945. #elif defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  1946. using namespace std; // For memcpy and strcmp.
  1947. if (af != ASIO_OS_DEF(AF_INET) && af != ASIO_OS_DEF(AF_INET6))
  1948. {
  1949. ec = asio::error::address_family_not_supported;
  1950. return -1;
  1951. }
  1952. union
  1953. {
  1954. socket_addr_type base;
  1955. sockaddr_storage_type storage;
  1956. sockaddr_in4_type v4;
  1957. sockaddr_in6_type v6;
  1958. } address;
  1959. int address_length = sizeof(sockaddr_storage_type);
  1960. #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
  1961. int num_wide_chars = static_cast<int>(strlen(src)) + 1;
  1962. LPWSTR wide_buffer = (LPWSTR)_alloca(num_wide_chars * sizeof(WCHAR));
  1963. ::MultiByteToWideChar(CP_ACP, 0, src, -1, wide_buffer, num_wide_chars);
  1964. int result = error_wrapper(::WSAStringToAddressW(
  1965. wide_buffer, af, 0, &address.base, &address_length), ec);
  1966. #else
  1967. int result = error_wrapper(::WSAStringToAddressA(
  1968. const_cast<char*>(src), af, 0, &address.base, &address_length), ec);
  1969. #endif
  1970. if (af == ASIO_OS_DEF(AF_INET))
  1971. {
  1972. if (result != socket_error_retval)
  1973. {
  1974. memcpy(dest, &address.v4.sin_addr, sizeof(in4_addr_type));
  1975. ec = asio::error_code();
  1976. }
  1977. else if (strcmp(src, "255.255.255.255") == 0)
  1978. {
  1979. static_cast<in4_addr_type*>(dest)->s_addr = INADDR_NONE;
  1980. ec = asio::error_code();
  1981. }
  1982. }
  1983. else // AF_INET6
  1984. {
  1985. if (result != socket_error_retval)
  1986. {
  1987. memcpy(dest, &address.v6.sin6_addr, sizeof(in6_addr_type));
  1988. if (scope_id)
  1989. *scope_id = address.v6.sin6_scope_id;
  1990. ec = asio::error_code();
  1991. }
  1992. }
  1993. // Windows may not set an error code on failure.
  1994. if (result == socket_error_retval && !ec)
  1995. ec = asio::error::invalid_argument;
  1996. if (result != socket_error_retval)
  1997. ec = asio::error_code();
  1998. return result == socket_error_retval ? -1 : 1;
  1999. #else // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2000. using namespace std; // For strchr, memcpy and atoi.
  2001. // On some platforms, inet_pton fails if an address string contains a scope
  2002. // id. Detect and remove the scope id before passing the string to inet_pton.
  2003. const bool is_v6 = (af == ASIO_OS_DEF(AF_INET6));
  2004. const char* if_name = is_v6 ? strchr(src, '%') : 0;
  2005. char src_buf[max_addr_v6_str_len + 1];
  2006. const char* src_ptr = src;
  2007. if (if_name != 0)
  2008. {
  2009. if (if_name - src > max_addr_v6_str_len)
  2010. {
  2011. ec = asio::error::invalid_argument;
  2012. return 0;
  2013. }
  2014. memcpy(src_buf, src, if_name - src);
  2015. src_buf[if_name - src] = 0;
  2016. src_ptr = src_buf;
  2017. }
  2018. int result = error_wrapper(::inet_pton(af, src_ptr, dest), ec);
  2019. if (result <= 0 && !ec)
  2020. ec = asio::error::invalid_argument;
  2021. if (result > 0 && is_v6 && scope_id)
  2022. {
  2023. using namespace std; // For strchr and atoi.
  2024. *scope_id = 0;
  2025. if (if_name != 0)
  2026. {
  2027. in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest);
  2028. bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
  2029. && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
  2030. bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
  2031. && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
  2032. if (is_link_local || is_multicast_link_local)
  2033. *scope_id = if_nametoindex(if_name + 1);
  2034. if (*scope_id == 0)
  2035. *scope_id = atoi(if_name + 1);
  2036. }
  2037. }
  2038. return result;
  2039. #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2040. }
  2041. int gethostname(char* name, int namelen, asio::error_code& ec)
  2042. {
  2043. clear_last_error();
  2044. #if defined(ASIO_WINDOWS_RUNTIME)
  2045. try
  2046. {
  2047. using namespace Windows::Foundation::Collections;
  2048. using namespace Windows::Networking;
  2049. using namespace Windows::Networking::Connectivity;
  2050. IVectorView<HostName^>^ hostnames = NetworkInformation::GetHostNames();
  2051. for (unsigned i = 0; i < hostnames->Size; ++i)
  2052. {
  2053. HostName^ hostname = hostnames->GetAt(i);
  2054. if (hostname->Type == HostNameType::DomainName)
  2055. {
  2056. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  2057. std::string raw_name = converter.to_bytes(hostname->RawName->Data());
  2058. if (namelen > 0 && raw_name.size() < static_cast<std::size_t>(namelen))
  2059. {
  2060. strcpy_s(name, namelen, raw_name.c_str());
  2061. return 0;
  2062. }
  2063. }
  2064. }
  2065. return -1;
  2066. }
  2067. catch (Platform::Exception^ e)
  2068. {
  2069. ec = asio::error_code(e->HResult,
  2070. asio::system_category());
  2071. return -1;
  2072. }
  2073. #else // defined(ASIO_WINDOWS_RUNTIME)
  2074. int result = error_wrapper(::gethostname(name, namelen), ec);
  2075. # if defined(ASIO_WINDOWS)
  2076. if (result == 0)
  2077. ec = asio::error_code();
  2078. # endif // defined(ASIO_WINDOWS)
  2079. return result;
  2080. #endif // defined(ASIO_WINDOWS_RUNTIME)
  2081. }
  2082. #if !defined(ASIO_WINDOWS_RUNTIME)
  2083. #if !defined(ASIO_HAS_GETADDRINFO)
  2084. // The following functions are only needed for emulation of getaddrinfo and
  2085. // getnameinfo.
  2086. inline asio::error_code translate_netdb_error(int error)
  2087. {
  2088. switch (error)
  2089. {
  2090. case 0:
  2091. return asio::error_code();
  2092. case HOST_NOT_FOUND:
  2093. return asio::error::host_not_found;
  2094. case TRY_AGAIN:
  2095. return asio::error::host_not_found_try_again;
  2096. case NO_RECOVERY:
  2097. return asio::error::no_recovery;
  2098. case NO_DATA:
  2099. return asio::error::no_data;
  2100. default:
  2101. ASIO_ASSERT(false);
  2102. return asio::error::invalid_argument;
  2103. }
  2104. }
  2105. inline hostent* gethostbyaddr(const char* addr, int length, int af,
  2106. hostent* result, char* buffer, int buflength, asio::error_code& ec)
  2107. {
  2108. clear_last_error();
  2109. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2110. (void)(buffer);
  2111. (void)(buflength);
  2112. hostent* retval = error_wrapper(::gethostbyaddr(addr, length, af), ec);
  2113. if (!retval)
  2114. return 0;
  2115. ec = asio::error_code();
  2116. *result = *retval;
  2117. return retval;
  2118. #elif defined(__sun) || defined(__QNX__)
  2119. int error = 0;
  2120. hostent* retval = error_wrapper(::gethostbyaddr_r(addr, length, af, result,
  2121. buffer, buflength, &error), ec);
  2122. if (error)
  2123. ec = translate_netdb_error(error);
  2124. return retval;
  2125. #elif defined(__MACH__) && defined(__APPLE__)
  2126. (void)(buffer);
  2127. (void)(buflength);
  2128. int error = 0;
  2129. hostent* retval = error_wrapper(::getipnodebyaddr(
  2130. addr, length, af, &error), ec);
  2131. if (error)
  2132. ec = translate_netdb_error(error);
  2133. if (!retval)
  2134. return 0;
  2135. *result = *retval;
  2136. return retval;
  2137. #else
  2138. hostent* retval = 0;
  2139. int error = 0;
  2140. error_wrapper(::gethostbyaddr_r(addr, length, af, result, buffer,
  2141. buflength, &retval, &error), ec);
  2142. if (error)
  2143. ec = translate_netdb_error(error);
  2144. return retval;
  2145. #endif
  2146. }
  2147. inline hostent* gethostbyname(const char* name, int af, struct hostent* result,
  2148. char* buffer, int buflength, int ai_flags, asio::error_code& ec)
  2149. {
  2150. clear_last_error();
  2151. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2152. (void)(buffer);
  2153. (void)(buflength);
  2154. (void)(ai_flags);
  2155. if (af != ASIO_OS_DEF(AF_INET))
  2156. {
  2157. ec = asio::error::address_family_not_supported;
  2158. return 0;
  2159. }
  2160. hostent* retval = error_wrapper(::gethostbyname(name), ec);
  2161. if (!retval)
  2162. return 0;
  2163. ec = asio::error_code();
  2164. *result = *retval;
  2165. return result;
  2166. #elif defined(__sun) || defined(__QNX__)
  2167. (void)(ai_flags);
  2168. if (af != ASIO_OS_DEF(AF_INET))
  2169. {
  2170. ec = asio::error::address_family_not_supported;
  2171. return 0;
  2172. }
  2173. int error = 0;
  2174. hostent* retval = error_wrapper(::gethostbyname_r(name, result, buffer,
  2175. buflength, &error), ec);
  2176. if (error)
  2177. ec = translate_netdb_error(error);
  2178. return retval;
  2179. #elif defined(__MACH__) && defined(__APPLE__)
  2180. (void)(buffer);
  2181. (void)(buflength);
  2182. int error = 0;
  2183. hostent* retval = error_wrapper(::getipnodebyname(
  2184. name, af, ai_flags, &error), ec);
  2185. if (error)
  2186. ec = translate_netdb_error(error);
  2187. if (!retval)
  2188. return 0;
  2189. *result = *retval;
  2190. return retval;
  2191. #else
  2192. (void)(ai_flags);
  2193. if (af != ASIO_OS_DEF(AF_INET))
  2194. {
  2195. ec = asio::error::address_family_not_supported;
  2196. return 0;
  2197. }
  2198. hostent* retval = 0;
  2199. int error = 0;
  2200. error_wrapper(::gethostbyname_r(name, result,
  2201. buffer, buflength, &retval, &error), ec);
  2202. if (error)
  2203. ec = translate_netdb_error(error);
  2204. return retval;
  2205. #endif
  2206. }
  2207. inline void freehostent(hostent* h)
  2208. {
  2209. #if defined(__MACH__) && defined(__APPLE__)
  2210. if (h)
  2211. ::freehostent(h);
  2212. #else
  2213. (void)(h);
  2214. #endif
  2215. }
  2216. // Emulation of getaddrinfo based on implementation in:
  2217. // Stevens, W. R., UNIX Network Programming Vol. 1, 2nd Ed., Prentice-Hall 1998.
  2218. struct gai_search
  2219. {
  2220. const char* host;
  2221. int family;
  2222. };
  2223. inline int gai_nsearch(const char* host,
  2224. const addrinfo_type* hints, gai_search (&search)[2])
  2225. {
  2226. int search_count = 0;
  2227. if (host == 0 || host[0] == '\0')
  2228. {
  2229. if (hints->ai_flags & AI_PASSIVE)
  2230. {
  2231. // No host and AI_PASSIVE implies wildcard bind.
  2232. switch (hints->ai_family)
  2233. {
  2234. case ASIO_OS_DEF(AF_INET):
  2235. search[search_count].host = "0.0.0.0";
  2236. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2237. ++search_count;
  2238. break;
  2239. case ASIO_OS_DEF(AF_INET6):
  2240. search[search_count].host = "0::0";
  2241. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2242. ++search_count;
  2243. break;
  2244. case ASIO_OS_DEF(AF_UNSPEC):
  2245. search[search_count].host = "0::0";
  2246. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2247. ++search_count;
  2248. search[search_count].host = "0.0.0.0";
  2249. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2250. ++search_count;
  2251. break;
  2252. default:
  2253. break;
  2254. }
  2255. }
  2256. else
  2257. {
  2258. // No host and not AI_PASSIVE means connect to local host.
  2259. switch (hints->ai_family)
  2260. {
  2261. case ASIO_OS_DEF(AF_INET):
  2262. search[search_count].host = "localhost";
  2263. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2264. ++search_count;
  2265. break;
  2266. case ASIO_OS_DEF(AF_INET6):
  2267. search[search_count].host = "localhost";
  2268. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2269. ++search_count;
  2270. break;
  2271. case ASIO_OS_DEF(AF_UNSPEC):
  2272. search[search_count].host = "localhost";
  2273. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2274. ++search_count;
  2275. search[search_count].host = "localhost";
  2276. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2277. ++search_count;
  2278. break;
  2279. default:
  2280. break;
  2281. }
  2282. }
  2283. }
  2284. else
  2285. {
  2286. // Host is specified.
  2287. switch (hints->ai_family)
  2288. {
  2289. case ASIO_OS_DEF(AF_INET):
  2290. search[search_count].host = host;
  2291. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2292. ++search_count;
  2293. break;
  2294. case ASIO_OS_DEF(AF_INET6):
  2295. search[search_count].host = host;
  2296. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2297. ++search_count;
  2298. break;
  2299. case ASIO_OS_DEF(AF_UNSPEC):
  2300. search[search_count].host = host;
  2301. search[search_count].family = ASIO_OS_DEF(AF_INET6);
  2302. ++search_count;
  2303. search[search_count].host = host;
  2304. search[search_count].family = ASIO_OS_DEF(AF_INET);
  2305. ++search_count;
  2306. break;
  2307. default:
  2308. break;
  2309. }
  2310. }
  2311. return search_count;
  2312. }
  2313. template <typename T>
  2314. inline T* gai_alloc(std::size_t size = sizeof(T))
  2315. {
  2316. using namespace std;
  2317. T* p = static_cast<T*>(::operator new(size, std::nothrow));
  2318. if (p)
  2319. memset(p, 0, size);
  2320. return p;
  2321. }
  2322. inline void gai_free(void* p)
  2323. {
  2324. ::operator delete(p);
  2325. }
  2326. inline void gai_strcpy(char* target, const char* source, std::size_t max_size)
  2327. {
  2328. using namespace std;
  2329. #if defined(ASIO_HAS_SECURE_RTL)
  2330. strcpy_s(target, max_size, source);
  2331. #else // defined(ASIO_HAS_SECURE_RTL)
  2332. *target = 0;
  2333. strncat(target, source, max_size);
  2334. #endif // defined(ASIO_HAS_SECURE_RTL)
  2335. }
  2336. enum { gai_clone_flag = 1 << 30 };
  2337. inline int gai_aistruct(addrinfo_type*** next, const addrinfo_type* hints,
  2338. const void* addr, int family)
  2339. {
  2340. using namespace std;
  2341. addrinfo_type* ai = gai_alloc<addrinfo_type>();
  2342. if (ai == 0)
  2343. return EAI_MEMORY;
  2344. ai->ai_next = 0;
  2345. **next = ai;
  2346. *next = &ai->ai_next;
  2347. ai->ai_canonname = 0;
  2348. ai->ai_socktype = hints->ai_socktype;
  2349. if (ai->ai_socktype == 0)
  2350. ai->ai_flags |= gai_clone_flag;
  2351. ai->ai_protocol = hints->ai_protocol;
  2352. ai->ai_family = family;
  2353. switch (ai->ai_family)
  2354. {
  2355. case ASIO_OS_DEF(AF_INET):
  2356. {
  2357. sockaddr_in4_type* sinptr = gai_alloc<sockaddr_in4_type>();
  2358. if (sinptr == 0)
  2359. return EAI_MEMORY;
  2360. sinptr->sin_family = ASIO_OS_DEF(AF_INET);
  2361. memcpy(&sinptr->sin_addr, addr, sizeof(in4_addr_type));
  2362. ai->ai_addr = reinterpret_cast<sockaddr*>(sinptr);
  2363. ai->ai_addrlen = sizeof(sockaddr_in4_type);
  2364. break;
  2365. }
  2366. case ASIO_OS_DEF(AF_INET6):
  2367. {
  2368. sockaddr_in6_type* sin6ptr = gai_alloc<sockaddr_in6_type>();
  2369. if (sin6ptr == 0)
  2370. return EAI_MEMORY;
  2371. sin6ptr->sin6_family = ASIO_OS_DEF(AF_INET6);
  2372. memcpy(&sin6ptr->sin6_addr, addr, sizeof(in6_addr_type));
  2373. ai->ai_addr = reinterpret_cast<sockaddr*>(sin6ptr);
  2374. ai->ai_addrlen = sizeof(sockaddr_in6_type);
  2375. break;
  2376. }
  2377. default:
  2378. break;
  2379. }
  2380. return 0;
  2381. }
  2382. inline addrinfo_type* gai_clone(addrinfo_type* ai)
  2383. {
  2384. using namespace std;
  2385. addrinfo_type* new_ai = gai_alloc<addrinfo_type>();
  2386. if (new_ai == 0)
  2387. return new_ai;
  2388. new_ai->ai_next = ai->ai_next;
  2389. ai->ai_next = new_ai;
  2390. new_ai->ai_flags = 0;
  2391. new_ai->ai_family = ai->ai_family;
  2392. new_ai->ai_socktype = ai->ai_socktype;
  2393. new_ai->ai_protocol = ai->ai_protocol;
  2394. new_ai->ai_canonname = 0;
  2395. new_ai->ai_addrlen = ai->ai_addrlen;
  2396. new_ai->ai_addr = gai_alloc<sockaddr>(ai->ai_addrlen);
  2397. memcpy(new_ai->ai_addr, ai->ai_addr, ai->ai_addrlen);
  2398. return new_ai;
  2399. }
  2400. inline int gai_port(addrinfo_type* aihead, int port, int socktype)
  2401. {
  2402. int num_found = 0;
  2403. for (addrinfo_type* ai = aihead; ai; ai = ai->ai_next)
  2404. {
  2405. if (ai->ai_flags & gai_clone_flag)
  2406. {
  2407. if (ai->ai_socktype != 0)
  2408. {
  2409. ai = gai_clone(ai);
  2410. if (ai == 0)
  2411. return -1;
  2412. // ai now points to newly cloned entry.
  2413. }
  2414. }
  2415. else if (ai->ai_socktype != socktype)
  2416. {
  2417. // Ignore if mismatch on socket type.
  2418. continue;
  2419. }
  2420. ai->ai_socktype = socktype;
  2421. switch (ai->ai_family)
  2422. {
  2423. case ASIO_OS_DEF(AF_INET):
  2424. {
  2425. sockaddr_in4_type* sinptr =
  2426. reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
  2427. sinptr->sin_port = port;
  2428. ++num_found;
  2429. break;
  2430. }
  2431. case ASIO_OS_DEF(AF_INET6):
  2432. {
  2433. sockaddr_in6_type* sin6ptr =
  2434. reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
  2435. sin6ptr->sin6_port = port;
  2436. ++num_found;
  2437. break;
  2438. }
  2439. default:
  2440. break;
  2441. }
  2442. }
  2443. return num_found;
  2444. }
  2445. inline int gai_serv(addrinfo_type* aihead,
  2446. const addrinfo_type* hints, const char* serv)
  2447. {
  2448. using namespace std;
  2449. int num_found = 0;
  2450. if (
  2451. #if defined(AI_NUMERICSERV)
  2452. (hints->ai_flags & AI_NUMERICSERV) ||
  2453. #endif
  2454. isdigit(static_cast<unsigned char>(serv[0])))
  2455. {
  2456. int port = htons(atoi(serv));
  2457. if (hints->ai_socktype)
  2458. {
  2459. // Caller specifies socket type.
  2460. int rc = gai_port(aihead, port, hints->ai_socktype);
  2461. if (rc < 0)
  2462. return EAI_MEMORY;
  2463. num_found += rc;
  2464. }
  2465. else
  2466. {
  2467. // Caller does not specify socket type.
  2468. int rc = gai_port(aihead, port, SOCK_STREAM);
  2469. if (rc < 0)
  2470. return EAI_MEMORY;
  2471. num_found += rc;
  2472. rc = gai_port(aihead, port, SOCK_DGRAM);
  2473. if (rc < 0)
  2474. return EAI_MEMORY;
  2475. num_found += rc;
  2476. }
  2477. }
  2478. else
  2479. {
  2480. // Try service name with TCP first, then UDP.
  2481. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_STREAM)
  2482. {
  2483. servent* sptr = getservbyname(serv, "tcp");
  2484. if (sptr != 0)
  2485. {
  2486. int rc = gai_port(aihead, sptr->s_port, SOCK_STREAM);
  2487. if (rc < 0)
  2488. return EAI_MEMORY;
  2489. num_found += rc;
  2490. }
  2491. }
  2492. if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_DGRAM)
  2493. {
  2494. servent* sptr = getservbyname(serv, "udp");
  2495. if (sptr != 0)
  2496. {
  2497. int rc = gai_port(aihead, sptr->s_port, SOCK_DGRAM);
  2498. if (rc < 0)
  2499. return EAI_MEMORY;
  2500. num_found += rc;
  2501. }
  2502. }
  2503. }
  2504. if (num_found == 0)
  2505. {
  2506. if (hints->ai_socktype == 0)
  2507. {
  2508. // All calls to getservbyname() failed.
  2509. return EAI_NONAME;
  2510. }
  2511. else
  2512. {
  2513. // Service not supported for socket type.
  2514. return EAI_SERVICE;
  2515. }
  2516. }
  2517. return 0;
  2518. }
  2519. inline int gai_echeck(const char* host, const char* service,
  2520. int flags, int family, int socktype, int protocol)
  2521. {
  2522. (void)(flags);
  2523. (void)(protocol);
  2524. // Host or service must be specified.
  2525. if (host == 0 || host[0] == '\0')
  2526. if (service == 0 || service[0] == '\0')
  2527. return EAI_NONAME;
  2528. // Check combination of family and socket type.
  2529. switch (family)
  2530. {
  2531. case ASIO_OS_DEF(AF_UNSPEC):
  2532. break;
  2533. case ASIO_OS_DEF(AF_INET):
  2534. case ASIO_OS_DEF(AF_INET6):
  2535. if (service != 0 && service[0] != '\0')
  2536. if (socktype != 0 && socktype != SOCK_STREAM && socktype != SOCK_DGRAM)
  2537. return EAI_SOCKTYPE;
  2538. break;
  2539. default:
  2540. return EAI_FAMILY;
  2541. }
  2542. return 0;
  2543. }
  2544. inline void freeaddrinfo_emulation(addrinfo_type* aihead)
  2545. {
  2546. addrinfo_type* ai = aihead;
  2547. while (ai)
  2548. {
  2549. gai_free(ai->ai_addr);
  2550. gai_free(ai->ai_canonname);
  2551. addrinfo_type* ainext = ai->ai_next;
  2552. gai_free(ai);
  2553. ai = ainext;
  2554. }
  2555. }
  2556. inline int getaddrinfo_emulation(const char* host, const char* service,
  2557. const addrinfo_type* hintsp, addrinfo_type** result)
  2558. {
  2559. // Set up linked list of addrinfo structures.
  2560. addrinfo_type* aihead = 0;
  2561. addrinfo_type** ainext = &aihead;
  2562. char* canon = 0;
  2563. // Supply default hints if not specified by caller.
  2564. addrinfo_type hints = addrinfo_type();
  2565. hints.ai_family = ASIO_OS_DEF(AF_UNSPEC);
  2566. if (hintsp)
  2567. hints = *hintsp;
  2568. // If the resolution is not specifically for AF_INET6, remove the AI_V4MAPPED
  2569. // and AI_ALL flags.
  2570. #if defined(AI_V4MAPPED)
  2571. if (hints.ai_family != ASIO_OS_DEF(AF_INET6))
  2572. hints.ai_flags &= ~AI_V4MAPPED;
  2573. #endif
  2574. #if defined(AI_ALL)
  2575. if (hints.ai_family != ASIO_OS_DEF(AF_INET6))
  2576. hints.ai_flags &= ~AI_ALL;
  2577. #endif
  2578. // Basic error checking.
  2579. int rc = gai_echeck(host, service, hints.ai_flags, hints.ai_family,
  2580. hints.ai_socktype, hints.ai_protocol);
  2581. if (rc != 0)
  2582. {
  2583. freeaddrinfo_emulation(aihead);
  2584. return rc;
  2585. }
  2586. gai_search search[2];
  2587. int search_count = gai_nsearch(host, &hints, search);
  2588. for (gai_search* sptr = search; sptr < search + search_count; ++sptr)
  2589. {
  2590. // Check for IPv4 dotted decimal string.
  2591. in4_addr_type inaddr;
  2592. asio::error_code ec;
  2593. if (socket_ops::inet_pton(ASIO_OS_DEF(AF_INET),
  2594. sptr->host, &inaddr, 0, ec) == 1)
  2595. {
  2596. if (hints.ai_family != ASIO_OS_DEF(AF_UNSPEC)
  2597. && hints.ai_family != ASIO_OS_DEF(AF_INET))
  2598. {
  2599. freeaddrinfo_emulation(aihead);
  2600. gai_free(canon);
  2601. return EAI_FAMILY;
  2602. }
  2603. if (sptr->family == ASIO_OS_DEF(AF_INET))
  2604. {
  2605. rc = gai_aistruct(&ainext, &hints, &inaddr, ASIO_OS_DEF(AF_INET));
  2606. if (rc != 0)
  2607. {
  2608. freeaddrinfo_emulation(aihead);
  2609. gai_free(canon);
  2610. return rc;
  2611. }
  2612. }
  2613. continue;
  2614. }
  2615. // Check for IPv6 hex string.
  2616. in6_addr_type in6addr;
  2617. if (socket_ops::inet_pton(ASIO_OS_DEF(AF_INET6),
  2618. sptr->host, &in6addr, 0, ec) == 1)
  2619. {
  2620. if (hints.ai_family != ASIO_OS_DEF(AF_UNSPEC)
  2621. && hints.ai_family != ASIO_OS_DEF(AF_INET6))
  2622. {
  2623. freeaddrinfo_emulation(aihead);
  2624. gai_free(canon);
  2625. return EAI_FAMILY;
  2626. }
  2627. if (sptr->family == ASIO_OS_DEF(AF_INET6))
  2628. {
  2629. rc = gai_aistruct(&ainext, &hints, &in6addr,
  2630. ASIO_OS_DEF(AF_INET6));
  2631. if (rc != 0)
  2632. {
  2633. freeaddrinfo_emulation(aihead);
  2634. gai_free(canon);
  2635. return rc;
  2636. }
  2637. }
  2638. continue;
  2639. }
  2640. // Look up hostname.
  2641. hostent hent;
  2642. char hbuf[8192] = "";
  2643. hostent* hptr = socket_ops::gethostbyname(sptr->host,
  2644. sptr->family, &hent, hbuf, sizeof(hbuf), hints.ai_flags, ec);
  2645. if (hptr == 0)
  2646. {
  2647. if (search_count == 2)
  2648. {
  2649. // Failure is OK if there are multiple searches.
  2650. continue;
  2651. }
  2652. freeaddrinfo_emulation(aihead);
  2653. gai_free(canon);
  2654. if (ec == asio::error::host_not_found)
  2655. return EAI_NONAME;
  2656. if (ec == asio::error::host_not_found_try_again)
  2657. return EAI_AGAIN;
  2658. if (ec == asio::error::no_recovery)
  2659. return EAI_FAIL;
  2660. if (ec == asio::error::no_data)
  2661. return EAI_NONAME;
  2662. return EAI_NONAME;
  2663. }
  2664. // Check for address family mismatch if one was specified.
  2665. if (hints.ai_family != ASIO_OS_DEF(AF_UNSPEC)
  2666. && hints.ai_family != hptr->h_addrtype)
  2667. {
  2668. freeaddrinfo_emulation(aihead);
  2669. gai_free(canon);
  2670. socket_ops::freehostent(hptr);
  2671. return EAI_FAMILY;
  2672. }
  2673. // Save canonical name first time.
  2674. if (host != 0 && host[0] != '\0' && hptr->h_name && hptr->h_name[0]
  2675. && (hints.ai_flags & AI_CANONNAME) && canon == 0)
  2676. {
  2677. std::size_t canon_len = strlen(hptr->h_name) + 1;
  2678. canon = gai_alloc<char>(canon_len);
  2679. if (canon == 0)
  2680. {
  2681. freeaddrinfo_emulation(aihead);
  2682. socket_ops::freehostent(hptr);
  2683. return EAI_MEMORY;
  2684. }
  2685. gai_strcpy(canon, hptr->h_name, canon_len);
  2686. }
  2687. // Create an addrinfo structure for each returned address.
  2688. for (char** ap = hptr->h_addr_list; *ap; ++ap)
  2689. {
  2690. rc = gai_aistruct(&ainext, &hints, *ap, hptr->h_addrtype);
  2691. if (rc != 0)
  2692. {
  2693. freeaddrinfo_emulation(aihead);
  2694. gai_free(canon);
  2695. socket_ops::freehostent(hptr);
  2696. return EAI_FAMILY;
  2697. }
  2698. }
  2699. socket_ops::freehostent(hptr);
  2700. }
  2701. // Check if we found anything.
  2702. if (aihead == 0)
  2703. {
  2704. gai_free(canon);
  2705. return EAI_NONAME;
  2706. }
  2707. // Return canonical name in first entry.
  2708. if (host != 0 && host[0] != '\0' && (hints.ai_flags & AI_CANONNAME))
  2709. {
  2710. if (canon)
  2711. {
  2712. aihead->ai_canonname = canon;
  2713. canon = 0;
  2714. }
  2715. else
  2716. {
  2717. std::size_t canonname_len = strlen(search[0].host) + 1;
  2718. aihead->ai_canonname = gai_alloc<char>(canonname_len);
  2719. if (aihead->ai_canonname == 0)
  2720. {
  2721. freeaddrinfo_emulation(aihead);
  2722. return EAI_MEMORY;
  2723. }
  2724. gai_strcpy(aihead->ai_canonname, search[0].host, canonname_len);
  2725. }
  2726. }
  2727. gai_free(canon);
  2728. // Process the service name.
  2729. if (service != 0 && service[0] != '\0')
  2730. {
  2731. rc = gai_serv(aihead, &hints, service);
  2732. if (rc != 0)
  2733. {
  2734. freeaddrinfo_emulation(aihead);
  2735. return rc;
  2736. }
  2737. }
  2738. // Return result to caller.
  2739. *result = aihead;
  2740. return 0;
  2741. }
  2742. inline asio::error_code getnameinfo_emulation(
  2743. const socket_addr_type* sa, std::size_t salen, char* host,
  2744. std::size_t hostlen, char* serv, std::size_t servlen, int flags,
  2745. asio::error_code& ec)
  2746. {
  2747. using namespace std;
  2748. const char* addr;
  2749. size_t addr_len;
  2750. unsigned short port;
  2751. switch (sa->sa_family)
  2752. {
  2753. case ASIO_OS_DEF(AF_INET):
  2754. if (salen != sizeof(sockaddr_in4_type))
  2755. {
  2756. return ec = asio::error::invalid_argument;
  2757. }
  2758. addr = reinterpret_cast<const char*>(
  2759. &reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_addr);
  2760. addr_len = sizeof(in4_addr_type);
  2761. port = reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_port;
  2762. break;
  2763. case ASIO_OS_DEF(AF_INET6):
  2764. if (salen != sizeof(sockaddr_in6_type))
  2765. {
  2766. return ec = asio::error::invalid_argument;
  2767. }
  2768. addr = reinterpret_cast<const char*>(
  2769. &reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_addr);
  2770. addr_len = sizeof(in6_addr_type);
  2771. port = reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_port;
  2772. break;
  2773. default:
  2774. return ec = asio::error::address_family_not_supported;
  2775. }
  2776. if (host && hostlen > 0)
  2777. {
  2778. if (flags & NI_NUMERICHOST)
  2779. {
  2780. if (socket_ops::inet_ntop(sa->sa_family, addr, host, hostlen, 0, ec) == 0)
  2781. {
  2782. return ec;
  2783. }
  2784. }
  2785. else
  2786. {
  2787. hostent hent;
  2788. char hbuf[8192] = "";
  2789. hostent* hptr = socket_ops::gethostbyaddr(addr,
  2790. static_cast<int>(addr_len), sa->sa_family,
  2791. &hent, hbuf, sizeof(hbuf), ec);
  2792. if (hptr && hptr->h_name && hptr->h_name[0] != '\0')
  2793. {
  2794. if (flags & NI_NOFQDN)
  2795. {
  2796. char* dot = strchr(hptr->h_name, '.');
  2797. if (dot)
  2798. {
  2799. *dot = 0;
  2800. }
  2801. }
  2802. gai_strcpy(host, hptr->h_name, hostlen);
  2803. socket_ops::freehostent(hptr);
  2804. }
  2805. else
  2806. {
  2807. socket_ops::freehostent(hptr);
  2808. if (flags & NI_NAMEREQD)
  2809. {
  2810. return ec = asio::error::host_not_found;
  2811. }
  2812. if (socket_ops::inet_ntop(sa->sa_family,
  2813. addr, host, hostlen, 0, ec) == 0)
  2814. {
  2815. return ec;
  2816. }
  2817. }
  2818. }
  2819. }
  2820. if (serv && servlen > 0)
  2821. {
  2822. if (flags & NI_NUMERICSERV)
  2823. {
  2824. if (servlen < 6)
  2825. {
  2826. return ec = asio::error::no_buffer_space;
  2827. }
  2828. #if defined(ASIO_HAS_SECURE_RTL)
  2829. sprintf_s(serv, servlen, "%u", ntohs(port));
  2830. #else // defined(ASIO_HAS_SECURE_RTL)
  2831. sprintf(serv, "%u", ntohs(port));
  2832. #endif // defined(ASIO_HAS_SECURE_RTL)
  2833. }
  2834. else
  2835. {
  2836. #if defined(ASIO_HAS_PTHREADS)
  2837. static ::pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2838. ::pthread_mutex_lock(&mutex);
  2839. #endif // defined(ASIO_HAS_PTHREADS)
  2840. servent* sptr = ::getservbyport(port, (flags & NI_DGRAM) ? "udp" : 0);
  2841. if (sptr && sptr->s_name && sptr->s_name[0] != '\0')
  2842. {
  2843. gai_strcpy(serv, sptr->s_name, servlen);
  2844. }
  2845. else
  2846. {
  2847. if (servlen < 6)
  2848. {
  2849. return ec = asio::error::no_buffer_space;
  2850. }
  2851. #if defined(ASIO_HAS_SECURE_RTL)
  2852. sprintf_s(serv, servlen, "%u", ntohs(port));
  2853. #else // defined(ASIO_HAS_SECURE_RTL)
  2854. sprintf(serv, "%u", ntohs(port));
  2855. #endif // defined(ASIO_HAS_SECURE_RTL)
  2856. }
  2857. #if defined(ASIO_HAS_PTHREADS)
  2858. ::pthread_mutex_unlock(&mutex);
  2859. #endif // defined(ASIO_HAS_PTHREADS)
  2860. }
  2861. }
  2862. ec = asio::error_code();
  2863. return ec;
  2864. }
  2865. #endif // !defined(ASIO_HAS_GETADDRINFO)
  2866. inline asio::error_code translate_addrinfo_error(int error)
  2867. {
  2868. switch (error)
  2869. {
  2870. case 0:
  2871. return asio::error_code();
  2872. case EAI_AGAIN:
  2873. return asio::error::host_not_found_try_again;
  2874. case EAI_BADFLAGS:
  2875. return asio::error::invalid_argument;
  2876. case EAI_FAIL:
  2877. return asio::error::no_recovery;
  2878. case EAI_FAMILY:
  2879. return asio::error::address_family_not_supported;
  2880. case EAI_MEMORY:
  2881. return asio::error::no_memory;
  2882. case EAI_NONAME:
  2883. #if defined(EAI_ADDRFAMILY)
  2884. case EAI_ADDRFAMILY:
  2885. #endif
  2886. #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
  2887. case EAI_NODATA:
  2888. #endif
  2889. return asio::error::host_not_found;
  2890. case EAI_SERVICE:
  2891. return asio::error::service_not_found;
  2892. case EAI_SOCKTYPE:
  2893. return asio::error::socket_type_not_supported;
  2894. default: // Possibly the non-portable EAI_SYSTEM.
  2895. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2896. return asio::error_code(
  2897. WSAGetLastError(), asio::error::get_system_category());
  2898. #else
  2899. return asio::error_code(
  2900. errno, asio::error::get_system_category());
  2901. #endif
  2902. }
  2903. }
  2904. asio::error_code getaddrinfo(const char* host,
  2905. const char* service, const addrinfo_type& hints,
  2906. addrinfo_type** result, asio::error_code& ec)
  2907. {
  2908. host = (host && *host) ? host : 0;
  2909. service = (service && *service) ? service : 0;
  2910. clear_last_error();
  2911. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2912. # if defined(ASIO_HAS_GETADDRINFO)
  2913. // Building for Windows XP, Windows Server 2003, or later.
  2914. int error = ::getaddrinfo(host, service, &hints, result);
  2915. return ec = translate_addrinfo_error(error);
  2916. # else
  2917. // Building for Windows 2000 or earlier.
  2918. typedef int (WSAAPI *gai_t)(const char*,
  2919. const char*, const addrinfo_type*, addrinfo_type**);
  2920. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2921. {
  2922. if (gai_t gai = (gai_t)::GetProcAddress(winsock_module, "getaddrinfo"))
  2923. {
  2924. int error = gai(host, service, &hints, result);
  2925. return ec = translate_addrinfo_error(error);
  2926. }
  2927. }
  2928. int error = getaddrinfo_emulation(host, service, &hints, result);
  2929. return ec = translate_addrinfo_error(error);
  2930. # endif
  2931. #elif !defined(ASIO_HAS_GETADDRINFO)
  2932. int error = getaddrinfo_emulation(host, service, &hints, result);
  2933. return ec = translate_addrinfo_error(error);
  2934. #else
  2935. int error = ::getaddrinfo(host, service, &hints, result);
  2936. return ec = translate_addrinfo_error(error);
  2937. #endif
  2938. }
  2939. asio::error_code background_getaddrinfo(
  2940. const weak_cancel_token_type& cancel_token, const char* host,
  2941. const char* service, const addrinfo_type& hints,
  2942. addrinfo_type** result, asio::error_code& ec)
  2943. {
  2944. if (cancel_token.expired())
  2945. ec = asio::error::operation_aborted;
  2946. else
  2947. socket_ops::getaddrinfo(host, service, hints, result, ec);
  2948. return ec;
  2949. }
  2950. void freeaddrinfo(addrinfo_type* ai)
  2951. {
  2952. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2953. # if defined(ASIO_HAS_GETADDRINFO)
  2954. // Building for Windows XP, Windows Server 2003, or later.
  2955. ::freeaddrinfo(ai);
  2956. # else
  2957. // Building for Windows 2000 or earlier.
  2958. typedef int (WSAAPI *fai_t)(addrinfo_type*);
  2959. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2960. {
  2961. if (fai_t fai = (fai_t)::GetProcAddress(winsock_module, "freeaddrinfo"))
  2962. {
  2963. fai(ai);
  2964. return;
  2965. }
  2966. }
  2967. freeaddrinfo_emulation(ai);
  2968. # endif
  2969. #elif !defined(ASIO_HAS_GETADDRINFO)
  2970. freeaddrinfo_emulation(ai);
  2971. #else
  2972. ::freeaddrinfo(ai);
  2973. #endif
  2974. }
  2975. asio::error_code getnameinfo(const socket_addr_type* addr,
  2976. std::size_t addrlen, char* host, std::size_t hostlen,
  2977. char* serv, std::size_t servlen, int flags, asio::error_code& ec)
  2978. {
  2979. #if defined(ASIO_WINDOWS) || defined(__CYGWIN__)
  2980. # if defined(ASIO_HAS_GETADDRINFO)
  2981. // Building for Windows XP, Windows Server 2003, or later.
  2982. clear_last_error();
  2983. int error = ::getnameinfo(addr, static_cast<socklen_t>(addrlen),
  2984. host, static_cast<DWORD>(hostlen),
  2985. serv, static_cast<DWORD>(servlen), flags);
  2986. return ec = translate_addrinfo_error(error);
  2987. # else
  2988. // Building for Windows 2000 or earlier.
  2989. typedef int (WSAAPI *gni_t)(const socket_addr_type*,
  2990. int, char*, DWORD, char*, DWORD, int);
  2991. if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
  2992. {
  2993. if (gni_t gni = (gni_t)::GetProcAddress(winsock_module, "getnameinfo"))
  2994. {
  2995. clear_last_error();
  2996. int error = gni(addr, static_cast<int>(addrlen),
  2997. host, static_cast<DWORD>(hostlen),
  2998. serv, static_cast<DWORD>(servlen), flags);
  2999. return ec = translate_addrinfo_error(error);
  3000. }
  3001. }
  3002. clear_last_error();
  3003. return getnameinfo_emulation(addr, addrlen,
  3004. host, hostlen, serv, servlen, flags, ec);
  3005. # endif
  3006. #elif !defined(ASIO_HAS_GETADDRINFO)
  3007. using namespace std; // For memcpy.
  3008. sockaddr_storage_type tmp_addr;
  3009. memcpy(&tmp_addr, addr, addrlen);
  3010. tmp_addr.ss_len = addrlen;
  3011. addr = reinterpret_cast<socket_addr_type*>(&tmp_addr);
  3012. clear_last_error();
  3013. return getnameinfo_emulation(addr, addrlen,
  3014. host, hostlen, serv, servlen, flags, ec);
  3015. #else
  3016. clear_last_error();
  3017. int error = ::getnameinfo(addr, addrlen, host, hostlen, serv, servlen, flags);
  3018. return ec = translate_addrinfo_error(error);
  3019. #endif
  3020. }
  3021. asio::error_code sync_getnameinfo(
  3022. const socket_addr_type* addr, std::size_t addrlen,
  3023. char* host, std::size_t hostlen, char* serv,
  3024. std::size_t servlen, int sock_type, asio::error_code& ec)
  3025. {
  3026. // First try resolving with the service name. If that fails try resolving
  3027. // but allow the service to be returned as a number.
  3028. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  3029. socket_ops::getnameinfo(addr, addrlen, host,
  3030. hostlen, serv, servlen, flags, ec);
  3031. if (ec)
  3032. {
  3033. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  3034. serv, servlen, flags | NI_NUMERICSERV, ec);
  3035. }
  3036. return ec;
  3037. }
  3038. asio::error_code background_getnameinfo(
  3039. const weak_cancel_token_type& cancel_token,
  3040. const socket_addr_type* addr, std::size_t addrlen,
  3041. char* host, std::size_t hostlen, char* serv,
  3042. std::size_t servlen, int sock_type, asio::error_code& ec)
  3043. {
  3044. if (cancel_token.expired())
  3045. {
  3046. ec = asio::error::operation_aborted;
  3047. }
  3048. else
  3049. {
  3050. // First try resolving with the service name. If that fails try resolving
  3051. // but allow the service to be returned as a number.
  3052. int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
  3053. socket_ops::getnameinfo(addr, addrlen, host,
  3054. hostlen, serv, servlen, flags, ec);
  3055. if (ec)
  3056. {
  3057. socket_ops::getnameinfo(addr, addrlen, host, hostlen,
  3058. serv, servlen, flags | NI_NUMERICSERV, ec);
  3059. }
  3060. }
  3061. return ec;
  3062. }
  3063. #endif // !defined(ASIO_WINDOWS_RUNTIME)
  3064. u_long_type network_to_host_long(u_long_type value)
  3065. {
  3066. #if defined(ASIO_WINDOWS_RUNTIME)
  3067. unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
  3068. u_long_type result = (static_cast<u_long_type>(value_p[0]) << 24)
  3069. | (static_cast<u_long_type>(value_p[1]) << 16)
  3070. | (static_cast<u_long_type>(value_p[2]) << 8)
  3071. | static_cast<u_long_type>(value_p[3]);
  3072. return result;
  3073. #else // defined(ASIO_WINDOWS_RUNTIME)
  3074. return ntohl(value);
  3075. #endif // defined(ASIO_WINDOWS_RUNTIME)
  3076. }
  3077. u_long_type host_to_network_long(u_long_type value)
  3078. {
  3079. #if defined(ASIO_WINDOWS_RUNTIME)
  3080. u_long_type result;
  3081. unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
  3082. result_p[0] = static_cast<unsigned char>((value >> 24) & 0xFF);
  3083. result_p[1] = static_cast<unsigned char>((value >> 16) & 0xFF);
  3084. result_p[2] = static_cast<unsigned char>((value >> 8) & 0xFF);
  3085. result_p[3] = static_cast<unsigned char>(value & 0xFF);
  3086. return result;
  3087. #else // defined(ASIO_WINDOWS_RUNTIME)
  3088. return htonl(value);
  3089. #endif // defined(ASIO_WINDOWS_RUNTIME)
  3090. }
  3091. u_short_type network_to_host_short(u_short_type value)
  3092. {
  3093. #if defined(ASIO_WINDOWS_RUNTIME)
  3094. unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
  3095. u_short_type result = (static_cast<u_short_type>(value_p[0]) << 8)
  3096. | static_cast<u_short_type>(value_p[1]);
  3097. return result;
  3098. #else // defined(ASIO_WINDOWS_RUNTIME)
  3099. return ntohs(value);
  3100. #endif // defined(ASIO_WINDOWS_RUNTIME)
  3101. }
  3102. u_short_type host_to_network_short(u_short_type value)
  3103. {
  3104. #if defined(ASIO_WINDOWS_RUNTIME)
  3105. u_short_type result;
  3106. unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
  3107. result_p[0] = static_cast<unsigned char>((value >> 8) & 0xFF);
  3108. result_p[1] = static_cast<unsigned char>(value & 0xFF);
  3109. return result;
  3110. #else // defined(ASIO_WINDOWS_RUNTIME)
  3111. return htons(value);
  3112. #endif // defined(ASIO_WINDOWS_RUNTIME)
  3113. }
  3114. } // namespace socket_ops
  3115. } // namespace detail
  3116. } // namespace asio
  3117. #include "asio/detail/pop_options.hpp"
  3118. #endif // ASIO_DETAIL_SOCKET_OPS_IPP