SocketImpl.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429
  1. #include "il2cpp-config.h"
  2. #if !IL2CPP_USE_GENERIC_SOCKET_IMPL && IL2CPP_TARGET_WINDOWS && IL2CPP_SUPPORT_SOCKETS
  3. #include <time.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <sys/stat.h>
  8. #include "WindowsHelpers.h"
  9. #include <WinSock2.h>
  10. #include <WS2tcpip.h>
  11. #if !IL2CPP_TARGET_XBOXONE
  12. #include <mswsock.h>
  13. #endif
  14. #include "os/Error.h"
  15. #include "os/Socket.h"
  16. #include "os/ErrorCodes.h"
  17. #include "os/Win32/SocketImpl.h"
  18. #include "utils/Il2CppError.h"
  19. #include "utils/StringUtils.h"
  20. #include "utils/Memory.h"
  21. typedef int socklen_t;
  22. namespace il2cpp
  23. {
  24. namespace os
  25. {
  26. static bool is_loopback(int32_t family, uint8_t *addr)
  27. {
  28. if (family == AF_INET)
  29. return addr[0] == 127;
  30. #if IL2CPP_SUPPORT_IPV6
  31. else if (family == AF_INET6)
  32. return (IN6_IS_ADDR_LOOPBACK((struct in6_addr *)addr));
  33. #endif
  34. return false;
  35. }
  36. static struct in_addr *get_local_ips(int32_t family, int32_t *nips)
  37. {
  38. *nips = 0;
  39. return 0;
  40. }
  41. static bool hostent_get_info(struct hostent *he, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addresses)
  42. {
  43. if (he == NULL)
  44. return false;
  45. if (he->h_length != 4 || he->h_addrtype != AF_INET)
  46. return false;
  47. name.assign(he->h_name);
  48. for (int32_t i = 0; he->h_aliases[i] != NULL; ++i)
  49. aliases.push_back(he->h_aliases[i]);
  50. if (he->h_addrtype == AF_INET)
  51. {
  52. struct in_addr addr = {0};
  53. for (int32_t i = 0; he->h_addr_list[i] != NULL; ++i)
  54. {
  55. addr.s_addr = *(u_long*)he->h_addr_list[i];
  56. addresses.push_back(inet_ntoa(addr));
  57. }
  58. }
  59. return true;
  60. }
  61. static bool hostent_get_info_with_local_ips(struct hostent *he, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addresses)
  62. {
  63. int32_t i = 0;
  64. int32_t nlocal_in = 0;
  65. if (he != NULL)
  66. {
  67. if (he->h_length != 4 || he->h_addrtype != AF_INET)
  68. return false;
  69. name.assign(he->h_name);
  70. for (int32_t i = 0; he->h_aliases[i] != NULL; ++i)
  71. aliases.push_back(he->h_aliases[i]);
  72. }
  73. struct in_addr *local_in = get_local_ips(AF_INET, &nlocal_in);
  74. if (nlocal_in)
  75. {
  76. for (int32_t i = 0; i < nlocal_in; ++i)
  77. addresses.push_back(inet_ntoa(local_in[i]));
  78. free(local_in);
  79. }
  80. else if (he == NULL)
  81. {
  82. // If requesting "" and there are no other interfaces up, MS returns 127.0.0.1
  83. addresses.push_back("127.0.0.1");
  84. return true;
  85. }
  86. if (nlocal_in == 0 && he != NULL)
  87. {
  88. if (he->h_addrtype == AF_INET)
  89. {
  90. struct in_addr addr = {0};
  91. for (int32_t i = 0; he->h_addr_list[i] != NULL; ++i)
  92. {
  93. addr.s_addr = *(u_long*)he->h_addr_list[i];
  94. addresses.push_back(inet_ntoa(addr));
  95. }
  96. }
  97. }
  98. return true;
  99. }
  100. static int32_t convert_socket_flags(os::SocketFlags flags)
  101. {
  102. int32_t c_flags = 0;
  103. if (flags)
  104. {
  105. // Check if contains invalid flag values
  106. if (flags & ~(os::kSocketFlagsOutOfBand | os::kSocketFlagsMaxIOVectorLength | os::kSocketFlagsPeek | os::kSocketFlagsDontRoute | os::kSocketFlagsPartial))
  107. {
  108. return -1;
  109. }
  110. if (flags & os::kSocketFlagsOutOfBand)
  111. c_flags |= MSG_OOB;
  112. if (flags & os::kSocketFlagsPeek)
  113. c_flags |= MSG_PEEK;
  114. if (flags & os::kSocketFlagsDontRoute)
  115. c_flags |= MSG_DONTROUTE;
  116. // Ignore Partial - see bug 349688. Don't return -1, because
  117. // according to the comment in that bug ms runtime doesn't for
  118. // UDP sockets (this means we will silently ignore it for TCP
  119. // too)
  120. #ifdef MSG_MORE
  121. if (flags & os::kSocketFlagsPartial)
  122. c_flags |= MSG_MORE;
  123. #endif
  124. }
  125. return c_flags;
  126. }
  127. #if IL2CPP_SUPPORT_IPV6
  128. static void AddrinfoGetAddresses(struct addrinfo *info, std::string& name, bool add_local_ips,
  129. std::vector<std::string> &addr_list)
  130. {
  131. if (add_local_ips)
  132. {
  133. int nlocal_in = 0;
  134. int nlocal_in6 = 0;
  135. in_addr* local_in = (struct in_addr *)get_local_ips(AF_INET, &nlocal_in);
  136. in6_addr* local_in6 = (struct in6_addr *)get_local_ips(AF_INET6, &nlocal_in6);
  137. if (nlocal_in || nlocal_in6)
  138. {
  139. if (nlocal_in)
  140. {
  141. for (int i = 0; i < nlocal_in; i++)
  142. {
  143. char addr[16];
  144. inet_ntop(AF_INET, &local_in[i], addr, sizeof(addr));
  145. addr_list.push_back(std::string(addr));
  146. }
  147. }
  148. if (nlocal_in6)
  149. {
  150. for (int i = 0; i < nlocal_in6; i++)
  151. {
  152. char addr[48];
  153. const char* ret = inet_ntop(AF_INET6, &local_in6[i], addr, sizeof(addr));
  154. if (ret != NULL)
  155. addr_list.push_back(std::string(addr));
  156. }
  157. }
  158. }
  159. free(local_in);
  160. free(local_in6);
  161. }
  162. bool nameSet = false;
  163. for (addrinfo* ai = info; ai != NULL; ai = ai->ai_next)
  164. {
  165. const char *ret;
  166. char buffer[48]; /* Max. size for IPv6 */
  167. if ((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6))
  168. continue;
  169. if (ai->ai_family == PF_INET)
  170. ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
  171. else
  172. ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
  173. if (ret)
  174. addr_list.push_back(std::string(buffer));
  175. else
  176. addr_list.push_back(std::string());
  177. if (!nameSet)
  178. {
  179. if (ai->ai_canonname != NULL)
  180. name = std::string(ai->ai_canonname);
  181. else
  182. name = std::string();
  183. nameSet = true;
  184. }
  185. }
  186. }
  187. WaitStatus GetAddressInfo(const char* hostname, bool add_local_ips, std::string &name, std::vector<std::string> &addr_list)
  188. {
  189. addrinfo *info = NULL;
  190. addrinfo hints;
  191. memset(&hints, 0, sizeof(hints));
  192. // Here Mono inspects the ipv4Supported and ipv6Supported properties on the managed Socket class.
  193. // This seems to be unnecessary though, as we can use PF_UNSPEC in all cases, and getaddrinfo works.
  194. hints.ai_family = PF_UNSPEC;
  195. hints.ai_socktype = SOCK_STREAM;
  196. hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
  197. if (getaddrinfo(hostname, NULL, &hints, &info) == -1)
  198. return kWaitStatusFailure;
  199. AddrinfoGetAddresses(info, name, add_local_ips, addr_list);
  200. if (info)
  201. freeaddrinfo(info);
  202. if (name.empty())
  203. name.assign(hostname);
  204. return kWaitStatusSuccess;
  205. }
  206. #endif
  207. static WaitStatus GetHostByAddrIPv4(const std::string &address, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addr_list)
  208. {
  209. struct in_addr inaddr;
  210. if (inet_pton(AF_INET, address.c_str(), &inaddr) <= 0)
  211. return kWaitStatusFailure;
  212. struct hostent *he = gethostbyaddr((char*)&inaddr, sizeof(inaddr), AF_INET);
  213. if (he == NULL)
  214. {
  215. name = address;
  216. addr_list.push_back(name);
  217. return kWaitStatusSuccess;
  218. }
  219. return hostent_get_info(he, name, aliases, addr_list)
  220. ? kWaitStatusSuccess
  221. : kWaitStatusFailure;
  222. }
  223. WaitStatus SocketImpl::GetHostByAddr(const std::string &address, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addr_list)
  224. {
  225. #if IL2CPP_SUPPORT_IPV6
  226. struct sockaddr_in saddr;
  227. struct sockaddr_in6 saddr6;
  228. int32_t family;
  229. char hostname[1024] = { 0 };
  230. int flags = 0;
  231. if (inet_pton(AF_INET, address.c_str(), &saddr.sin_addr) <= 0)
  232. {
  233. /* Maybe an ipv6 address */
  234. if (inet_pton(AF_INET6, address.c_str(), &saddr6.sin6_addr) <= 0)
  235. {
  236. return kWaitStatusFailure;
  237. }
  238. else
  239. {
  240. family = AF_INET6;
  241. saddr6.sin6_family = AF_INET6;
  242. }
  243. }
  244. else
  245. {
  246. family = AF_INET;
  247. saddr.sin_family = AF_INET;
  248. }
  249. if (family == AF_INET)
  250. {
  251. return GetHostByAddrIPv4(address, name, aliases, addr_list);
  252. }
  253. else if (family == AF_INET6)
  254. {
  255. #if HAVE_SOCKADDR_IN6_SIN_LEN
  256. saddr6.sin6_len = sizeof(saddr6);
  257. #endif
  258. if (getnameinfo((struct sockaddr*)&saddr6, sizeof(saddr6),
  259. hostname, sizeof(hostname), NULL, 0,
  260. flags) != 0)
  261. {
  262. return kWaitStatusFailure;
  263. }
  264. }
  265. return GetAddressInfo(hostname, true, name, addr_list);
  266. #else
  267. return GetHostByAddrIPv4(address, name, aliases, addr_list);
  268. #endif
  269. }
  270. WaitStatus SocketImpl::GetHostByName(const std::string &host, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addresses)
  271. {
  272. char this_hostname[256] = {0};
  273. const char *hostname = host.c_str();
  274. bool add_local_ips = (*hostname == '\0');
  275. if (!add_local_ips && gethostname(this_hostname, sizeof(this_hostname)) != -1)
  276. {
  277. if (!strcmp(hostname, this_hostname))
  278. add_local_ips = true;
  279. }
  280. #if IL2CPP_SUPPORT_IPV6
  281. return GetAddressInfo(hostname, add_local_ips, name, addresses);
  282. #else
  283. struct hostent *he = NULL;
  284. if (*hostname)
  285. he = gethostbyname(hostname);
  286. if (*hostname && he == NULL)
  287. return kWaitStatusFailure;
  288. return (add_local_ips
  289. ? hostent_get_info_with_local_ips(he, name, aliases, addresses)
  290. : hostent_get_info(he, name, aliases, addresses))
  291. ? kWaitStatusSuccess
  292. : kWaitStatusFailure;
  293. #endif
  294. }
  295. WaitStatus SocketImpl::GetHostByName(const std::string &host, std::string &name, int32_t &family, std::vector<std::string> &aliases, std::vector<void*> &addr_list, int32_t &addr_size)
  296. {
  297. std::vector<std::string> addresses;
  298. WaitStatus result = GetHostByName(host, name, aliases, addresses);
  299. addr_size = sizeof(in_addr);
  300. family = AF_INET;
  301. for (std::vector<std::string>::iterator it = addresses.begin(); it != addresses.end(); ++it)
  302. {
  303. void* addressLocation = il2cpp::utils::Memory::Malloc(addr_size);
  304. in_addr address;
  305. if (inet_pton(family, it->c_str(), &address))
  306. {
  307. memcpy(addressLocation, &address.S_un.S_addr, addr_size);
  308. addr_list.push_back(addressLocation);
  309. }
  310. }
  311. return result;
  312. }
  313. void SocketImpl::Startup()
  314. {
  315. WSADATA wsadata;
  316. const int32_t ret = WSAStartup(MAKEWORD(2, 0), &wsadata);
  317. if (ret != 0)
  318. {
  319. exit(-1);
  320. }
  321. }
  322. void SocketImpl::Cleanup()
  323. {
  324. WSACleanup();
  325. }
  326. WaitStatus SocketImpl::GetHostName(std::string &name)
  327. {
  328. char hostname[256];
  329. int32_t ret = gethostname(hostname, sizeof(hostname));
  330. if (ret == -1)
  331. return kWaitStatusFailure;
  332. name.assign(hostname);
  333. return kWaitStatusSuccess;
  334. }
  335. SocketImpl::SocketImpl(ThreadStatusCallback thread_status_callback)
  336. : _is_valid(false)
  337. , _fd(-1)
  338. , _domain(-1)
  339. , _type(-1)
  340. , _protocol(-1)
  341. , _saved_error(kErrorCodeSuccess)
  342. , _still_readable(0)
  343. , _thread_status_callback(thread_status_callback)
  344. {
  345. }
  346. SocketImpl::~SocketImpl()
  347. {
  348. }
  349. static int32_t convert_address_family(AddressFamily family)
  350. {
  351. switch (family)
  352. {
  353. case kAddressFamilyUnspecified:
  354. return AF_UNSPEC;
  355. // NOTE(gab): not supported on Windows
  356. //case kAddressFamilyUnix:
  357. // return AF_UNIX;
  358. case kAddressFamilyInterNetwork:
  359. return AF_INET;
  360. case kAddressFamilyIpx:
  361. return AF_IPX;
  362. case kAddressFamilySna:
  363. return AF_SNA;
  364. case kAddressFamilyDecNet:
  365. return AF_DECnet;
  366. case kAddressFamilyAppleTalk:
  367. return AF_APPLETALK;
  368. #if IL2CPP_SUPPORT_IPV6
  369. case kAddressFamilyInterNetworkV6:
  370. return AF_INET6;
  371. #endif
  372. #ifdef AF_IRDA
  373. case kAddressFamilyIrda:
  374. return AF_IRDA;
  375. #endif
  376. default:
  377. break;
  378. }
  379. return -1;
  380. }
  381. static int32_t convert_socket_type(SocketType type)
  382. {
  383. switch (type)
  384. {
  385. case kSocketTypeStream:
  386. return SOCK_STREAM;
  387. case kSocketTypeDgram:
  388. return SOCK_DGRAM;
  389. case kSocketTypeRaw:
  390. return SOCK_RAW;
  391. case kSocketTypeRdm:
  392. return SOCK_RDM;
  393. case kSocketTypeSeqpacket:
  394. return SOCK_SEQPACKET;
  395. default:
  396. break;
  397. }
  398. return -1;
  399. }
  400. static int32_t convert_socket_protocol(ProtocolType protocol)
  401. {
  402. switch (protocol)
  403. {
  404. case kProtocolTypeIP:
  405. case kProtocolTypeIPv6:
  406. case kProtocolTypeIcmp:
  407. case kProtocolTypeIgmp:
  408. case kProtocolTypeGgp:
  409. case kProtocolTypeTcp:
  410. case kProtocolTypePup:
  411. case kProtocolTypeUdp:
  412. case kProtocolTypeIdp:
  413. case kProtocolTypeIcmpV6:
  414. // In this case the enum values map exactly.
  415. return (int32_t)protocol;
  416. default:
  417. break;
  418. }
  419. // Everything else in unsupported and unexpected
  420. return -1;
  421. }
  422. static int SocketExceptionFilter(unsigned int code)
  423. {
  424. // Sometimes, we call the socket functions and close the socket right after,
  425. // and in some rare cases, it throws EXCEPTION_INVALID_HANDLE SEH exception
  426. // rather than returning an error code. Although this is undocumented on MSDN,
  427. // it causes a crash just because it thinks we gave it an invalid handle.
  428. // We guard against it by wrapping every socket call with __try/__except
  429. if (code == EXCEPTION_INVALID_HANDLE)
  430. return EXCEPTION_CONTINUE_EXECUTION;
  431. return EXCEPTION_CONTINUE_SEARCH;
  432. }
  433. WaitStatus SocketImpl::Create(AddressFamily family, SocketType type, ProtocolType protocol)
  434. {
  435. _fd = -1;
  436. _is_valid = false;
  437. _still_readable = 1;
  438. _domain = convert_address_family(family);
  439. _type = convert_socket_type(type);
  440. _protocol = convert_socket_protocol(protocol);
  441. IL2CPP_ASSERT(_type != -1 && "Unsupported socket type");
  442. IL2CPP_ASSERT(_domain != -1 && "Unsupported address family");
  443. IL2CPP_ASSERT(_protocol != -1 && "Unsupported protocol type");
  444. _fd = socket(_domain, _type, _protocol);
  445. if (_fd == -1 && _domain == AF_INET && _type == SOCK_RAW && _protocol == 0)
  446. {
  447. // Retry with protocol == 4 (see bug #54565)
  448. _protocol = 4;
  449. _fd = socket(AF_INET, SOCK_RAW, 4);
  450. }
  451. if (_fd == -1)
  452. {
  453. StoreLastError();
  454. return kWaitStatusFailure;
  455. }
  456. _is_valid = true;
  457. return kWaitStatusSuccess;
  458. }
  459. WaitStatus SocketImpl::Create(SocketDescriptor fd, int32_t family, int32_t type, int32_t protocol)
  460. {
  461. _fd = fd;
  462. _is_valid = (fd != -1);
  463. _still_readable = 1;
  464. _domain = family;
  465. _type = type;
  466. _protocol = protocol;
  467. IL2CPP_ASSERT(_type != -1 && "Unsupported socket type");
  468. IL2CPP_ASSERT(_domain != -1 && "Unsupported address family");
  469. IL2CPP_ASSERT(_protocol != -1 && "Unsupported protocol type");
  470. return kWaitStatusSuccess;
  471. }
  472. WaitStatus SocketImpl::Close()
  473. {
  474. _saved_error = kErrorCodeSuccess;
  475. SOCKET fd = (SOCKET)_fd;
  476. if (_is_valid && fd != -1)
  477. {
  478. if (closesocket(fd) == -1)
  479. StoreLastError();
  480. }
  481. _fd = -1;
  482. _is_valid = false;
  483. _still_readable = 0;
  484. _domain = -1;
  485. _type = -1;
  486. _protocol = -1;
  487. return kWaitStatusSuccess;
  488. }
  489. WaitStatus SocketImpl::SetBlocking(bool blocking)
  490. {
  491. /*
  492. * block == TRUE/FALSE means we will block/not block.
  493. * But the ioctlsocket call takes TRUE/FALSE for non-block/block
  494. */
  495. u_long ioctl_socket_blocking = (u_long) !blocking;
  496. SOCKET fd = (SOCKET)_fd;
  497. if (fd == -1)
  498. {
  499. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  500. return kWaitStatusFailure;
  501. }
  502. int32_t ret = -1;
  503. __try
  504. {
  505. ret = ioctlsocket(fd, FIONBIO, &ioctl_socket_blocking);
  506. }
  507. __except (SocketExceptionFilter(GetExceptionCode()))
  508. {
  509. }
  510. if (ret == SOCKET_ERROR)
  511. {
  512. StoreLastError();
  513. return kWaitStatusFailure;
  514. }
  515. return kWaitStatusSuccess;
  516. }
  517. ErrorCode SocketImpl::GetLastError() const
  518. {
  519. return _saved_error;
  520. }
  521. void SocketImpl::StoreLastError()
  522. {
  523. const ErrorCode error = (ErrorCode)WSAGetLastError();
  524. Error::SetLastError(error);
  525. _saved_error = error;
  526. }
  527. void SocketImpl::StoreLastError(int32_t error_no)
  528. {
  529. const ErrorCode error = (ErrorCode)error_no;
  530. Error::SetLastError(error);
  531. _saved_error = error;
  532. }
  533. static void sockaddr_from_address(uint32_t address, uint16_t port, struct sockaddr *sa, socklen_t *sa_size)
  534. {
  535. struct sockaddr_in sa_in = {0};
  536. sa_in.sin_family = AF_INET;
  537. sa_in.sin_port = port;
  538. sa_in.sin_addr.s_addr = address;
  539. *sa_size = sizeof(struct sockaddr_in);
  540. *sa = *((struct sockaddr*)&sa_in);
  541. }
  542. #if IL2CPP_SUPPORT_IPV6
  543. static void sockaddr_from_address(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port, sockaddr_in6* sa, socklen_t *sa_size)
  544. {
  545. sa->sin6_family = AF_INET6;
  546. sa->sin6_port = port;
  547. memcpy(&sa->sin6_addr, &address[0], 16);
  548. sa->sin6_scope_id = scope;
  549. *sa_size = sizeof(struct sockaddr_in6);
  550. }
  551. #endif
  552. static AddressFamily convert_define_to_address_family(int32_t family)
  553. {
  554. switch (family)
  555. {
  556. case AF_UNSPEC:
  557. return kAddressFamilyUnspecified;
  558. case AF_UNIX:
  559. return kAddressFamilyUnix;
  560. case AF_INET:
  561. return kAddressFamilyInterNetwork;
  562. #ifdef AF_IPX
  563. case AF_IPX:
  564. return kAddressFamilyIpx;
  565. #endif
  566. #ifdef AF_SNA
  567. case AF_SNA:
  568. return kAddressFamilySna;
  569. #endif
  570. #ifdef AF_DECnet
  571. case AF_DECnet:
  572. return kAddressFamilyDecNet;
  573. #endif
  574. #ifdef AF_APPLETALK
  575. case AF_APPLETALK:
  576. return kAddressFamilyAppleTalk;
  577. #endif
  578. #ifdef AF_INET6
  579. case AF_INET6:
  580. return kAddressFamilyInterNetworkV6;
  581. #endif
  582. #ifdef AF_IRDA
  583. case AF_IRDA:
  584. return kAddressFamilyIrda;
  585. #endif
  586. default:
  587. break;
  588. }
  589. return kAddressFamilyError;
  590. }
  591. static bool socketaddr_to_endpoint_info(const struct sockaddr *address, socklen_t address_len, EndPointInfo &info)
  592. {
  593. info.family = convert_define_to_address_family(address->sa_family);
  594. if (info.family == os::kAddressFamilyInterNetwork)
  595. {
  596. const struct sockaddr_in *address_in = (const struct sockaddr_in *)address;
  597. info.data.inet.port = ntohs(address_in->sin_port);
  598. info.data.inet.address = ntohl(address_in->sin_addr.s_addr);
  599. return true;
  600. }
  601. // NOTE(gab): kAddressFamilyUnix not supported on Windows
  602. //if (info.family == os::kAddressFamilyUnix)
  603. //{
  604. // for (int32_t i = 0; i < address_len; i++)
  605. // info.data.path[i] = address->sa_data[i];
  606. // return true;
  607. //}
  608. #if IL2CPP_SUPPORT_IPV6
  609. if (info.family == os::kAddressFamilyInterNetworkV6)
  610. {
  611. const struct sockaddr_in6 *address_in = (const struct sockaddr_in6 *)address;
  612. uint16_t port = ntohs(address_in->sin6_port);
  613. info.data.raw[2] = (port >> 8) & 0xff;
  614. info.data.raw[3] = port & 0xff;
  615. for (int i = 0; i < 16; i++)
  616. info.data.raw[i + 8] = address_in->sin6_addr.s6_addr[i];
  617. info.data.raw[24] = address_in->sin6_scope_id & 0xff;
  618. info.data.raw[25] = (address_in->sin6_scope_id >> 8) & 0xff;
  619. info.data.raw[26] = (address_in->sin6_scope_id >> 16) & 0xff;
  620. info.data.raw[27] = (address_in->sin6_scope_id >> 24) & 0xff;
  621. return true;
  622. }
  623. #endif
  624. return false;
  625. }
  626. WaitStatus SocketImpl::Bind(const char *path)
  627. {
  628. // NOTE(gab): not supported on Windows.
  629. return kWaitStatusFailure;
  630. }
  631. WaitStatus SocketImpl::Bind(const char *address, uint16_t port)
  632. {
  633. struct sockaddr sa = {0};
  634. socklen_t sa_size = 0;
  635. sockaddr_from_address(inet_addr(address), htons(port), &sa, &sa_size);
  636. SOCKET fd = (SOCKET)_fd;
  637. if (fd == -1)
  638. {
  639. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  640. return kWaitStatusFailure;
  641. }
  642. int bindResult = -1;
  643. __try
  644. {
  645. bindResult = bind(fd, &sa, sa_size);
  646. }
  647. __except (SocketExceptionFilter(GetExceptionCode()))
  648. {
  649. }
  650. if (bindResult == -1)
  651. {
  652. StoreLastError();
  653. return kWaitStatusFailure;
  654. }
  655. return kWaitStatusSuccess;
  656. }
  657. WaitStatus SocketImpl::Bind(uint32_t address, uint16_t port)
  658. {
  659. struct sockaddr sa = {0};
  660. socklen_t sa_size = 0;
  661. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  662. SOCKET fd = (SOCKET)_fd;
  663. if (fd == -1)
  664. {
  665. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  666. return kWaitStatusFailure;
  667. }
  668. int bindResult = -1;
  669. __try
  670. {
  671. bindResult = bind(fd, &sa, sa_size);
  672. }
  673. __except (SocketExceptionFilter(GetExceptionCode()))
  674. {
  675. }
  676. if (bindResult == -1)
  677. {
  678. StoreLastError();
  679. return kWaitStatusFailure;
  680. }
  681. return kWaitStatusSuccess;
  682. }
  683. WaitStatus SocketImpl::Bind(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port)
  684. {
  685. struct sockaddr_in6 sa = { 0 };
  686. socklen_t sa_size = 0;
  687. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  688. if (bind((SOCKET)_fd, (sockaddr*)&sa, sa_size) == -1)
  689. {
  690. StoreLastError();
  691. return kWaitStatusFailure;
  692. }
  693. return kWaitStatusSuccess;
  694. }
  695. WaitStatus SocketImpl::ConnectInternal(struct sockaddr *sa, int32_t sa_size)
  696. {
  697. SOCKET fd = (SOCKET)_fd;
  698. if (fd == -1)
  699. {
  700. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  701. return kWaitStatusFailure;
  702. }
  703. __try
  704. {
  705. if (connect(fd, sa, (socklen_t)sa_size) != -1)
  706. return kWaitStatusSuccess;
  707. if (errno != EINTR)
  708. {
  709. StoreLastError();
  710. return kWaitStatusFailure;
  711. }
  712. struct pollfd fds = { 0 };
  713. fds.fd = fd;
  714. fds.events = POLLOUT;
  715. while (WSAPoll(&fds, 1, -1) == -1)
  716. {
  717. if (errno != EINTR)
  718. {
  719. StoreLastError();
  720. return kWaitStatusFailure;
  721. }
  722. }
  723. int32_t so_error = 0;
  724. socklen_t len = sizeof(so_error);
  725. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&so_error, &len) == -1)
  726. {
  727. StoreLastError();
  728. return kWaitStatusFailure;
  729. }
  730. if (so_error != 0)
  731. {
  732. StoreLastError(so_error);
  733. return kWaitStatusFailure;
  734. }
  735. }
  736. __except (SocketExceptionFilter(GetExceptionCode()))
  737. {
  738. SetLastError(kWSAeshutdown);
  739. return kWaitStatusFailure;
  740. }
  741. return kWaitStatusSuccess;
  742. }
  743. WaitStatus SocketImpl::Connect(const char *path)
  744. {
  745. // NOTE(gab): not supported on Windows.
  746. return kWaitStatusFailure;
  747. }
  748. WaitStatus SocketImpl::Connect(uint32_t address, uint16_t port)
  749. {
  750. struct sockaddr sa = {0};
  751. socklen_t sa_size = 0;
  752. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  753. return ConnectInternal((struct sockaddr *)&sa, sa_size);
  754. }
  755. WaitStatus SocketImpl::Connect(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port)
  756. {
  757. struct sockaddr_in6 sa = { 0 };
  758. socklen_t sa_size = 0;
  759. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  760. return ConnectInternal((struct sockaddr *)&sa, sa_size);
  761. }
  762. WaitStatus SocketImpl::GetLocalEndPointInfo(EndPointInfo &info)
  763. {
  764. // Note: the size here could probably be smaller
  765. uint8_t buffer[END_POINT_MAX_PATH_LEN + 3] = {0};
  766. socklen_t address_len = sizeof(buffer);
  767. SOCKET fd = (SOCKET)_fd;
  768. if (fd == -1)
  769. {
  770. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  771. return kWaitStatusFailure;
  772. }
  773. int getsocknameResult = -1;
  774. __try
  775. {
  776. getsocknameResult = getsockname(fd, (struct sockaddr *)buffer, &address_len);
  777. }
  778. __except (SocketExceptionFilter(GetExceptionCode()))
  779. {
  780. SetLastError(kWSAeshutdown);
  781. return kWaitStatusFailure;
  782. }
  783. if (getsocknameResult == -1)
  784. {
  785. StoreLastError();
  786. return kWaitStatusFailure;
  787. }
  788. if (!socketaddr_to_endpoint_info((struct sockaddr *)buffer, address_len, info))
  789. {
  790. _saved_error = kWSAeafnosupport;
  791. return kWaitStatusFailure;
  792. }
  793. return kWaitStatusSuccess;
  794. }
  795. WaitStatus SocketImpl::GetRemoteEndPointInfo(EndPointInfo &info)
  796. {
  797. // Note: the size here could probably be smaller
  798. uint8_t buffer[END_POINT_MAX_PATH_LEN + 3] = {0};
  799. socklen_t address_len = sizeof(buffer);
  800. SOCKET fd = (SOCKET)_fd;
  801. if (fd == -1)
  802. {
  803. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  804. return kWaitStatusFailure;
  805. }
  806. int getpeernameResult = -1;
  807. __try
  808. {
  809. getpeernameResult = getpeername(fd, (struct sockaddr *)buffer, &address_len);
  810. }
  811. __except (SocketExceptionFilter(GetExceptionCode()))
  812. {
  813. }
  814. if (getpeernameResult == -1)
  815. {
  816. StoreLastError();
  817. return kWaitStatusFailure;
  818. }
  819. if (!socketaddr_to_endpoint_info((struct sockaddr *)buffer, address_len, info))
  820. {
  821. _saved_error = kWSAeafnosupport;
  822. return kWaitStatusFailure;
  823. }
  824. return kWaitStatusSuccess;
  825. }
  826. WaitStatus SocketImpl::Listen(int32_t backlog)
  827. {
  828. SOCKET fd = (SOCKET)_fd;
  829. if (fd == -1)
  830. {
  831. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  832. return kWaitStatusFailure;
  833. }
  834. int listenResult = -1;
  835. __try
  836. {
  837. listenResult = listen(fd, backlog);
  838. }
  839. __except (SocketExceptionFilter(GetExceptionCode()))
  840. {
  841. }
  842. if (listenResult == -1)
  843. {
  844. StoreLastError();
  845. return kWaitStatusFailure;
  846. }
  847. return kWaitStatusSuccess;
  848. }
  849. WaitStatus SocketImpl::Shutdown(int32_t how)
  850. {
  851. SOCKET fd = (SOCKET)_fd;
  852. if (fd == -1)
  853. {
  854. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  855. return kWaitStatusFailure;
  856. }
  857. int shutdownResult = -1;
  858. __try
  859. {
  860. shutdownResult = shutdown(fd, how);
  861. }
  862. __except (SocketExceptionFilter(GetExceptionCode()))
  863. {
  864. }
  865. if (shutdownResult == -1)
  866. {
  867. StoreLastError();
  868. return kWaitStatusFailure;
  869. }
  870. if (how == SD_RECEIVE || how == SD_BOTH)
  871. _still_readable = 0;
  872. return kWaitStatusSuccess;
  873. }
  874. static SOCKET AcceptProtected(SOCKET fd)
  875. {
  876. SOCKET new_fd;
  877. do
  878. {
  879. __try
  880. {
  881. new_fd = accept(fd, NULL, 0);
  882. }
  883. __except (SocketExceptionFilter(GetExceptionCode()))
  884. {
  885. new_fd = -1;
  886. break;
  887. }
  888. }
  889. while (new_fd == -1 && errno == EINTR);
  890. return new_fd;
  891. }
  892. WaitStatus SocketImpl::Accept(os::Socket **socket)
  893. {
  894. SocketDescriptor new_fd = 0;
  895. *socket = NULL;
  896. SOCKET fd = (SOCKET)_fd;
  897. if (fd == -1)
  898. {
  899. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  900. return kWaitStatusFailure;
  901. }
  902. new_fd = AcceptProtected(fd);
  903. if (new_fd == -1)
  904. {
  905. StoreLastError();
  906. return kWaitStatusFailure;
  907. }
  908. *socket = new os::Socket(_thread_status_callback);
  909. const WaitStatus status = (*socket)->Create(new_fd, _domain, _type, _protocol);
  910. if (status != kWaitStatusSuccess)
  911. {
  912. delete *socket;
  913. *socket = NULL;
  914. return status;
  915. }
  916. return kWaitStatusSuccess;
  917. }
  918. WaitStatus SocketImpl::Disconnect(bool reuse)
  919. {
  920. GUID GuidDisconnectEx = WSAID_DISCONNECTEX;
  921. LPFN_DISCONNECTEX disconnectEx;
  922. DWORD copied;
  923. SOCKET fd = (SOCKET)_fd;
  924. if (fd == -1)
  925. {
  926. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  927. return kWaitStatusFailure;
  928. }
  929. __try
  930. {
  931. int32_t ret = WSAIoctl(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidDisconnectEx, sizeof(GuidDisconnectEx), &disconnectEx, sizeof(disconnectEx), &copied, 0, 0);
  932. if (ret == SOCKET_ERROR)
  933. {
  934. StoreLastError();
  935. return kWaitStatusFailure;
  936. }
  937. if (!disconnectEx(fd, NULL, 0, NULL))
  938. {
  939. StoreLastError();
  940. return kWaitStatusFailure;
  941. }
  942. }
  943. __except (SocketExceptionFilter(GetExceptionCode()))
  944. {
  945. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  946. return kWaitStatusFailure;
  947. }
  948. return kWaitStatusSuccess;
  949. }
  950. WaitStatus SocketImpl::Receive(const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  951. {
  952. *len = 0;
  953. const int32_t c_flags = convert_socket_flags(flags);
  954. if (c_flags == -1)
  955. {
  956. _saved_error = kWSAeopnotsupp;
  957. return kWaitStatusFailure;
  958. }
  959. return ReceiveFromInternal(data, count, c_flags, len, NULL, 0);
  960. }
  961. WaitStatus SocketImpl::ReceiveFromInternal(const uint8_t *data, size_t count, int32_t flags, int32_t *len, struct sockaddr *from, int32_t *fromlen)
  962. {
  963. int32_t ret = 0;
  964. IL2CPP_ASSERT(count < static_cast<size_t>(std::numeric_limits<int>::max()));
  965. SOCKET fd = (SOCKET)_fd;
  966. if (fd == -1)
  967. {
  968. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  969. return kWaitStatusFailure;
  970. }
  971. do
  972. {
  973. __try
  974. {
  975. ret = recvfrom(fd, (char*)data, static_cast<int>(count), flags, from, (socklen_t*)fromlen);
  976. }
  977. __except (SocketExceptionFilter(GetExceptionCode()))
  978. {
  979. ret = -1;
  980. break;
  981. }
  982. }
  983. while (ret == -1 && errno == EINTR);
  984. if (ret == 0 && count > 0)
  985. {
  986. // According to the Linux man page, recvfrom only
  987. // returns 0 when the socket has been shut down
  988. // cleanly. Turn this into an EINTR to simulate win32
  989. // behaviour of returning EINTR when a socket is
  990. // closed while the recvfrom is blocking (we use a
  991. // shutdown() in socket_close() to trigger this.) See
  992. // bug 75705.
  993. // Distinguish between the socket being shut down at
  994. // the local or remote ends, and reads that request 0
  995. // bytes to be read
  996. // If this returns FALSE, it means the socket has been
  997. // closed locally. If it returns TRUE, but
  998. // still_readable != 1 then shutdown
  999. // (SHUT_RD|SHUT_RDWR) has been called locally.
  1000. if (_still_readable != 1)
  1001. {
  1002. ret = -1;
  1003. errno = EINTR;
  1004. }
  1005. }
  1006. if (ret == -1)
  1007. {
  1008. StoreLastError();
  1009. return kWaitStatusFailure;
  1010. }
  1011. *len = ret;
  1012. return kWaitStatusSuccess;
  1013. }
  1014. WaitStatus SocketImpl::Send(const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1015. {
  1016. *len = 0;
  1017. const int32_t c_flags = convert_socket_flags(flags);
  1018. if (c_flags == -1)
  1019. {
  1020. _saved_error = kWSAeopnotsupp;
  1021. return kWaitStatusFailure;
  1022. }
  1023. SOCKET fd = (SOCKET)_fd;
  1024. if (fd == -1)
  1025. {
  1026. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1027. return kWaitStatusFailure;
  1028. }
  1029. int32_t ret = 0;
  1030. do
  1031. {
  1032. __try
  1033. {
  1034. ret = send(fd, (char*)data, count, flags);
  1035. }
  1036. __except (SocketExceptionFilter(GetExceptionCode()))
  1037. {
  1038. ret = -1;
  1039. break;
  1040. }
  1041. }
  1042. while (ret == -1 && errno == EINTR);
  1043. if (ret == -1)
  1044. {
  1045. StoreLastError();
  1046. return kWaitStatusFailure;
  1047. }
  1048. *len = ret;
  1049. return kWaitStatusSuccess;
  1050. }
  1051. WaitStatus SocketImpl::SendArray(WSABuf *wsabufs, int32_t count, int32_t *sent, SocketFlags flags)
  1052. {
  1053. DWORD c_flags = convert_socket_flags(flags);
  1054. if (c_flags == -1)
  1055. {
  1056. _saved_error = kWSAeopnotsupp;
  1057. return kWaitStatusFailure;
  1058. }
  1059. SOCKET fd = (SOCKET)_fd;
  1060. if (fd == -1)
  1061. {
  1062. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1063. return kWaitStatusFailure;
  1064. }
  1065. DWORD bytes_sent;
  1066. int32_t ret = -1;
  1067. __try
  1068. {
  1069. ret = WSASend(fd, (WSABUF*)wsabufs, count, &bytes_sent, c_flags, NULL, NULL);
  1070. }
  1071. __except (SocketExceptionFilter(GetExceptionCode()))
  1072. {
  1073. }
  1074. if (ret == SOCKET_ERROR)
  1075. {
  1076. *sent = 0;
  1077. StoreLastError();
  1078. return kWaitStatusFailure;
  1079. }
  1080. *sent = bytes_sent;
  1081. return kWaitStatusSuccess;
  1082. }
  1083. WaitStatus SocketImpl::ReceiveArray(WSABuf *wsabufs, int32_t count, int32_t *len, SocketFlags flags)
  1084. {
  1085. DWORD recv;
  1086. DWORD c_flags = convert_socket_flags(flags);
  1087. if (c_flags == -1)
  1088. {
  1089. _saved_error = kWSAeopnotsupp;
  1090. return kWaitStatusFailure;
  1091. }
  1092. SOCKET fd = (SOCKET)_fd;
  1093. if (fd == -1)
  1094. {
  1095. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1096. return kWaitStatusFailure;
  1097. }
  1098. int32_t ret = -1;
  1099. __try
  1100. {
  1101. // NOTE(gab): this cast is possible as long as WSABuf is binary compatible with WSABUF
  1102. ret = WSARecv(fd, (WSABUF*)wsabufs, count, &recv, &c_flags, NULL, NULL);
  1103. }
  1104. __except (SocketExceptionFilter(GetExceptionCode()))
  1105. {
  1106. }
  1107. if (ret == SOCKET_ERROR)
  1108. {
  1109. *len = 0;
  1110. StoreLastError();
  1111. return kWaitStatusFailure;
  1112. }
  1113. *len = recv;
  1114. return kWaitStatusSuccess;
  1115. }
  1116. WaitStatus SocketImpl::SendToInternal(struct sockaddr *sa, int32_t sa_size, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1117. {
  1118. const int32_t c_flags = convert_socket_flags(flags);
  1119. if (c_flags == -1)
  1120. {
  1121. _saved_error = kWSAeopnotsupp;
  1122. return kWaitStatusFailure;
  1123. }
  1124. SOCKET fd = (SOCKET)_fd;
  1125. if (fd == -1)
  1126. {
  1127. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1128. return kWaitStatusFailure;
  1129. }
  1130. int32_t ret = 0;
  1131. do
  1132. {
  1133. __try
  1134. {
  1135. ret = sendto(fd, (char*)data, count, c_flags, sa, sa_size);
  1136. }
  1137. __except (SocketExceptionFilter(GetExceptionCode()))
  1138. {
  1139. ret = -1;
  1140. break;
  1141. }
  1142. }
  1143. while (ret == -1 && errno == EINTR);
  1144. if (ret == -1)
  1145. {
  1146. StoreLastError();
  1147. return kWaitStatusFailure;
  1148. }
  1149. *len = ret;
  1150. return kWaitStatusSuccess;
  1151. }
  1152. WaitStatus SocketImpl::SendTo(uint32_t address, uint16_t port, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1153. {
  1154. *len = 0;
  1155. struct sockaddr sa = {0};
  1156. socklen_t sa_size = 0;
  1157. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  1158. return SendToInternal(&sa, sa_size, data, count, flags, len);
  1159. }
  1160. utils::Expected<WaitStatus> SocketImpl::SendTo(const char *path, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1161. {
  1162. return utils::Il2CppError(utils::NotSupported, "Unix sockets are not supported on this platform.");
  1163. }
  1164. WaitStatus SocketImpl::SendTo(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1165. {
  1166. *len = 0;
  1167. struct sockaddr_in6 sa = { 0 };
  1168. socklen_t sa_size = 0;
  1169. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1170. return SendToInternal((sockaddr*)&sa, sa_size, data, count, flags, len);
  1171. }
  1172. WaitStatus SocketImpl::RecvFromInternal(struct sockaddr* sa, int32_t sa_size, const uint8_t* data, int32_t count, os::SocketFlags flags, int32_t* len, os::EndPointInfo& ep)
  1173. {
  1174. const int32_t c_flags = convert_socket_flags(flags);
  1175. if (c_flags == -1)
  1176. {
  1177. _saved_error = kWSAeopnotsupp;
  1178. return kWaitStatusFailure;
  1179. }
  1180. int32_t ret = 0;
  1181. const WaitStatus status = ReceiveFromInternal(data, count, c_flags, len, sa, &sa_size);
  1182. if (status != kWaitStatusSuccess)
  1183. {
  1184. ep.family = os::kAddressFamilyError;
  1185. return status;
  1186. }
  1187. if (sa_size == 0)
  1188. return kWaitStatusSuccess;
  1189. if (!socketaddr_to_endpoint_info(sa, sa_size, ep))
  1190. {
  1191. ep.family = os::kAddressFamilyError;
  1192. _saved_error = kWSAeafnosupport;
  1193. return kWaitStatusFailure;
  1194. }
  1195. return kWaitStatusSuccess;
  1196. }
  1197. WaitStatus SocketImpl::RecvFrom(uint32_t address, uint16_t port, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len, os::EndPointInfo &ep)
  1198. {
  1199. *len = 0;
  1200. struct sockaddr sa = {0};
  1201. socklen_t sa_size = 0;
  1202. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  1203. return RecvFromInternal(&sa, sa_size, data, count, flags, len, ep);
  1204. }
  1205. utils::Expected<WaitStatus> SocketImpl::RecvFrom(const char *path, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len, os::EndPointInfo &ep)
  1206. {
  1207. return utils::Il2CppError(utils::NotSupported, "Unix sockets are not supported on this platform.");
  1208. }
  1209. WaitStatus SocketImpl::RecvFrom(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len, os::EndPointInfo &ep)
  1210. {
  1211. *len = 0;
  1212. struct sockaddr_in6 sa = { 0 };
  1213. socklen_t sa_size = 0;
  1214. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1215. return RecvFromInternal((sockaddr*)&sa, sa_size, data, count, flags, len, ep);
  1216. }
  1217. WaitStatus SocketImpl::Available(int32_t *amount)
  1218. {
  1219. *amount = 0;
  1220. u_long a = 0;
  1221. SOCKET fd = (SOCKET)_fd;
  1222. if (fd == -1)
  1223. {
  1224. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1225. return kWaitStatusFailure;
  1226. }
  1227. int ioctlsocketResult = -1;
  1228. __try
  1229. {
  1230. ioctlsocketResult = ioctlsocket(fd, FIONREAD, &a);
  1231. }
  1232. __except (SocketExceptionFilter(GetExceptionCode()))
  1233. {
  1234. }
  1235. if (ioctlsocketResult == -1)
  1236. {
  1237. StoreLastError();
  1238. return kWaitStatusFailure;
  1239. }
  1240. *amount = a;
  1241. return kWaitStatusSuccess;
  1242. }
  1243. WaitStatus SocketImpl::Ioctl(int32_t command, const uint8_t *in_data, int32_t in_len, uint8_t *out_data, int32_t out_len, int32_t *written)
  1244. {
  1245. IL2CPP_ASSERT(command != 0xC8000006 /* SIO_GET_EXTENSION_FUNCTION_POINTER */ && "SIO_GET_EXTENSION_FUNCTION_POINTER ioctl command not supported");
  1246. SOCKET fd = (SOCKET)_fd;
  1247. if (fd == -1)
  1248. {
  1249. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1250. return kWaitStatusFailure;
  1251. }
  1252. DWORD len = 0;
  1253. int32_t ret = -1;
  1254. __try
  1255. {
  1256. ret = WSAIoctl(fd, command, (void*)in_data, in_len, out_data, out_len, &len, NULL, NULL);
  1257. }
  1258. __except (SocketExceptionFilter(GetExceptionCode()))
  1259. {
  1260. }
  1261. if (ret == SOCKET_ERROR)
  1262. {
  1263. StoreLastError();
  1264. return kWaitStatusFailure;
  1265. }
  1266. *written = len;
  1267. return kWaitStatusSuccess;
  1268. }
  1269. #define SKIP_OPTION -2
  1270. #define INVALID_OPTION_NAME -1
  1271. static int32_t level_and_name_to_system(SocketOptionLevel level, SocketOptionName name, int32_t *system_level, int32_t *system_name)
  1272. {
  1273. switch (level)
  1274. {
  1275. case kSocketOptionLevelSocket:
  1276. *system_level = SOL_SOCKET;
  1277. switch (name)
  1278. {
  1279. // This is SO_LINGER, because the setsockopt
  1280. // internal call maps DontLinger to SO_LINGER
  1281. // with l_onoff=0
  1282. case kSocketOptionNameDontLinger:
  1283. *system_name = SO_LINGER;
  1284. break;
  1285. case kSocketOptionNameDebug:
  1286. *system_name = SO_DEBUG;
  1287. break;
  1288. // #ifdef SO_ACCEPTCONN
  1289. case kSocketOptionNameAcceptConnection:
  1290. *system_name = SO_ACCEPTCONN;
  1291. break;
  1292. // #endif
  1293. case kSocketOptionNameReuseAddress:
  1294. *system_name = SO_REUSEADDR;
  1295. break;
  1296. case kSocketOptionNameKeepAlive:
  1297. *system_name = SO_KEEPALIVE;
  1298. break;
  1299. case kSocketOptionNameDontRoute:
  1300. *system_name = SO_DONTROUTE;
  1301. break;
  1302. case kSocketOptionNameBroadcast:
  1303. *system_name = SO_BROADCAST;
  1304. break;
  1305. case kSocketOptionNameLinger:
  1306. *system_name = SO_LINGER;
  1307. break;
  1308. case kSocketOptionNameOutOfBandInline:
  1309. *system_name = SO_OOBINLINE;
  1310. break;
  1311. case kSocketOptionNameSendBuffer:
  1312. *system_name = SO_SNDBUF;
  1313. break;
  1314. case kSocketOptionNameReceiveBuffer:
  1315. *system_name = SO_RCVBUF;
  1316. break;
  1317. case kSocketOptionNameSendLowWater:
  1318. *system_name = SO_SNDLOWAT;
  1319. break;
  1320. case kSocketOptionNameReceiveLowWater:
  1321. *system_name = SO_RCVLOWAT;
  1322. break;
  1323. case kSocketOptionNameSendTimeout:
  1324. *system_name = SO_SNDTIMEO;
  1325. break;
  1326. case kSocketOptionNameReceiveTimeout:
  1327. *system_name = SO_RCVTIMEO;
  1328. break;
  1329. case kSocketOptionNameError:
  1330. *system_name = SO_ERROR;
  1331. break;
  1332. case kSocketOptionNameType:
  1333. *system_name = SO_TYPE;
  1334. break;
  1335. case kSocketOptionNameExclusiveAddressUse:
  1336. #ifdef SO_EXCLUSIVEADDRUSE
  1337. *system_name = SO_EXCLUSIVEADDRUSE;
  1338. break;
  1339. #elif SO_REUSEADDR
  1340. *system_name = SO_REUSEADDR;
  1341. break;
  1342. #endif
  1343. case kSocketOptionNameUseLoopback:
  1344. #ifdef SO_USELOOPBACK
  1345. *system_name = SO_USELOOPBACK;
  1346. break;
  1347. #endif
  1348. case kSocketOptionNameMaxConnections:
  1349. #ifdef SO_MAXCONN
  1350. *system_name = SO_MAXCONN;
  1351. break;
  1352. #elif defined(SOMAXCONN)
  1353. *system_name = SOMAXCONN;
  1354. break;
  1355. #endif
  1356. default:
  1357. return INVALID_OPTION_NAME;
  1358. }
  1359. break;
  1360. case kSocketOptionLevelIP:
  1361. *system_level = IPPROTO_IP;
  1362. switch (name)
  1363. {
  1364. case kSocketOptionNameIPOptions:
  1365. *system_name = IP_OPTIONS;
  1366. break;
  1367. #ifdef IP_HDRINCL
  1368. case kSocketOptionNameHeaderIncluded:
  1369. *system_name = IP_HDRINCL;
  1370. break;
  1371. #endif
  1372. #ifdef IP_TOS
  1373. case kSocketOptionNameTypeOfService:
  1374. *system_name = IP_TOS;
  1375. break;
  1376. #endif
  1377. #ifdef IP_TTL
  1378. case kSocketOptionNameIpTimeToLive:
  1379. *system_name = IP_TTL;
  1380. break;
  1381. #endif
  1382. case kSocketOptionNameMulticastInterface:
  1383. *system_name = IP_MULTICAST_IF;
  1384. break;
  1385. case kSocketOptionNameMulticastTimeToLive:
  1386. *system_name = IP_MULTICAST_TTL;
  1387. break;
  1388. case kSocketOptionNameMulticastLoopback:
  1389. *system_name = IP_MULTICAST_LOOP;
  1390. break;
  1391. case kSocketOptionNameAddMembership:
  1392. *system_name = IP_ADD_MEMBERSHIP;
  1393. break;
  1394. case kSocketOptionNameDropMembership:
  1395. *system_name = IP_DROP_MEMBERSHIP;
  1396. break;
  1397. #ifdef HAVE_IP_PKTINFO
  1398. case kSocketOptionNamePacketInformation:
  1399. *system_name = IP_PKTINFO;
  1400. break;
  1401. #endif
  1402. case kSocketOptionNameDontFragment:
  1403. #ifdef IP_DONTFRAGMENT
  1404. *system_name = IP_DONTFRAGMENT;
  1405. #elif IP_MTU_DISCOVER
  1406. *system_name = IP_MTU_DISCOVER;
  1407. #elif IP_DONTFRAG
  1408. *system_name = IP_DONTFRAG;
  1409. #else
  1410. return SKIP_OPTION;
  1411. #endif
  1412. break;
  1413. case kSocketOptionNameAddSourceMembership:
  1414. case kSocketOptionNameDropSourceMembership:
  1415. case kSocketOptionNameBlockSource:
  1416. case kSocketOptionNameUnblockSource:
  1417. // Can't figure out how to map these, so fall
  1418. // through
  1419. default:
  1420. return INVALID_OPTION_NAME;
  1421. }
  1422. break;
  1423. #if IL2CPP_SUPPORT_IPV6
  1424. case kSocketOptionLevelIPv6:
  1425. *system_level = IPPROTO_IPV6;
  1426. switch (name)
  1427. {
  1428. case kSocketOptionNameMulticastInterface:
  1429. *system_name = IPV6_MULTICAST_IF;
  1430. break;
  1431. case kSocketOptionNameMulticastTimeToLive:
  1432. *system_name = IPV6_MULTICAST_HOPS;
  1433. break;
  1434. case kSocketOptionNameMulticastLoopback:
  1435. *system_name = IPV6_MULTICAST_LOOP;
  1436. break;
  1437. case kSocketOptionNameAddMembership:
  1438. *system_name = IPV6_JOIN_GROUP;
  1439. break;
  1440. case kSocketOptionNameDropMembership:
  1441. *system_name = IPV6_LEAVE_GROUP;
  1442. break;
  1443. case kSocketOptionNamePacketInformation:
  1444. #ifdef HAVE_IPV6_PKTINFO
  1445. *system_name = IPV6_PKTINFO;
  1446. break;
  1447. #endif
  1448. case kSocketOptionNameIPv6Only:
  1449. #ifdef IPV6_V6ONLY
  1450. *system_name = IPV6_V6ONLY;
  1451. break;
  1452. #endif
  1453. case kSocketOptionNameHeaderIncluded:
  1454. case kSocketOptionNameIPOptions:
  1455. case kSocketOptionNameTypeOfService:
  1456. case kSocketOptionNameDontFragment:
  1457. case kSocketOptionNameAddSourceMembership:
  1458. case kSocketOptionNameDropSourceMembership:
  1459. case kSocketOptionNameBlockSource:
  1460. case kSocketOptionNameUnblockSource:
  1461. // Can't figure out how to map these, so fall
  1462. // through
  1463. default:
  1464. return INVALID_OPTION_NAME;
  1465. }
  1466. break;
  1467. #endif // IL2CPP_SUPPORT_IPV6
  1468. case kSocketOptionLevelTcp:
  1469. #ifdef SOL_TCP
  1470. *system_level = SOL_TCP;
  1471. #else
  1472. *system_level = IPPROTO_TCP;
  1473. #endif
  1474. switch (name)
  1475. {
  1476. case kSocketOptionNameNoDelay:
  1477. *system_name = TCP_NODELAY;
  1478. break;
  1479. default:
  1480. return INVALID_OPTION_NAME;
  1481. }
  1482. break;
  1483. case kSocketOptionLevelUdp:
  1484. default:
  1485. return INVALID_OPTION_NAME;
  1486. }
  1487. return 0;
  1488. }
  1489. WaitStatus SocketImpl::GetSocketOption(SocketOptionLevel level, SocketOptionName name, uint8_t *buffer, int32_t *length)
  1490. {
  1491. int32_t system_level = 0;
  1492. int32_t system_name = 0;
  1493. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1494. if (o_res == SKIP_OPTION)
  1495. {
  1496. *((int32_t*)buffer) = 0;
  1497. *length = sizeof(int32_t);
  1498. return kWaitStatusSuccess;
  1499. }
  1500. if (o_res == INVALID_OPTION_NAME)
  1501. {
  1502. _saved_error = kWSAenoprotoopt;
  1503. return kWaitStatusFailure;
  1504. }
  1505. SOCKET fd = (SOCKET)_fd;
  1506. if (fd == -1)
  1507. {
  1508. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1509. return kWaitStatusFailure;
  1510. }
  1511. uint8_t *tmp_val = buffer;
  1512. int32_t ret = -1;
  1513. __try
  1514. {
  1515. ret = getsockopt(fd, system_level, system_name, (char*)tmp_val, (socklen_t*)length);
  1516. }
  1517. __except (SocketExceptionFilter(GetExceptionCode()))
  1518. {
  1519. }
  1520. if (ret == -1)
  1521. {
  1522. StoreLastError();
  1523. return kWaitStatusFailure;
  1524. }
  1525. if (system_name == SO_ERROR)
  1526. {
  1527. if (*((int32_t*)buffer) != 0)
  1528. {
  1529. StoreLastError(*((int32_t*)buffer));
  1530. }
  1531. else
  1532. {
  1533. *((int32_t*)buffer) = _saved_error;
  1534. }
  1535. }
  1536. return kWaitStatusSuccess;
  1537. }
  1538. WaitStatus SocketImpl::GetSocketOptionFull(SocketOptionLevel level, SocketOptionName name, int32_t *first, int32_t *second)
  1539. {
  1540. int32_t system_level = 0;
  1541. int32_t system_name = 0;
  1542. #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
  1543. if (level == kSocketOptionLevelSocket && name == kSocketOptionNameExclusiveAddressUse)
  1544. {
  1545. system_level = SOL_SOCKET;
  1546. system_name = SO_REUSEADDR;
  1547. }
  1548. else
  1549. #endif
  1550. {
  1551. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1552. if (o_res == SKIP_OPTION)
  1553. {
  1554. *first = 0;
  1555. *second = 0;
  1556. return kWaitStatusSuccess;
  1557. }
  1558. if (o_res == INVALID_OPTION_NAME)
  1559. {
  1560. _saved_error = kWSAenoprotoopt;
  1561. return kWaitStatusFailure;
  1562. }
  1563. }
  1564. SOCKET fd = (SOCKET)_fd;
  1565. if (fd == -1)
  1566. {
  1567. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1568. return kWaitStatusFailure;
  1569. }
  1570. int32_t ret = -1;
  1571. switch (name)
  1572. {
  1573. case kSocketOptionNameLinger:
  1574. {
  1575. struct linger linger;
  1576. socklen_t lingersize = sizeof(linger);
  1577. __try
  1578. {
  1579. ret = getsockopt(fd, system_level, system_name, (char*)&linger, &lingersize);
  1580. *first = linger.l_onoff;
  1581. *second = linger.l_linger;
  1582. }
  1583. __except (SocketExceptionFilter(GetExceptionCode()))
  1584. {
  1585. ret = -1;
  1586. }
  1587. }
  1588. break;
  1589. case kSocketOptionNameDontLinger:
  1590. {
  1591. struct linger linger;
  1592. socklen_t lingersize = sizeof(linger);
  1593. __try
  1594. {
  1595. ret = getsockopt(fd, system_level, system_name, (char*)&linger, &lingersize);
  1596. *first = !linger.l_onoff;
  1597. }
  1598. __except (SocketExceptionFilter(GetExceptionCode()))
  1599. {
  1600. ret = -1;
  1601. }
  1602. }
  1603. break;
  1604. case kSocketOptionNameSendTimeout:
  1605. case kSocketOptionNameReceiveTimeout:
  1606. {
  1607. socklen_t time_ms_size = sizeof(*first);
  1608. __try
  1609. {
  1610. ret = getsockopt(fd, system_level, system_name, (char*)first, &time_ms_size);
  1611. }
  1612. __except (SocketExceptionFilter(GetExceptionCode()))
  1613. {
  1614. ret = -1;
  1615. }
  1616. }
  1617. break;
  1618. default:
  1619. {
  1620. socklen_t valsize = sizeof(*first);
  1621. __try
  1622. {
  1623. ret = getsockopt(fd, system_level, system_name, (char*)first, &valsize);
  1624. }
  1625. __except (SocketExceptionFilter(GetExceptionCode()))
  1626. {
  1627. ret = -1;
  1628. }
  1629. }
  1630. break;
  1631. }
  1632. if (ret == -1)
  1633. {
  1634. StoreLastError();
  1635. return kWaitStatusFailure;
  1636. }
  1637. #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
  1638. if (level == kSocketOptionLevelSocket && name == kSocketOptionNameExclusiveAddressUse)
  1639. *first = *first ? 0 : 1;
  1640. #endif
  1641. return kWaitStatusSuccess;
  1642. }
  1643. WaitStatus SocketImpl::Poll(std::vector<PollRequest> &requests, int32_t count, int32_t timeout, int32_t *result, int32_t *error)
  1644. {
  1645. const size_t nfds = (size_t)count;
  1646. fd_set rfds, wfds, efds;
  1647. FD_ZERO(&rfds);
  1648. FD_ZERO(&wfds);
  1649. FD_ZERO(&efds);
  1650. for (size_t i = 0; i < nfds; i++)
  1651. {
  1652. SOCKET fd = static_cast<SOCKET>(requests[i].fd);
  1653. requests[i].revents = kPollFlagsNone;
  1654. if (fd == -1)
  1655. continue;
  1656. if ((requests[i].events & kPollFlagsIn) != 0)
  1657. FD_SET(fd, &rfds);
  1658. if ((requests[i].events & kPollFlagsOut) != 0)
  1659. FD_SET(fd, &wfds);
  1660. FD_SET(fd, &efds);
  1661. }
  1662. timeval timevalTimeout;
  1663. timeval* timeoutPtr = NULL;
  1664. if (timeout != -1)
  1665. {
  1666. timevalTimeout.tv_sec = timeout / 1000;
  1667. timevalTimeout.tv_usec = (timeout % 1000) * 1000;
  1668. timeoutPtr = &timevalTimeout;
  1669. }
  1670. int32_t affected = -1;
  1671. __try
  1672. {
  1673. affected = select(0, &rfds, &wfds, &efds, timeoutPtr);
  1674. }
  1675. __except (SocketExceptionFilter(GetExceptionCode()))
  1676. {
  1677. }
  1678. if (affected == -1)
  1679. {
  1680. *error = WSAGetLastError();
  1681. // Mono does this as well and the threadpool-ms-io-poll code depends on this behavior
  1682. if (*error == WSAENOTSOCK)
  1683. {
  1684. *error = os::kInvalidHandle;
  1685. }
  1686. return kWaitStatusFailure;
  1687. }
  1688. int32_t resultCount = 0;
  1689. for (size_t i = 0; i < nfds && affected > 0; i++)
  1690. {
  1691. SOCKET fd = static_cast<SOCKET>(requests[i].fd);
  1692. if (fd == -1)
  1693. continue;
  1694. if ((requests[i].events & kPollFlagsIn) != 0 && FD_ISSET(fd, &rfds))
  1695. {
  1696. requests[i].revents |= kPollFlagsIn;
  1697. affected--;
  1698. }
  1699. if ((requests[i].events & kPollFlagsOut) != 0 && FD_ISSET(fd, &wfds))
  1700. {
  1701. requests[i].revents |= kPollFlagsOut;
  1702. affected--;
  1703. }
  1704. if (FD_ISSET(fd, &efds))
  1705. {
  1706. requests[i].revents |= kPollFlagsErr;
  1707. affected--;
  1708. }
  1709. if (requests[i].revents != kPollFlagsNone)
  1710. resultCount++;
  1711. }
  1712. *result = resultCount;
  1713. return kWaitStatusSuccess;
  1714. }
  1715. WaitStatus SocketImpl::Poll(std::vector<PollRequest>& requests, int32_t timeout, int32_t *result, int32_t *error)
  1716. {
  1717. return Poll(requests, (int32_t)requests.size(), timeout, result, error);
  1718. }
  1719. WaitStatus SocketImpl::Poll(PollRequest& request, int32_t timeout, int32_t *result, int32_t *error)
  1720. {
  1721. std::vector<PollRequest> requests;
  1722. requests.push_back(request);
  1723. return Poll(requests, 1, timeout, result, error);
  1724. }
  1725. WaitStatus SocketImpl::SetSocketOption(SocketOptionLevel level, SocketOptionName name, int32_t value)
  1726. {
  1727. int32_t system_level = 0;
  1728. int32_t system_name = 0;
  1729. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1730. if (o_res == SKIP_OPTION)
  1731. {
  1732. return kWaitStatusSuccess;
  1733. }
  1734. if (o_res == INVALID_OPTION_NAME)
  1735. {
  1736. _saved_error = kWSAenoprotoopt;
  1737. return kWaitStatusFailure;
  1738. }
  1739. struct linger linger;
  1740. WaitStatus ret = kWaitStatusFailure;
  1741. switch (name)
  1742. {
  1743. case kSocketOptionNameDontLinger:
  1744. linger.l_onoff = !value;
  1745. linger.l_linger = 0;
  1746. ret = SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  1747. break;
  1748. case kSocketOptionNameDontFragment:
  1749. #ifdef IP_PMTUDISC_DO
  1750. // Fiddle with the value slightly if we're turning DF on
  1751. if (value == 1)
  1752. value = IP_PMTUDISC_DO;
  1753. #endif
  1754. ret = SetSocketOptionInternal(system_level, system_name, (char*)&value, sizeof(value));
  1755. break;
  1756. default:
  1757. ret = SetSocketOptionInternal(system_level, system_name, (char*)&value, sizeof(value));
  1758. break;
  1759. }
  1760. return ret;
  1761. }
  1762. WaitStatus SocketImpl::SetSocketOptionLinger(SocketOptionLevel level, SocketOptionName name, bool enabled, int32_t seconds)
  1763. {
  1764. int32_t system_level = 0;
  1765. int32_t system_name = 0;
  1766. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1767. if (o_res == SKIP_OPTION)
  1768. {
  1769. return kWaitStatusSuccess;
  1770. }
  1771. if (o_res == INVALID_OPTION_NAME)
  1772. {
  1773. _saved_error = kWSAenoprotoopt;
  1774. return kWaitStatusFailure;
  1775. }
  1776. struct linger linger;
  1777. linger.l_onoff = enabled;
  1778. linger.l_linger = seconds;
  1779. return SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  1780. }
  1781. WaitStatus SocketImpl::SetSocketOptionArray(SocketOptionLevel level, SocketOptionName name, const uint8_t *buffer, int32_t length)
  1782. {
  1783. int32_t system_level = 0;
  1784. int32_t system_name = 0;
  1785. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1786. if (o_res == SKIP_OPTION)
  1787. {
  1788. return kWaitStatusSuccess;
  1789. }
  1790. if (o_res == INVALID_OPTION_NAME)
  1791. {
  1792. _saved_error = kWSAenoprotoopt;
  1793. return kWaitStatusFailure;
  1794. }
  1795. struct linger linger;
  1796. WaitStatus ret = kWaitStatusFailure;
  1797. switch (name)
  1798. {
  1799. case kSocketOptionNameDontLinger:
  1800. if (length == 1)
  1801. {
  1802. linger.l_linger = 0;
  1803. linger.l_onoff = (*((char*)buffer)) ? 0 : 1;
  1804. ret = SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  1805. }
  1806. else
  1807. {
  1808. _saved_error = kWSAeinval;
  1809. return kWaitStatusFailure;
  1810. }
  1811. break;
  1812. default:
  1813. ret = SetSocketOptionInternal(system_level, system_name, buffer, length);
  1814. break;
  1815. }
  1816. return ret;
  1817. }
  1818. WaitStatus SocketImpl::SetSocketOptionMembership(SocketOptionLevel level, SocketOptionName name, uint32_t group_address, uint32_t local_address)
  1819. {
  1820. int32_t system_level = 0;
  1821. int32_t system_name = 0;
  1822. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1823. if (o_res == SKIP_OPTION)
  1824. {
  1825. return kWaitStatusSuccess;
  1826. }
  1827. if (o_res == INVALID_OPTION_NAME)
  1828. {
  1829. _saved_error = kWSAenoprotoopt;
  1830. return kWaitStatusFailure;
  1831. }
  1832. IP_MREQ mreq = {{0}};
  1833. mreq.imr_multiaddr.s_addr = group_address;
  1834. mreq.imr_interface.s_addr = local_address;
  1835. return SetSocketOptionInternal(system_level, system_name, &mreq, sizeof(mreq));
  1836. return kWaitStatusFailure;
  1837. }
  1838. #if IL2CPP_SUPPORT_IPV6
  1839. WaitStatus SocketImpl::SetSocketOptionMembership(SocketOptionLevel level, SocketOptionName name, IPv6Address ipv6, uint64_t interfaceOffset)
  1840. {
  1841. int32_t system_level = 0;
  1842. int32_t system_name = 0;
  1843. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1844. if (o_res == SKIP_OPTION)
  1845. {
  1846. return kWaitStatusSuccess;
  1847. }
  1848. if (o_res == INVALID_OPTION_NAME)
  1849. {
  1850. _saved_error = kWSAenoprotoopt;
  1851. return kWaitStatusFailure;
  1852. }
  1853. struct ipv6_mreq mreq6 = { { 0 } };
  1854. struct in6_addr in6addr;
  1855. for (int i = 0; i < 16; ++i)
  1856. in6addr.s6_addr[i] = ipv6.addr[i];
  1857. mreq6.ipv6mr_multiaddr = in6addr;
  1858. mreq6.ipv6mr_interface = (ULONG)interfaceOffset;
  1859. return SetSocketOptionInternal(system_level, system_name, &mreq6, sizeof(mreq6));
  1860. }
  1861. #endif
  1862. WaitStatus SocketImpl::SetSocketOptionInternal(int32_t level, int32_t name, const void *value, int32_t len)
  1863. {
  1864. const void *real_val = value;
  1865. SOCKET fd = (SOCKET)_fd;
  1866. if (fd == -1)
  1867. {
  1868. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1869. return kWaitStatusFailure;
  1870. }
  1871. int32_t ret = -1;
  1872. __try
  1873. {
  1874. ret = setsockopt(fd, level, name, (const char*)real_val, (socklen_t)len);
  1875. }
  1876. __except (SocketExceptionFilter(GetExceptionCode()))
  1877. {
  1878. }
  1879. if (ret == -1)
  1880. {
  1881. StoreLastError();
  1882. return kWaitStatusFailure;
  1883. }
  1884. return kWaitStatusSuccess;
  1885. }
  1886. int32_t WSAIoctlProtected(SOCKET s, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
  1887. {
  1888. __try
  1889. {
  1890. return WSAIoctl(s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
  1891. }
  1892. __except (SocketExceptionFilter(GetExceptionCode()))
  1893. {
  1894. }
  1895. return -1;
  1896. }
  1897. BOOL transmitFileProtected(LPFN_TRANSMITFILE transmitFile, SOCKET hSocket, HANDLE hFile, DWORD nNumberOfBytesToWrite, DWORD nNumberOfBytesPerSend, LPOVERLAPPED lpOverlapped, LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, DWORD dwReserved)
  1898. {
  1899. __try
  1900. {
  1901. return transmitFile(hSocket, hFile, nNumberOfBytesToWrite, nNumberOfBytesPerSend, lpOverlapped, lpTransmitBuffers, dwReserved);
  1902. }
  1903. __except (SocketExceptionFilter(GetExceptionCode()))
  1904. {
  1905. }
  1906. return FALSE;
  1907. }
  1908. WaitStatus SocketImpl::SendFile(const char *filename, TransmitFileBuffers *buffers, TransmitFileOptions options)
  1909. {
  1910. if (filename == NULL)
  1911. return kWaitStatusFailure;
  1912. const UTF16String wideFilename = utils::StringUtils::Utf8ToUtf16(filename);
  1913. HANDLE file = CreateFileW((LPCWSTR)wideFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  1914. if (file == INVALID_HANDLE_VALUE)
  1915. {
  1916. StoreLastError();
  1917. return kWaitStatusFailure;
  1918. }
  1919. GUID transmitFileGuid = WSAID_TRANSMITFILE;
  1920. LPFN_TRANSMITFILE transmitFile;
  1921. DWORD copied;
  1922. SOCKET fd = (SOCKET)_fd;
  1923. if (fd == -1)
  1924. {
  1925. Error::SetLastError(il2cpp::os::kWSAeshutdown);
  1926. return kWaitStatusFailure;
  1927. }
  1928. int32_t ret = WSAIoctlProtected(fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &transmitFileGuid, sizeof(transmitFileGuid), &transmitFile, sizeof(transmitFile), &copied, 0, 0);
  1929. if (ret == SOCKET_ERROR)
  1930. {
  1931. StoreLastError();
  1932. return kWaitStatusFailure;
  1933. }
  1934. if (!transmitFileProtected(transmitFile, fd, file, 0, 0, NULL, (TRANSMIT_FILE_BUFFERS*)buffers, options))
  1935. {
  1936. StoreLastError();
  1937. CloseHandle(file);
  1938. return kWaitStatusFailure;
  1939. }
  1940. CloseHandle(file);
  1941. return kWaitStatusSuccess;
  1942. }
  1943. }
  1944. }
  1945. #endif