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

socket_ops.ipp 97KB

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