socket_ops.ipp 108 KB

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