SocketImpl.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920
  1. #include "il2cpp-config.h"
  2. #if !IL2CPP_USE_GENERIC_SOCKET_IMPL && (IL2CPP_TARGET_POSIX || IL2CPP_SUPPORT_SOCKETS_POSIX_API) && IL2CPP_SUPPORT_SOCKETS
  3. // enable support for AF_UNIX and socket paths
  4. #define SUPPORT_UNIXSOCKETS (1)
  5. // some platforms require a different function to close sockets
  6. #define SOCK_CLOSE close
  7. // allow option include file to configure platform
  8. #if IL2CPP_USE_POSIX_SOCKET_PLATFORM_CONFIG
  9. #include "SocketImplPlatformConfig.h"
  10. #endif
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <sys/socket.h>
  14. #include <netinet/in.h>
  15. #include <netinet/tcp.h>
  16. #include <sys/ioctl.h>
  17. #include <net/if.h>
  18. #include <netdb.h>
  19. #include <arpa/inet.h>
  20. #include <errno.h>
  21. #include <fcntl.h>
  22. #if SUPPORT_UNIXSOCKETS
  23. #include <sys/un.h>
  24. #endif
  25. #include <sys/poll.h>
  26. #include <sys/stat.h>
  27. #if IL2CPP_SUPPORT_SEND_FILE && (IL2CPP_TARGET_LINUX || IL2CPP_TARGET_ANDROID)
  28. #include <sys/sendfile.h>
  29. #endif
  30. #include "os/Error.h"
  31. #include "os/Socket.h"
  32. #include "os/ErrorCodes.h"
  33. #include "os/Posix/Error.h"
  34. #include "os/Posix/PosixHelpers.h"
  35. #include "os/Posix/SocketImpl.h"
  36. #include "os/Posix/ThreadImpl.h"
  37. #include "utils/Memory.h"
  38. #include "utils/Il2CppError.h"
  39. #include "utils/StringUtils.h"
  40. namespace il2cpp
  41. {
  42. namespace os
  43. {
  44. static bool is_loopback(int32_t family, uint8_t *addr)
  45. {
  46. if (family == AF_INET)
  47. return addr[0] == 127;
  48. #if IL2CPP_SUPPORT_IPV6
  49. else if (family == AF_INET6)
  50. return (IN6_IS_ADDR_LOOPBACK((struct in6_addr *)addr));
  51. #endif
  52. return false;
  53. }
  54. static bool is_loopback(const char* address)
  55. {
  56. if (strcmp(address, "localhost") == 0)
  57. {
  58. return true;
  59. }
  60. {
  61. sockaddr_in sin = {0};
  62. if (inet_pton(AF_INET, address, &sin.sin_addr) > 0)
  63. {
  64. return is_loopback(AF_INET, (uint8_t*)&sin.sin_addr);
  65. }
  66. }
  67. #if IL2CPP_SUPPORT_IPV6
  68. {
  69. sockaddr_in6 sin = {0};
  70. if (inet_pton(AF_INET6, address, &sin.sin6_addr) > 0)
  71. {
  72. return is_loopback(AF_INET6, (uint8_t*)&sin.sin6_addr);
  73. }
  74. }
  75. #endif
  76. return false;
  77. }
  78. static bool is_limited_broadcast(const struct sockaddr *sa, socklen_t sa_size)
  79. {
  80. if (sa != NULL && sa_size >= sizeof(sockaddr_in))
  81. {
  82. const sockaddr_in *sin = (const sockaddr_in *)sa;
  83. return sin->sin_family == AF_INET && sin->sin_addr.s_addr == htonl(INADDR_BROADCAST);
  84. }
  85. return false;
  86. }
  87. bool SocketImpl::is_private(const struct sockaddr *sa, socklen_t sa_size)
  88. {
  89. if (is_limited_broadcast(sa, sa_size))
  90. {
  91. return true;
  92. }
  93. if (sa != NULL)
  94. {
  95. if (sa_size >= sizeof(const sockaddr_in) && sa->sa_family == AF_INET)
  96. {
  97. const uint8_t *addr = (uint8_t *)&(((const sockaddr_in *)sa)->sin_addr);
  98. if (addr[0] == 10) // Class A
  99. {
  100. return true;
  101. }
  102. if (addr[0] == 172 && (addr[1] & 0xf0) == 16) // Class B
  103. {
  104. return true;
  105. }
  106. if (addr[0] == 192 && addr[1] == 168) // Class C
  107. {
  108. return true;
  109. }
  110. }
  111. #if IL2CPP_SUPPORT_IPV6
  112. else if (sa_size >= sizeof(struct sockaddr_in6) && sa->sa_family == AF_INET6)
  113. {
  114. const uint8_t *addr = (uint8_t *)&(((const sockaddr_in6 *)sa)->sin6_addr);
  115. if (addr[0] == 0xf && (addr[1] & 0xe) == 0xc) // Unique local unicast address(ULA)
  116. {
  117. return true;
  118. }
  119. if (addr[0] == 0xf && addr[1] == 0xe && (addr[2] & 0xc) == 0x8) // Link local unicast address
  120. {
  121. return true;
  122. }
  123. }
  124. #endif
  125. }
  126. return false;
  127. }
  128. bool SocketImpl::is_private(const char* address)
  129. {
  130. if (address == 0 || address[0] == 0)
  131. {
  132. return false;
  133. }
  134. {
  135. sockaddr_in sin = {0};
  136. if (inet_pton(AF_INET, address, &sin.sin_addr) > 0)
  137. {
  138. sin.sin_family = AF_INET;
  139. return is_private((const sockaddr *)&sin, sizeof(sin));
  140. }
  141. }
  142. #if IL2CPP_SUPPORT_IPV6
  143. {
  144. sockaddr_in6 sin = {0};
  145. if (inet_pton(AF_INET6, address, &sin.sin6_addr) > 0)
  146. {
  147. sin.sin6_family = AF_INET6;
  148. return is_private((const sockaddr *)&sin, sizeof(sin));
  149. }
  150. }
  151. #endif
  152. return false;
  153. }
  154. #define IFCONF_BUFF_SIZE 1024
  155. #ifndef _SIZEOF_ADDR_IFREQ
  156. #define _SIZEOF_ADDR_IFREQ(ifr) (sizeof (struct ifreq))
  157. #endif
  158. #define FOREACH_IFR(IFR, IFC) \
  159. for (IFR = (IFC).ifc_req; \
  160. ifr < (struct ifreq*)((char*)(IFC).ifc_req + (IFC).ifc_len); \
  161. ifr = (struct ifreq*)((char*)(IFR) + _SIZEOF_ADDR_IFREQ (*(IFR))))
  162. static int address_size_for_family(int family)
  163. {
  164. switch (family)
  165. {
  166. case AF_INET:
  167. return sizeof(struct in_addr);
  168. #if IL2CPP_SUPPORT_IPV6
  169. case AF_INET6:
  170. return sizeof(struct in6_addr);
  171. #endif
  172. }
  173. return 0;
  174. }
  175. static void*
  176. get_address_from_sockaddr(struct sockaddr *sa)
  177. {
  178. switch (sa->sa_family)
  179. {
  180. case AF_INET:
  181. return &((struct sockaddr_in*)sa)->sin_addr;
  182. #if IL2CPP_SUPPORT_IPV6
  183. case AF_INET6:
  184. return &((struct sockaddr_in6*)sa)->sin6_addr;
  185. #endif
  186. }
  187. return NULL;
  188. }
  189. static struct in_addr *get_local_ips(int32_t family, int32_t *interface_count)
  190. {
  191. int fd;
  192. struct ifconf ifc;
  193. struct ifreq *ifr;
  194. int if_count = 0;
  195. bool ignore_loopback = false;
  196. void *result = NULL;
  197. char *result_ptr;
  198. *interface_count = 0;
  199. if (!address_size_for_family(family))
  200. return NULL;
  201. fd = socket(family, SOCK_STREAM, 0);
  202. if (fd == -1)
  203. return NULL;
  204. memset(&ifc, 0, sizeof(ifc));
  205. ifc.ifc_len = IFCONF_BUFF_SIZE;
  206. ifc.ifc_buf = (char*)malloc(IFCONF_BUFF_SIZE); /* We can't have such huge buffers on the stack. */
  207. if (ioctl(fd, SIOCGIFCONF, &ifc) < 0)
  208. goto done;
  209. FOREACH_IFR(ifr, ifc) {
  210. struct ifreq iflags;
  211. //only return addresses of the same type as @family
  212. if (ifr->ifr_addr.sa_family != family)
  213. {
  214. ifr->ifr_name[0] = '\0';
  215. continue;
  216. }
  217. strcpy(iflags.ifr_name, ifr->ifr_name);
  218. //ignore interfaces we can't get props for
  219. if (ioctl(fd, SIOCGIFFLAGS, &iflags) < 0)
  220. {
  221. ifr->ifr_name[0] = '\0';
  222. continue;
  223. }
  224. //ignore interfaces that are down
  225. if ((iflags.ifr_flags & IFF_UP) == 0)
  226. {
  227. ifr->ifr_name[0] = '\0';
  228. continue;
  229. }
  230. //If we have a non-loopback iface, don't return any loopback
  231. if ((iflags.ifr_flags & IFF_LOOPBACK) == 0)
  232. {
  233. ignore_loopback = true;
  234. ifr->ifr_name[0] = 1; //1 means non-loopback
  235. }
  236. else
  237. {
  238. ifr->ifr_name[0] = 2; //2 means loopback
  239. }
  240. ++if_count;
  241. }
  242. result = (char*)malloc(if_count * address_size_for_family(family));
  243. result_ptr = (char*)result;
  244. FOREACH_IFR(ifr, ifc) {
  245. if (ifr->ifr_name[0] == '\0')
  246. continue;
  247. if (ignore_loopback && ifr->ifr_name[0] == 2)
  248. {
  249. --if_count;
  250. continue;
  251. }
  252. memcpy(result_ptr, get_address_from_sockaddr(&ifr->ifr_addr), address_size_for_family(family));
  253. result_ptr += address_size_for_family(family);
  254. }
  255. IL2CPP_ASSERT(result_ptr <= (char*)result + if_count * address_size_for_family(family));
  256. done:
  257. *interface_count = if_count;
  258. free(ifc.ifc_buf);
  259. close(fd);
  260. return (struct in_addr*)result;
  261. }
  262. static bool hostent_get_info(struct hostent *he, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addr_list)
  263. {
  264. if (he == NULL)
  265. return false;
  266. if (he->h_length != 4 || he->h_addrtype != AF_INET)
  267. return false;
  268. name.assign(he->h_name);
  269. for (int32_t i = 0; he->h_aliases[i] != NULL; ++i)
  270. aliases.push_back(he->h_aliases[i]);
  271. for (int32_t i = 0; he->h_addr_list[i] != NULL; ++i)
  272. addr_list.push_back(
  273. utils::StringUtils::NPrintf("%u.%u.%u.%u", 16,
  274. (uint8_t)he->h_addr_list[i][0],
  275. (uint8_t)he->h_addr_list[i][1],
  276. (uint8_t)he->h_addr_list[i][2],
  277. (uint8_t)he->h_addr_list[i][3]));
  278. return true;
  279. }
  280. static bool hostent_get_info_with_local_ips(struct hostent *he, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addr_list)
  281. {
  282. int32_t nlocal_in = 0;
  283. if (he != NULL)
  284. {
  285. if (he->h_length != 4 || he->h_addrtype != AF_INET)
  286. return false;
  287. name.assign(he->h_name);
  288. for (int32_t i = 0; he->h_aliases[i] != NULL; ++i)
  289. aliases.push_back(he->h_aliases[i]);
  290. }
  291. struct in_addr *local_in = get_local_ips(AF_INET, &nlocal_in);
  292. if (nlocal_in)
  293. {
  294. for (int32_t i = 0; i < nlocal_in; ++i)
  295. {
  296. const uint8_t *ptr = (uint8_t*)&local_in[i];
  297. addr_list.push_back(
  298. utils::StringUtils::NPrintf("%u.%u.%u.%u", 16,
  299. (uint8_t)ptr[0],
  300. (uint8_t)ptr[1],
  301. (uint8_t)ptr[2],
  302. (uint8_t)ptr[3]));
  303. }
  304. free(local_in);
  305. }
  306. else if (he == NULL)
  307. {
  308. // If requesting "" and there are no other interfaces up, MS returns 127.0.0.1
  309. addr_list.push_back("127.0.0.1");
  310. return true;
  311. }
  312. if (nlocal_in == 0 && he != NULL)
  313. {
  314. for (int32_t i = 0; he->h_addr_list[i] != NULL; ++i)
  315. {
  316. addr_list.push_back(
  317. utils::StringUtils::NPrintf("%u.%u.%u.%u", 16,
  318. (uint8_t)he->h_addr_list[i][0],
  319. (uint8_t)he->h_addr_list[i][1],
  320. (uint8_t)he->h_addr_list[i][2],
  321. (uint8_t)he->h_addr_list[i][3]));
  322. }
  323. }
  324. return true;
  325. }
  326. static int32_t convert_socket_flags(os::SocketFlags flags)
  327. {
  328. int32_t c_flags = 0;
  329. if (flags)
  330. {
  331. // Check if contains invalid flag values
  332. if (flags & ~(os::kSocketFlagsOutOfBand | os::kSocketFlagsMaxIOVectorLength | os::kSocketFlagsPeek | os::kSocketFlagsDontRoute | os::kSocketFlagsPartial))
  333. {
  334. return -1;
  335. }
  336. #ifdef MSG_OOB
  337. if (flags & os::kSocketFlagsOutOfBand)
  338. c_flags |= MSG_OOB;
  339. #endif
  340. if (flags & os::kSocketFlagsPeek)
  341. c_flags |= MSG_PEEK;
  342. if (flags & os::kSocketFlagsDontRoute)
  343. c_flags |= MSG_DONTROUTE;
  344. // Ignore Partial - see bug 349688. Don't return -1, because
  345. // according to the comment in that bug ms runtime doesn't for
  346. // UDP sockets (this means we will silently ignore it for TCP
  347. // too)
  348. #ifdef MSG_MORE
  349. if (flags & os::kSocketFlagsPartial)
  350. c_flags |= MSG_MORE;
  351. #endif
  352. }
  353. return c_flags;
  354. }
  355. void SocketImpl::Startup()
  356. {
  357. }
  358. void SocketImpl::Cleanup()
  359. {
  360. }
  361. #if IL2CPP_SUPPORT_IPV6
  362. static void AddrinfoGetAddresses(struct addrinfo *info, std::string& name, bool add_local_ips,
  363. std::vector<std::string> &addr_list)
  364. {
  365. if (add_local_ips)
  366. {
  367. bool any_local_ips_added = false;
  368. int nlocal_in = 0;
  369. int nlocal_in6 = 0;
  370. in_addr* local_in = (struct in_addr *)get_local_ips(AF_INET, &nlocal_in);
  371. in6_addr* local_in6 = (struct in6_addr *)get_local_ips(AF_INET6, &nlocal_in6);
  372. if (nlocal_in || nlocal_in6)
  373. {
  374. if (nlocal_in)
  375. {
  376. for (int i = 0; i < nlocal_in; i++)
  377. {
  378. char addr[16];
  379. inet_ntop(AF_INET, &local_in[i], addr, sizeof(addr));
  380. addr_list.push_back(std::string(addr));
  381. any_local_ips_added = true;
  382. }
  383. }
  384. if (nlocal_in6)
  385. {
  386. for (int i = 0; i < nlocal_in6; i++)
  387. {
  388. char addr[48];
  389. const char* ret = inet_ntop(AF_INET6, &local_in6[i], addr, sizeof(addr));
  390. if (ret != NULL)
  391. {
  392. addr_list.push_back(std::string(addr));
  393. any_local_ips_added = true;
  394. }
  395. }
  396. }
  397. }
  398. free(local_in);
  399. free(local_in6);
  400. if (any_local_ips_added)
  401. return;
  402. }
  403. bool nameSet = false;
  404. for (addrinfo* ai = info; ai != NULL; ai = ai->ai_next)
  405. {
  406. const char *ret;
  407. char buffer[48]; /* Max. size for IPv6 */
  408. if ((ai->ai_family != PF_INET) && (ai->ai_family != PF_INET6))
  409. continue;
  410. if (ai->ai_family == PF_INET)
  411. ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in*)ai->ai_addr)->sin_addr), buffer, 16);
  412. else
  413. ret = inet_ntop(ai->ai_family, (void*)&(((struct sockaddr_in6*)ai->ai_addr)->sin6_addr), buffer, 48);
  414. if (ret)
  415. addr_list.push_back(std::string(buffer));
  416. else
  417. addr_list.push_back(std::string());
  418. if (!nameSet)
  419. {
  420. if (ai->ai_canonname != NULL)
  421. name = std::string(ai->ai_canonname);
  422. else
  423. name = std::string();
  424. nameSet = true;
  425. }
  426. }
  427. }
  428. WaitStatus GetAddressInfo(const char* hostname, bool add_local_ips, std::string &name, std::vector<std::string> &addr_list)
  429. {
  430. NetworkAccessHandler::Auto scopedAccess;
  431. if (!is_loopback(hostname) || add_local_ips)
  432. {
  433. if (!scopedAccess.RequestAccessForAddressInfo(SocketImpl::is_private(hostname)))
  434. {
  435. return kWaitStatusFailure;
  436. }
  437. }
  438. addrinfo *info = NULL;
  439. addrinfo hints;
  440. memset(&hints, 0, sizeof(hints));
  441. // Here Mono inspects the ipv4Supported and ipv6Supported properties on the managed Socket class.
  442. // This seems to be unnecessary though, as we can use PF_UNSPEC in all cases, and getaddrinfo works.
  443. hints.ai_family = PF_UNSPEC;
  444. hints.ai_socktype = SOCK_STREAM;
  445. #if IL2CPP_TARGET_QNX
  446. // there is no AI_ADDRCONFIG flag on QNX:
  447. hints.ai_flags = AI_CANONNAME;
  448. #else
  449. hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
  450. #endif
  451. if (*hostname && getaddrinfo(hostname, NULL, &hints, &info) == -1)
  452. return kWaitStatusFailure;
  453. AddrinfoGetAddresses(info, name, add_local_ips, addr_list);
  454. if (info)
  455. freeaddrinfo(info);
  456. if (name.empty())
  457. name.assign(hostname);
  458. return kWaitStatusSuccess;
  459. }
  460. #endif
  461. WaitStatus SocketImpl::GetHostByAddr(const std::string &address, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addr_list)
  462. {
  463. NetworkAccessHandler::Auto scopedAccess;
  464. if (!is_loopback(address.c_str()))
  465. {
  466. if (!scopedAccess.RequestAccessForAddressInfo(is_private(address.c_str())))
  467. {
  468. return kWaitStatusFailure;
  469. }
  470. }
  471. #if IL2CPP_SUPPORT_IPV6
  472. struct sockaddr_in saddr;
  473. struct sockaddr_in6 saddr6;
  474. int32_t family;
  475. char hostname[1024] = {0};
  476. int flags = 0;
  477. if (inet_pton(AF_INET, address.c_str(), &saddr.sin_addr) <= 0)
  478. {
  479. /* Maybe an ipv6 address */
  480. if (inet_pton(AF_INET6, address.c_str(), &saddr6.sin6_addr) <= 0)
  481. {
  482. return kWaitStatusFailure;
  483. }
  484. else
  485. {
  486. family = AF_INET6;
  487. saddr6.sin6_family = AF_INET6;
  488. }
  489. }
  490. else
  491. {
  492. family = AF_INET;
  493. saddr.sin_family = AF_INET;
  494. }
  495. if (family == AF_INET)
  496. {
  497. #if HAVE_SOCKADDR_IN_SIN_LEN
  498. saddr.sin_len = sizeof(saddr);
  499. #endif
  500. if (getnameinfo((struct sockaddr*)&saddr, sizeof(saddr),
  501. hostname, sizeof(hostname), NULL, 0,
  502. flags) != 0)
  503. {
  504. return kWaitStatusFailure;
  505. }
  506. }
  507. else if (family == AF_INET6)
  508. {
  509. #if HAVE_SOCKADDR_IN6_SIN_LEN
  510. saddr6.sin6_len = sizeof(saddr6);
  511. #endif
  512. if (getnameinfo((struct sockaddr*)&saddr6, sizeof(saddr6),
  513. hostname, sizeof(hostname), NULL, 0,
  514. flags) != 0)
  515. {
  516. return kWaitStatusFailure;
  517. }
  518. }
  519. return GetAddressInfo(hostname, false, name, addr_list);
  520. #else
  521. struct in_addr inaddr;
  522. if (inet_pton(AF_INET, address.c_str(), &inaddr) <= 0)
  523. return kWaitStatusFailure;
  524. struct hostent *he = gethostbyaddr((char*)&inaddr, sizeof(inaddr), AF_INET);
  525. if (he == NULL)
  526. {
  527. name = address;
  528. addr_list.push_back(name);
  529. return kWaitStatusSuccess;
  530. }
  531. return hostent_get_info(he, name, aliases, addr_list)
  532. ? kWaitStatusSuccess
  533. : kWaitStatusFailure;
  534. #endif
  535. }
  536. WaitStatus SocketImpl::GetHostByName(const std::string &host, std::string &name, std::vector<std::string> &aliases, std::vector<std::string> &addresses)
  537. {
  538. char this_hostname[256] = {0};
  539. const char *hostname = host.c_str();
  540. bool add_local_ips = (*hostname == '\0');
  541. if (!add_local_ips && gethostname(this_hostname, sizeof(this_hostname)) != -1)
  542. {
  543. if (!strcmp(hostname, this_hostname))
  544. add_local_ips = true;
  545. }
  546. #if IL2CPP_SUPPORT_IPV6
  547. return GetAddressInfo(hostname, add_local_ips, name, addresses);
  548. #else
  549. struct hostent *he = NULL;
  550. if (*hostname)
  551. he = gethostbyname(hostname);
  552. if (*hostname && he == NULL)
  553. return kWaitStatusFailure;
  554. return (add_local_ips
  555. ? hostent_get_info_with_local_ips(he, name, aliases, addresses)
  556. : hostent_get_info(he, name, aliases, addresses))
  557. ? kWaitStatusSuccess
  558. : kWaitStatusFailure;
  559. #endif
  560. }
  561. static bool HasAnyIPv4Addresses(const std::vector<std::string>& addresses)
  562. {
  563. for (std::vector<std::string>::const_iterator it = addresses.begin(); it != addresses.end(); ++it)
  564. {
  565. in_addr address;
  566. if (inet_pton(AF_INET, it->c_str(), &address))
  567. return true;
  568. }
  569. return false;
  570. }
  571. 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)
  572. {
  573. std::vector<std::string> addresses;
  574. WaitStatus result = GetHostByName(host, name, aliases, addresses);
  575. // If we got an IPv4 address, use that and any others, skipping IPv6 addresses.
  576. // We can only return one address size, so we need to choose.
  577. if (HasAnyIPv4Addresses(addresses))
  578. {
  579. addr_size = sizeof(in_addr);
  580. family = AF_INET;
  581. for (std::vector<std::string>::iterator it = addresses.begin(); it != addresses.end(); ++it)
  582. {
  583. in_addr address;
  584. if (inet_pton(family, it->c_str(), &address))
  585. {
  586. void* addressLocation = il2cpp::utils::Memory::Malloc(addr_size);
  587. memcpy(addressLocation, &address.s_addr, addr_size);
  588. addr_list.push_back(addressLocation);
  589. }
  590. }
  591. }
  592. #if IL2CPP_SUPPORT_IPV6
  593. else
  594. {
  595. addr_size = sizeof(in6_addr);
  596. family = AF_INET6;
  597. for (std::vector<std::string>::iterator it = addresses.begin(); it != addresses.end(); ++it)
  598. {
  599. in6_addr address;
  600. if (inet_pton(family, it->c_str(), &address))
  601. {
  602. void* addressLocation = il2cpp::utils::Memory::Malloc(addr_size);
  603. memcpy(addressLocation, &address.s6_addr, addr_size);
  604. addr_list.push_back(addressLocation);
  605. }
  606. }
  607. }
  608. #endif
  609. return result;
  610. }
  611. WaitStatus SocketImpl::GetHostName(std::string &name)
  612. {
  613. char hostname[256];
  614. int32_t ret = gethostname(hostname, sizeof(hostname));
  615. if (ret == -1)
  616. return kWaitStatusFailure;
  617. name.assign(hostname);
  618. return kWaitStatusSuccess;
  619. }
  620. SocketImpl::SocketImpl(ThreadStatusCallback thread_status_callback)
  621. : _is_valid(false)
  622. , _fd(-1)
  623. , _domain(-1)
  624. , _type(-1)
  625. , _protocol(-1)
  626. , _saved_error(kErrorCodeSuccess)
  627. , _still_readable(0)
  628. , _thread_status_callback(thread_status_callback)
  629. {
  630. }
  631. SocketImpl::~SocketImpl()
  632. {
  633. }
  634. static int32_t convert_address_family(AddressFamily family)
  635. {
  636. switch (family)
  637. {
  638. case kAddressFamilyUnspecified:
  639. return AF_UNSPEC;
  640. case kAddressFamilyUnix:
  641. return AF_UNIX;
  642. case kAddressFamilyInterNetwork:
  643. return AF_INET;
  644. #ifdef AF_IPX
  645. case kAddressFamilyIpx:
  646. return AF_IPX;
  647. #endif
  648. #ifdef AF_SNA
  649. case kAddressFamilySna:
  650. return AF_SNA;
  651. #endif
  652. #ifdef AF_DECnet
  653. case kAddressFamilyDecNet:
  654. return AF_DECnet;
  655. #endif
  656. #ifdef AF_APPLETALK
  657. case kAddressFamilyAppleTalk:
  658. return AF_APPLETALK;
  659. #endif
  660. #ifdef AF_INET6
  661. case kAddressFamilyInterNetworkV6:
  662. return AF_INET6;
  663. #endif
  664. #ifdef AF_IRDA
  665. case kAddressFamilyIrda:
  666. return AF_IRDA;
  667. #endif
  668. default:
  669. break;
  670. }
  671. return -1;
  672. }
  673. static AddressFamily convert_define_to_address_family(int32_t family)
  674. {
  675. switch (family)
  676. {
  677. case AF_UNSPEC:
  678. return kAddressFamilyUnspecified;
  679. case AF_UNIX:
  680. return kAddressFamilyUnix;
  681. case AF_INET:
  682. return kAddressFamilyInterNetwork;
  683. #ifdef AF_IPX
  684. case AF_IPX:
  685. return kAddressFamilyIpx;
  686. #endif
  687. #ifdef AF_SNA
  688. case AF_SNA:
  689. return kAddressFamilySna;
  690. #endif
  691. #ifdef AF_DECnet
  692. case AF_DECnet:
  693. return kAddressFamilyDecNet;
  694. #endif
  695. #ifdef AF_APPLETALK
  696. case AF_APPLETALK:
  697. return kAddressFamilyAppleTalk;
  698. #endif
  699. #ifdef AF_INET6
  700. case AF_INET6:
  701. return kAddressFamilyInterNetworkV6;
  702. #endif
  703. #ifdef AF_IRDA
  704. case AF_IRDA:
  705. return kAddressFamilyIrda;
  706. #endif
  707. default:
  708. break;
  709. }
  710. return kAddressFamilyError;
  711. }
  712. static int32_t convert_socket_type(SocketType type)
  713. {
  714. switch (type)
  715. {
  716. case kSocketTypeStream:
  717. return SOCK_STREAM;
  718. case kSocketTypeDgram:
  719. return SOCK_DGRAM;
  720. case kSocketTypeRaw:
  721. return SOCK_RAW;
  722. #ifdef SOCK_RDM
  723. case kSocketTypeRdm:
  724. return SOCK_RDM;
  725. #endif
  726. #ifdef SOCK_SEQPACKET
  727. case kSocketTypeSeqpacket:
  728. return SOCK_SEQPACKET;
  729. #endif
  730. default:
  731. break;
  732. }
  733. return -1;
  734. }
  735. static int32_t convert_socket_protocol(ProtocolType protocol)
  736. {
  737. switch (protocol)
  738. {
  739. case kProtocolTypeIP:
  740. case kProtocolTypeIPv6:
  741. case kProtocolTypeIcmp:
  742. case kProtocolTypeIgmp:
  743. case kProtocolTypeGgp:
  744. case kProtocolTypeTcp:
  745. case kProtocolTypePup:
  746. case kProtocolTypeUdp:
  747. case kProtocolTypeIdp:
  748. // In this case the enum values map exactly.
  749. return (int32_t)protocol;
  750. default:
  751. break;
  752. }
  753. // Everything else in unsupported and unexpected
  754. return -1;
  755. }
  756. WaitStatus SocketImpl::Create(AddressFamily family, SocketType type, ProtocolType protocol)
  757. {
  758. _fd = -1;
  759. _is_valid = false;
  760. _still_readable = 1;
  761. _domain = convert_address_family(family);
  762. _type = convert_socket_type(type);
  763. _protocol = convert_socket_protocol(protocol);
  764. IL2CPP_ASSERT(_type != -1 && "Unsupported socket type");
  765. IL2CPP_ASSERT(_domain != -1 && "Unsupported address family");
  766. IL2CPP_ASSERT(_protocol != -1 && "Unsupported protocol type");
  767. _fd = socket(_domain, _type, _protocol);
  768. if (_fd == -1 && _domain == AF_INET && _type == SOCK_RAW && _protocol == 0)
  769. {
  770. // Retry with protocol == 4 (see bug #54565)
  771. _protocol = 4;
  772. _fd = socket(AF_INET, SOCK_RAW, 4);
  773. }
  774. if (_fd == -1)
  775. {
  776. StoreLastError();
  777. return kWaitStatusFailure;
  778. }
  779. // if (fd >= _wapi_fd_reserve)
  780. // {
  781. // WSASetLastError (WSASYSCALLFAILURE);
  782. // close (fd);
  783. // return(INVALID_SOCKET);
  784. // }
  785. /* .net seems to set this by default for SOCK_STREAM, not for
  786. * SOCK_DGRAM (see bug #36322)
  787. *
  788. * It seems winsock has a rather different idea of what
  789. * SO_REUSEADDR means. If it's set, then a new socket can be
  790. * bound over an existing listening socket. There's a new
  791. * windows-specific option called SO_EXCLUSIVEADDRUSE but
  792. * using that means the socket MUST be closed properly, or a
  793. * denial of service can occur. Luckily for us, winsock
  794. * behaves as though any other system would when SO_REUSEADDR
  795. * is true, so we don't need to do anything else here. See
  796. * bug 53992.
  797. */
  798. {
  799. int32_t v = 1;
  800. const int32_t ret = setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v));
  801. if (ret == -1)
  802. {
  803. if (SOCK_CLOSE(_fd) == -1)
  804. StoreLastError();
  805. return kWaitStatusFailure;
  806. }
  807. }
  808. #if IL2CPP_TARGET_DARWIN
  809. int32_t value = 1;
  810. setsockopt(_fd, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
  811. #endif
  812. // mono_once (&socket_ops_once, socket_ops_init);
  813. // handle = _wapi_handle_new_fd (WAPI_HANDLE_SOCKET, fd, &socket_handle);
  814. // if (handle == _WAPI_HANDLE_INVALID) {
  815. // g_warning ("%s: error creating socket handle", __func__);
  816. // WSASetLastError (WSASYSCALLFAILURE);
  817. // close (fd);
  818. // return(INVALID_SOCKET);
  819. // }
  820. _is_valid = true;
  821. _networkAccess.InheritNetworkAccessState(_fd);
  822. return kWaitStatusSuccess;
  823. }
  824. WaitStatus SocketImpl::Create(SocketDescriptor fd, int32_t family, int32_t type, int32_t protocol)
  825. {
  826. _fd = fd;
  827. _is_valid = (fd != -1);
  828. _still_readable = 1;
  829. _domain = family;
  830. _type = type;
  831. _protocol = protocol;
  832. _networkAccess.InheritNetworkAccessState(_fd);
  833. IL2CPP_ASSERT(_type != -1 && "Unsupported socket type");
  834. IL2CPP_ASSERT(_domain != -1 && "Unsupported address family");
  835. IL2CPP_ASSERT(_protocol != -1 && "Unsupported protocol type");
  836. return kWaitStatusSuccess;
  837. }
  838. WaitStatus SocketImpl::Close()
  839. {
  840. _saved_error = kErrorCodeSuccess;
  841. if (_is_valid && _fd != -1)
  842. {
  843. if (SOCK_CLOSE(_fd) == -1)
  844. StoreLastError();
  845. }
  846. _fd = -1;
  847. _is_valid = false;
  848. _still_readable = 0;
  849. _domain = -1;
  850. _type = -1;
  851. _protocol = -1;
  852. _networkAccess.CancelNetworkAccess();
  853. return kWaitStatusSuccess;
  854. }
  855. WaitStatus SocketImpl::SetBlocking(bool blocking)
  856. {
  857. #if IL2CPP_USE_SOCKET_SETBLOCKING
  858. return (WaitStatus)setBlocking(_fd, blocking);
  859. #else
  860. int32_t flags = fcntl(_fd, F_GETFL, 0);
  861. if (flags == -1)
  862. {
  863. StoreLastError();
  864. return kWaitStatusFailure;
  865. }
  866. flags = blocking
  867. ? (flags & ~O_NONBLOCK)
  868. : (flags | O_NONBLOCK);
  869. if (fcntl(_fd, F_SETFL, flags) == -1)
  870. {
  871. StoreLastError();
  872. return kWaitStatusFailure;
  873. }
  874. return kWaitStatusSuccess;
  875. #endif
  876. }
  877. ErrorCode SocketImpl::GetLastError() const
  878. {
  879. return _saved_error;
  880. }
  881. void SocketImpl::StoreLastError()
  882. {
  883. const ErrorCode error = SocketErrnoToErrorCode(errno);
  884. Error::SetLastError(error);
  885. _saved_error = error;
  886. }
  887. void SocketImpl::StoreLastError(int32_t error_no)
  888. {
  889. const ErrorCode error = SocketErrnoToErrorCode(error_no);
  890. Error::SetLastError(error);
  891. _saved_error = error;
  892. }
  893. #if SUPPORT_UNIXSOCKETS
  894. static struct sockaddr* sockaddr_from_path(const char *path, socklen_t *sa_size)
  895. {
  896. struct sockaddr_un* sa_un;
  897. const size_t len = strlen(path);
  898. if (len >= sizeof(sa_un->sun_path))
  899. return NULL;
  900. sa_un = (struct sockaddr_un*)IL2CPP_CALLOC(1, sizeof(sockaddr_un));
  901. sa_un->sun_family = AF_UNIX;
  902. memcpy(sa_un->sun_path, path, len);
  903. *sa_size = sizeof(sockaddr_un);
  904. return (struct sockaddr *)sa_un;
  905. }
  906. #endif
  907. #if IL2CPP_SUPPORT_IPV6
  908. static void sockaddr_from_address(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port, sockaddr_in6* sa, socklen_t *sa_size)
  909. {
  910. sa->sin6_family = AF_INET6;
  911. sa->sin6_port = port;
  912. memcpy(&sa->sin6_addr, &address[0], 16);
  913. sa->sin6_scope_id = scope;
  914. *sa_size = sizeof(struct sockaddr_in6);
  915. }
  916. #endif
  917. static void sockaddr_from_address(uint32_t address, uint16_t port, struct sockaddr *sa, socklen_t *sa_size)
  918. {
  919. struct sockaddr_in sa_in = {0};
  920. sa_in.sin_family = AF_INET;
  921. sa_in.sin_port = port;
  922. sa_in.sin_addr.s_addr = address;
  923. *sa_size = sizeof(struct sockaddr_in);
  924. *sa = *((struct sockaddr*)&sa_in);
  925. }
  926. static bool socketaddr_to_endpoint_info(const struct sockaddr *address, socklen_t address_len, EndPointInfo &info)
  927. {
  928. info.family = convert_define_to_address_family(address->sa_family);
  929. if (info.family == os::kAddressFamilyInterNetwork)
  930. {
  931. const struct sockaddr_in *address_in = (const struct sockaddr_in *)address;
  932. info.data.inet.port = ntohs(address_in->sin_port);
  933. info.data.inet.address = ntohl(address_in->sin_addr.s_addr);
  934. return true;
  935. }
  936. if (info.family == os::kAddressFamilyUnix)
  937. {
  938. for (int32_t i = 0; i < address_len; i++)
  939. info.data.path[i] = address->sa_data[i];
  940. return true;
  941. }
  942. #if IL2CPP_SUPPORT_IPV6
  943. if (info.family == os::kAddressFamilyInterNetworkV6)
  944. {
  945. const struct sockaddr_in6 *address_in = (const struct sockaddr_in6 *)address;
  946. uint16_t port = ntohs(address_in->sin6_port);
  947. info.data.raw[2] = (port >> 8) & 0xff;
  948. info.data.raw[3] = port & 0xff;
  949. for (int i = 0; i < 16; i++)
  950. info.data.raw[i + 8] = address_in->sin6_addr.s6_addr[i];
  951. info.data.raw[24] = address_in->sin6_scope_id & 0xff;
  952. info.data.raw[25] = (address_in->sin6_scope_id >> 8) & 0xff;
  953. info.data.raw[26] = (address_in->sin6_scope_id >> 16) & 0xff;
  954. info.data.raw[27] = (address_in->sin6_scope_id >> 24) & 0xff;
  955. return true;
  956. }
  957. #endif
  958. return false;
  959. }
  960. WaitStatus SocketImpl::Bind(const char *path)
  961. {
  962. #if SUPPORT_UNIXSOCKETS
  963. socklen_t sa_size = 0;
  964. struct sockaddr* sa = sockaddr_from_path(path, &sa_size);
  965. int result = bind(_fd, sa, sa_size);
  966. IL2CPP_FREE(sa);
  967. if (result == -1)
  968. {
  969. StoreLastError();
  970. return kWaitStatusFailure;
  971. }
  972. return kWaitStatusSuccess;
  973. #else
  974. return kWaitStatusFailure;
  975. #endif
  976. }
  977. WaitStatus SocketImpl::Bind(const char *address, uint16_t port)
  978. {
  979. struct sockaddr sa = {0};
  980. socklen_t sa_size = 0;
  981. sockaddr_from_address(inet_addr(address), htons(port), &sa, &sa_size);
  982. if (!_networkAccess.PrepareForBind(_fd, &sa, sa_size))
  983. {
  984. StoreLastError(_networkAccess.GetError());
  985. return kWaitStatusFailure;
  986. }
  987. if (bind(_fd, &sa, sa_size) == -1)
  988. {
  989. StoreLastError();
  990. return kWaitStatusFailure;
  991. }
  992. return kWaitStatusSuccess;
  993. }
  994. WaitStatus SocketImpl::Bind(uint32_t address, uint16_t port)
  995. {
  996. struct sockaddr sa = {0};
  997. socklen_t sa_size = 0;
  998. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  999. if (!_networkAccess.PrepareForBind(_fd, &sa, sa_size))
  1000. {
  1001. StoreLastError(_networkAccess.GetError());
  1002. return kWaitStatusFailure;
  1003. }
  1004. if (bind(_fd, &sa, sa_size) == -1)
  1005. {
  1006. StoreLastError();
  1007. return kWaitStatusFailure;
  1008. }
  1009. return kWaitStatusSuccess;
  1010. }
  1011. utils::Expected<WaitStatus> SocketImpl::Bind(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port)
  1012. {
  1013. #if IL2CPP_SUPPORT_IPV6
  1014. struct sockaddr_in6 sa = { 0 };
  1015. socklen_t sa_size = 0;
  1016. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1017. if (!_networkAccess.PrepareForBind(_fd, &sa, sa_size))
  1018. {
  1019. StoreLastError(_networkAccess.GetError());
  1020. return kWaitStatusFailure;
  1021. }
  1022. if (bind(_fd, (sockaddr*)&sa, sa_size) == -1)
  1023. {
  1024. StoreLastError();
  1025. return kWaitStatusFailure;
  1026. }
  1027. return kWaitStatusSuccess;
  1028. #else
  1029. return utils::Il2CppError(utils::NotSupported, "IPv6 is not supported on this platform.");
  1030. #endif
  1031. }
  1032. WaitStatus SocketImpl::ConnectInternal(struct sockaddr *sa, int32_t sa_size)
  1033. {
  1034. if (!_networkAccess.PrepareForConnect(_fd, sa, sa_size))
  1035. {
  1036. StoreLastError(_networkAccess.GetError());
  1037. return kWaitStatusFailure;
  1038. }
  1039. if (connect(_fd, sa, (socklen_t)sa_size) != -1)
  1040. return kWaitStatusSuccess;
  1041. if (errno != EINTR)
  1042. {
  1043. // errnum = errno_to_WSA (errnum, __func__);
  1044. // if (errnum == WSAEINPROGRESS)
  1045. // errnum = WSAEWOULDBLOCK; /* see bug #73053 */
  1046. StoreLastError();
  1047. return kWaitStatusFailure;
  1048. }
  1049. struct pollfd fds = {0};
  1050. fds.fd = _fd;
  1051. fds.events = POLLOUT;
  1052. while (poll(&fds, 1, -1) == -1)
  1053. {
  1054. if (errno != EINTR)
  1055. {
  1056. StoreLastError();
  1057. return kWaitStatusFailure;
  1058. }
  1059. }
  1060. int32_t so_error = 0;
  1061. socklen_t len = sizeof(so_error);
  1062. if (getsockopt(_fd, SOL_SOCKET, SO_ERROR, &so_error, &len) == -1)
  1063. {
  1064. StoreLastError();
  1065. return kWaitStatusFailure;
  1066. }
  1067. if (so_error != 0)
  1068. {
  1069. StoreLastError(so_error);
  1070. return kWaitStatusFailure;
  1071. }
  1072. return kWaitStatusSuccess;
  1073. }
  1074. WaitStatus SocketImpl::Connect(const char *path)
  1075. {
  1076. #if SUPPORT_UNIXSOCKETS
  1077. socklen_t sa_size = 0;
  1078. struct sockaddr* sa = sockaddr_from_path(path, &sa_size);
  1079. WaitStatus status = ConnectInternal(sa, sa_size);
  1080. IL2CPP_FREE(sa);
  1081. return status;
  1082. #else
  1083. return kWaitStatusFailure;
  1084. #endif
  1085. }
  1086. utils::Expected<WaitStatus> SocketImpl::Connect(uint8_t address[ipv6AddressSize], uint32_t scope, uint16_t port)
  1087. {
  1088. #if IL2CPP_SUPPORT_IPV6
  1089. struct sockaddr_in6 sa = { 0 };
  1090. socklen_t sa_size = 0;
  1091. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1092. return ConnectInternal((struct sockaddr *)&sa, sa_size);
  1093. #else
  1094. return utils::Il2CppError(utils::NotSupported, "IPv6 is not supported on this platform.");
  1095. #endif
  1096. }
  1097. WaitStatus SocketImpl::Connect(uint32_t address, uint16_t port)
  1098. {
  1099. struct sockaddr sa = {0};
  1100. socklen_t sa_size = 0;
  1101. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  1102. return ConnectInternal((struct sockaddr *)&sa, sa_size);
  1103. }
  1104. WaitStatus SocketImpl::GetLocalEndPointInfo(EndPointInfo &info)
  1105. {
  1106. // Note: the size here could probably be smaller
  1107. uint8_t buffer[END_POINT_MAX_PATH_LEN + 3] = {0};
  1108. socklen_t address_len = sizeof(buffer);
  1109. if (getsockname(_fd, (struct sockaddr *)buffer, &address_len) == -1)
  1110. {
  1111. StoreLastError();
  1112. return kWaitStatusFailure;
  1113. }
  1114. if (!socketaddr_to_endpoint_info((struct sockaddr *)buffer, address_len, info))
  1115. {
  1116. _saved_error = kWSAeafnosupport;
  1117. return kWaitStatusFailure;
  1118. }
  1119. return kWaitStatusSuccess;
  1120. }
  1121. WaitStatus SocketImpl::GetRemoteEndPointInfo(EndPointInfo &info)
  1122. {
  1123. // Note: the size here could probably be smaller
  1124. uint8_t buffer[END_POINT_MAX_PATH_LEN + 3] = {0};
  1125. socklen_t address_len = sizeof(buffer);
  1126. if (getpeername(_fd, (struct sockaddr *)buffer, &address_len) == -1)
  1127. {
  1128. StoreLastError();
  1129. return kWaitStatusFailure;
  1130. }
  1131. if (!socketaddr_to_endpoint_info((struct sockaddr *)buffer, address_len, info))
  1132. {
  1133. _saved_error = kWSAeafnosupport;
  1134. return kWaitStatusFailure;
  1135. }
  1136. return kWaitStatusSuccess;
  1137. }
  1138. WaitStatus SocketImpl::Listen(int32_t backlog)
  1139. {
  1140. if (listen(_fd, backlog) == -1)
  1141. {
  1142. StoreLastError();
  1143. return kWaitStatusFailure;
  1144. }
  1145. return kWaitStatusSuccess;
  1146. }
  1147. WaitStatus SocketImpl::Shutdown(int32_t how)
  1148. {
  1149. if (shutdown(_fd, how) == -1)
  1150. {
  1151. StoreLastError();
  1152. return kWaitStatusFailure;
  1153. }
  1154. if (how == SHUT_RD || how == SHUT_RDWR)
  1155. _still_readable = 0;
  1156. return kWaitStatusSuccess;
  1157. }
  1158. WaitStatus SocketImpl::Accept(os::Socket **socket)
  1159. {
  1160. int32_t new_fd = 0;
  1161. *socket = NULL;
  1162. do
  1163. {
  1164. new_fd = accept(_fd, NULL, 0);
  1165. }
  1166. while (new_fd == -1 && errno == EINTR);
  1167. if (new_fd == -1)
  1168. {
  1169. StoreLastError();
  1170. return kWaitStatusFailure;
  1171. }
  1172. *socket = new os::Socket(_thread_status_callback);
  1173. const WaitStatus status = (*socket)->Create(new_fd, _domain, _type, _protocol);
  1174. if (status != kWaitStatusSuccess)
  1175. {
  1176. delete *socket;
  1177. *socket = NULL;
  1178. return status;
  1179. }
  1180. return kWaitStatusSuccess;
  1181. }
  1182. WaitStatus SocketImpl::Disconnect(bool reuse)
  1183. {
  1184. int32_t new_sock = socket(_domain, _type, _protocol);
  1185. if (new_sock == -1)
  1186. {
  1187. StoreLastError();
  1188. return kWaitStatusFailure;
  1189. }
  1190. // According to Stevens "Advanced Programming in the UNIX
  1191. // Environment: UNIX File I/O" dup2() is atomic so there
  1192. // should not be a race condition between the old fd being
  1193. // closed and the new socket fd being copied over
  1194. int32_t ret = 0;
  1195. do
  1196. {
  1197. ret = dup2(new_sock, _fd);
  1198. }
  1199. while (ret == -1 && errno == EAGAIN);
  1200. if (ret == -1)
  1201. {
  1202. StoreLastError();
  1203. return kWaitStatusFailure;
  1204. }
  1205. SOCK_CLOSE(new_sock);
  1206. return kWaitStatusSuccess;
  1207. }
  1208. WaitStatus SocketImpl::Receive(const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1209. {
  1210. *len = 0;
  1211. const int32_t c_flags = convert_socket_flags(flags);
  1212. if (c_flags == -1)
  1213. {
  1214. _saved_error = kWSAeopnotsupp;
  1215. return kWaitStatusFailure;
  1216. }
  1217. return ReceiveFromInternal(data, count, c_flags, len, NULL, 0);
  1218. }
  1219. WaitStatus SocketImpl::ReceiveFromInternal(const uint8_t *data, size_t count, int32_t flags, int32_t *len, struct sockaddr *from, int32_t *fromlen)
  1220. {
  1221. int32_t ret = 0;
  1222. if (!_networkAccess.WaitForNetworkStatus(_fd))
  1223. {
  1224. StoreLastError(_networkAccess.GetError());
  1225. return kWaitStatusFailure;
  1226. }
  1227. do
  1228. {
  1229. ret = (int32_t)recvfrom(_fd, (void*)data, count, flags, from, (socklen_t*)fromlen);
  1230. }
  1231. while (ret == -1 && errno == EINTR);
  1232. if (ret == 0 && count > 0)
  1233. {
  1234. // According to the Linux man page, recvfrom only
  1235. // returns 0 when the socket has been shut down
  1236. // cleanly. Turn this into an EINTR to simulate win32
  1237. // behaviour of returning EINTR when a socket is
  1238. // closed while the recvfrom is blocking (we use a
  1239. // shutdown() in socket_close() to trigger this.) See
  1240. // bug 75705.
  1241. // Distinguish between the socket being shut down at
  1242. // the local or remote ends, and reads that request 0
  1243. // bytes to be read
  1244. // If this returns FALSE, it means the socket has been
  1245. // closed locally. If it returns TRUE, but
  1246. // still_readable != 1 then shutdown
  1247. // (SHUT_RD|SHUT_RDWR) has been called locally.
  1248. if (_still_readable != 1)
  1249. {
  1250. ret = -1;
  1251. errno = EINTR;
  1252. }
  1253. }
  1254. if (ret == -1)
  1255. {
  1256. StoreLastError();
  1257. return kWaitStatusFailure;
  1258. }
  1259. *len = ret;
  1260. return kWaitStatusSuccess;
  1261. }
  1262. WaitStatus SocketImpl::Send(const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1263. {
  1264. *len = 0;
  1265. int32_t c_flags = convert_socket_flags(flags);
  1266. if (c_flags == -1)
  1267. {
  1268. _saved_error = kWSAeopnotsupp;
  1269. return kWaitStatusFailure;
  1270. }
  1271. #if IL2CPP_USE_SEND_NOSIGNAL
  1272. c_flags |= MSG_NOSIGNAL;
  1273. #endif
  1274. int32_t ret = 0;
  1275. do
  1276. {
  1277. ret = (int32_t)send(_fd, (void*)data, count, c_flags);
  1278. }
  1279. while (ret == -1 && errno == EINTR);
  1280. if (ret == -1)
  1281. {
  1282. StoreLastError();
  1283. return kWaitStatusFailure;
  1284. }
  1285. *len = ret;
  1286. return kWaitStatusSuccess;
  1287. }
  1288. WaitStatus SocketImpl::SendArray(WSABuf *wsabufs, int32_t count, int32_t *sent, SocketFlags flags)
  1289. {
  1290. #if IL2CPP_SUPPORT_SEND_MSG
  1291. int32_t c_flags = convert_socket_flags(flags);
  1292. if (c_flags == -1)
  1293. {
  1294. _saved_error = kWSAeopnotsupp;
  1295. return kWaitStatusFailure;
  1296. }
  1297. struct msghdr hdr = {0};
  1298. hdr.msg_iovlen = count;
  1299. hdr.msg_iov = (struct iovec*)malloc(sizeof(struct iovec) * count);
  1300. for (int32_t i = 0; i < count; ++i)
  1301. {
  1302. hdr.msg_iov[i].iov_base = wsabufs[i].buffer;
  1303. hdr.msg_iov[i].iov_len = wsabufs[i].length;
  1304. }
  1305. #if IL2CPP_USE_SEND_NOSIGNAL
  1306. c_flags |= MSG_NOSIGNAL;
  1307. #endif
  1308. int32_t ret = 0;
  1309. do
  1310. {
  1311. ret = (int32_t)sendmsg(_fd, &hdr, c_flags);
  1312. }
  1313. while (ret == -1 && errno == EINTR);
  1314. free(hdr.msg_iov);
  1315. if (ret == -1)
  1316. {
  1317. *sent = 0;
  1318. StoreLastError();
  1319. return kWaitStatusFailure;
  1320. }
  1321. *sent = ret;
  1322. return kWaitStatusSuccess;
  1323. #else
  1324. if (sent != NULL)
  1325. {
  1326. *sent = 0; // Sent bytes.
  1327. }
  1328. if (wsabufs == NULL && count > 0)
  1329. {
  1330. _saved_error = kErrorInvalidFunction;
  1331. return kWaitStatusFailure;
  1332. }
  1333. int32_t c_flags = convert_socket_flags(flags);
  1334. for (int32_t i = 0; i < count; ++i)
  1335. {
  1336. ssize_t ret = 0;
  1337. do
  1338. {
  1339. ret = send(_fd, wsabufs[i].buffer, wsabufs[i].length, c_flags);
  1340. }
  1341. while (ret == EINTR);
  1342. if (ret == -1)
  1343. {
  1344. StoreLastError();
  1345. return kWaitStatusFailure;
  1346. }
  1347. if (sent != NULL)
  1348. {
  1349. *sent += ret;
  1350. }
  1351. }
  1352. return kWaitStatusSuccess;
  1353. #endif
  1354. }
  1355. WaitStatus SocketImpl::ReceiveArray(WSABuf *wsabufs, int32_t count, int32_t *len, SocketFlags flags)
  1356. {
  1357. #if IL2CPP_SUPPORT_RECV_MSG
  1358. const int32_t c_flags = convert_socket_flags(flags);
  1359. if (c_flags == -1)
  1360. {
  1361. _saved_error = kWSAeopnotsupp;
  1362. return kWaitStatusFailure;
  1363. }
  1364. struct msghdr hdr = {0};
  1365. hdr.msg_iovlen = count;
  1366. hdr.msg_iov = (struct iovec*)malloc(sizeof(struct iovec) * count);
  1367. for (int32_t i = 0; i < count; ++i)
  1368. {
  1369. hdr.msg_iov[i].iov_base = wsabufs[i].buffer;
  1370. hdr.msg_iov[i].iov_len = wsabufs[i].length;
  1371. }
  1372. int32_t ret = 0;
  1373. do
  1374. {
  1375. ret = (int32_t)recvmsg(_fd, &hdr, c_flags);
  1376. }
  1377. while (ret == -1 && errno == EINTR);
  1378. if (ret == 0)
  1379. {
  1380. // See SocketImpl::ReceiveFromInternal
  1381. if (_still_readable != 1)
  1382. {
  1383. ret = -1;
  1384. errno = EINTR;
  1385. }
  1386. }
  1387. free(hdr.msg_iov);
  1388. if (ret == -1)
  1389. {
  1390. *len = 0;
  1391. StoreLastError();
  1392. return kWaitStatusFailure;
  1393. }
  1394. *len = ret;
  1395. return kWaitStatusSuccess;
  1396. #else
  1397. if (len != NULL)
  1398. {
  1399. *len = 0;
  1400. }
  1401. if (wsabufs == NULL && count > 0)
  1402. {
  1403. _saved_error = kErrorInvalidFunction;
  1404. return kWaitStatusFailure;
  1405. }
  1406. int32_t c_flags = convert_socket_flags(flags);
  1407. for (int32_t i = 0; i < count; ++i)
  1408. {
  1409. int32_t ret = 0;
  1410. do
  1411. {
  1412. ret = recvfrom(_fd, wsabufs[i].buffer, wsabufs[i].length, c_flags, NULL, NULL);
  1413. }
  1414. while (ret == EINTR);
  1415. if (ret == 0 && count > 0)
  1416. {
  1417. if (_still_readable != 1)
  1418. {
  1419. _saved_error = SocketErrnoToErrorCode(EINTR);
  1420. return kWaitStatusFailure;
  1421. }
  1422. }
  1423. if (ret == -1)
  1424. {
  1425. StoreLastError();
  1426. return kWaitStatusFailure;
  1427. }
  1428. if (len != NULL)
  1429. {
  1430. *len += ret;
  1431. }
  1432. }
  1433. return kWaitStatusSuccess;
  1434. #endif
  1435. }
  1436. WaitStatus SocketImpl::SendToInternal(struct sockaddr *sa, int32_t sa_size, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1437. {
  1438. int32_t c_flags = convert_socket_flags(flags);
  1439. if (c_flags == -1)
  1440. {
  1441. _saved_error = kWSAeopnotsupp;
  1442. return kWaitStatusFailure;
  1443. }
  1444. #if IL2CPP_USE_SEND_NOSIGNAL
  1445. c_flags |= MSG_NOSIGNAL;
  1446. #endif
  1447. if (!_networkAccess.RequestNetwork(_fd, sa, sa_size))
  1448. {
  1449. StoreLastError(_networkAccess.GetError());
  1450. return kWaitStatusFailure;
  1451. }
  1452. int32_t ret = 0;
  1453. do
  1454. {
  1455. ret = (int32_t)sendto(_fd, (void*)data, count, c_flags, sa, sa_size);
  1456. }
  1457. while (ret == -1 && errno == EINTR);
  1458. if (ret == -1)
  1459. {
  1460. StoreLastError();
  1461. return kWaitStatusFailure;
  1462. }
  1463. *len = ret;
  1464. return kWaitStatusSuccess;
  1465. }
  1466. WaitStatus SocketImpl::SendTo(uint32_t address, uint16_t port, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1467. {
  1468. *len = 0;
  1469. struct sockaddr sa = {0};
  1470. socklen_t sa_size = 0;
  1471. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  1472. return SendToInternal(&sa, sa_size, data, count, flags, len);
  1473. }
  1474. WaitStatus SocketImpl::SendTo(const char *path, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len)
  1475. {
  1476. #if SUPPORT_UNIXSOCKETS
  1477. *len = 0;
  1478. socklen_t sa_size = 0;
  1479. struct sockaddr* sa = sockaddr_from_path(path, &sa_size);
  1480. WaitStatus status = SendToInternal(sa, sa_size, data, count, flags, len);
  1481. IL2CPP_FREE(sa);
  1482. return status;
  1483. #else
  1484. return kWaitStatusFailure;
  1485. #endif
  1486. }
  1487. utils::Expected<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)
  1488. {
  1489. #if IL2CPP_SUPPORT_IPV6
  1490. struct sockaddr_in6 sa = { 0 };
  1491. socklen_t sa_size = 0;
  1492. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1493. return SendToInternal((sockaddr*)&sa, sa_size, data, count, flags, len);
  1494. #else
  1495. return utils::Il2CppError(utils::NotSupported, "IPv6 is not supported on this platform.");
  1496. #endif
  1497. }
  1498. 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)
  1499. {
  1500. *len = 0;
  1501. struct sockaddr sa = {0};
  1502. socklen_t sa_size = 0;
  1503. sockaddr_from_address(htonl(address), htons(port), &sa, &sa_size);
  1504. const int32_t c_flags = convert_socket_flags(flags);
  1505. if (c_flags == -1)
  1506. {
  1507. _saved_error = kWSAeopnotsupp;
  1508. return kWaitStatusFailure;
  1509. }
  1510. const WaitStatus status = ReceiveFromInternal(data, count, c_flags, len, &sa, (int32_t*)&sa_size);
  1511. if (status != kWaitStatusSuccess)
  1512. {
  1513. ep.family = os::kAddressFamilyError;
  1514. return status;
  1515. }
  1516. if (sa_size == 0)
  1517. return kWaitStatusSuccess;
  1518. if (!socketaddr_to_endpoint_info(&sa, sa_size, ep))
  1519. {
  1520. ep.family = os::kAddressFamilyError;
  1521. _saved_error = kWSAeafnosupport;
  1522. return kWaitStatusFailure;
  1523. }
  1524. return kWaitStatusSuccess;
  1525. }
  1526. WaitStatus SocketImpl::RecvFrom(const char *path, const uint8_t *data, int32_t count, os::SocketFlags flags, int32_t *len, os::EndPointInfo &ep)
  1527. {
  1528. #if SUPPORT_UNIXSOCKETS
  1529. *len = 0;
  1530. socklen_t sa_size = 0;
  1531. struct sockaddr* sa = sockaddr_from_path(path, &sa_size);
  1532. const int32_t c_flags = convert_socket_flags(flags);
  1533. if (c_flags == -1)
  1534. {
  1535. _saved_error = kWSAeopnotsupp;
  1536. IL2CPP_FREE(sa);
  1537. return kWaitStatusFailure;
  1538. }
  1539. const WaitStatus status = ReceiveFromInternal(data, count, c_flags, len, sa, (int32_t*)&sa_size);
  1540. if (status != kWaitStatusSuccess)
  1541. {
  1542. ep.family = os::kAddressFamilyError;
  1543. IL2CPP_FREE(sa);
  1544. return kWaitStatusFailure;
  1545. }
  1546. if (sa_size == 0)
  1547. {
  1548. IL2CPP_FREE(sa);
  1549. return kWaitStatusSuccess;
  1550. }
  1551. if (!socketaddr_to_endpoint_info(sa, sa_size, ep))
  1552. {
  1553. ep.family = os::kAddressFamilyError;
  1554. _saved_error = kWSAeafnosupport;
  1555. IL2CPP_FREE(sa);
  1556. return kWaitStatusFailure;
  1557. }
  1558. IL2CPP_FREE(sa);
  1559. return kWaitStatusSuccess;
  1560. #else
  1561. return kWaitStatusFailure;
  1562. #endif
  1563. }
  1564. utils::Expected<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)
  1565. {
  1566. #if IL2CPP_SUPPORT_IPV6
  1567. struct sockaddr_in6 sa = { 0 };
  1568. socklen_t sa_size = 0;
  1569. sockaddr_from_address(address, scope, htons(port), &sa, &sa_size);
  1570. const int32_t c_flags = convert_socket_flags(flags);
  1571. if (c_flags == -1)
  1572. {
  1573. _saved_error = kWSAeopnotsupp;
  1574. return kWaitStatusFailure;
  1575. }
  1576. const WaitStatus status = ReceiveFromInternal(data, count, c_flags, len, (sockaddr*)&sa, (int32_t*)&sa_size);
  1577. if (status != kWaitStatusSuccess)
  1578. {
  1579. ep.family = os::kAddressFamilyError;
  1580. return kWaitStatusFailure;
  1581. }
  1582. if (sa_size == 0)
  1583. return kWaitStatusSuccess;
  1584. if (!socketaddr_to_endpoint_info((sockaddr*)&sa, sa_size, ep))
  1585. {
  1586. ep.family = os::kAddressFamilyError;
  1587. _saved_error = kWSAeafnosupport;
  1588. return kWaitStatusFailure;
  1589. }
  1590. return kWaitStatusSuccess;
  1591. #else
  1592. return utils::Il2CppError(utils::NotSupported, "IPv6 is not supported on this platform.");
  1593. #endif
  1594. }
  1595. WaitStatus SocketImpl::Available(int32_t *amount)
  1596. {
  1597. // ioctl (fd, FIONREAD, XXX) returns the size of
  1598. // the UDP header as well on Darwin.
  1599. //
  1600. // Use getsockopt SO_NREAD instead to get the
  1601. // right values for TCP and UDP.
  1602. //
  1603. // ai_canonname can be null in some cases on darwin, where the runtime assumes it will
  1604. // be the value of the ip buffer.
  1605. *amount = 0;
  1606. #if IL2CPP_TARGET_DARWIN
  1607. socklen_t optlen = sizeof(int32_t);
  1608. if (getsockopt(_fd, SOL_SOCKET, SO_NREAD, amount, &optlen) == -1)
  1609. #else
  1610. if (ioctl(_fd, FIONREAD, amount) == -1)
  1611. #endif
  1612. {
  1613. StoreLastError();
  1614. return kWaitStatusFailure;
  1615. }
  1616. return kWaitStatusSuccess;
  1617. }
  1618. 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)
  1619. {
  1620. IL2CPP_ASSERT(command != 0xC8000006 /* SIO_GET_EXTENSION_FUNCTION_POINTER */ && "SIO_GET_EXTENSION_FUNCTION_POINTER ioctl command not supported");
  1621. if (command == 0x98000004 /* SIO_KEEPALIVE_VALS */)
  1622. {
  1623. if (in_len < 3 * sizeof(uint32_t))
  1624. {
  1625. StoreLastError();
  1626. return kWaitStatusFailure;
  1627. }
  1628. uint32_t onoff = *((uint32_t*)in_data);
  1629. int32_t ret = setsockopt(_fd, SOL_SOCKET, SO_KEEPALIVE, &onoff, sizeof(uint32_t));
  1630. if (ret < 0)
  1631. {
  1632. StoreLastError();
  1633. return kWaitStatusFailure;
  1634. }
  1635. }
  1636. else
  1637. {
  1638. uint8_t *buffer = NULL;
  1639. if (in_len > 0)
  1640. {
  1641. buffer = (uint8_t*)malloc(in_len);
  1642. memcpy(buffer, in_data, in_len);
  1643. }
  1644. const int32_t ret = ioctl(_fd, command, buffer);
  1645. if (ret == -1)
  1646. {
  1647. StoreLastError();
  1648. free(buffer);
  1649. return kWaitStatusFailure;
  1650. }
  1651. if (buffer == NULL)
  1652. {
  1653. *written = 0;
  1654. return kWaitStatusSuccess;
  1655. }
  1656. // We just copy the buffer to the out_data. Some ioctls
  1657. // don't even out_data any data, but, well ...
  1658. //
  1659. // NB: windows returns WSAEFAULT if out_len is too small
  1660. const int32_t len = (in_len > out_len) ? out_len : in_len;
  1661. if (len > 0 && out_data != NULL)
  1662. memcpy(out_data, buffer, len);
  1663. free(buffer);
  1664. *written = len;
  1665. }
  1666. return kWaitStatusSuccess;
  1667. }
  1668. #define SKIP_OPTION -2
  1669. #define INVALID_OPTION_NAME -1
  1670. static int32_t level_and_name_to_system(SocketOptionLevel level, SocketOptionName name, int32_t *system_level, int32_t *system_name)
  1671. {
  1672. switch (level)
  1673. {
  1674. case kSocketOptionLevelSocket:
  1675. *system_level = SOL_SOCKET;
  1676. switch (name)
  1677. {
  1678. // This is SO_LINGER, because the setsockopt
  1679. // internal call maps DontLinger to SO_LINGER
  1680. // with l_onoff=0
  1681. case kSocketOptionNameDontLinger:
  1682. *system_name = SO_LINGER;
  1683. break;
  1684. #ifdef SO_DEBUG
  1685. case kSocketOptionNameDebug:
  1686. *system_name = SO_DEBUG;
  1687. break;
  1688. #endif
  1689. #ifdef SO_ACCEPTCONN
  1690. case kSocketOptionNameAcceptConnection:
  1691. *system_name = SO_ACCEPTCONN;
  1692. break;
  1693. #endif
  1694. case kSocketOptionNameReuseAddress:
  1695. *system_name = SO_REUSEADDR;
  1696. break;
  1697. case kSocketOptionNameKeepAlive:
  1698. *system_name = SO_KEEPALIVE;
  1699. break;
  1700. #ifdef SO_DONTROUTE
  1701. case kSocketOptionNameDontRoute:
  1702. *system_name = SO_DONTROUTE;
  1703. break;
  1704. #endif
  1705. case kSocketOptionNameBroadcast:
  1706. *system_name = SO_BROADCAST;
  1707. break;
  1708. case kSocketOptionNameLinger:
  1709. *system_name = SO_LINGER;
  1710. break;
  1711. #ifdef SO_OOBINLINE
  1712. case kSocketOptionNameOutOfBandInline:
  1713. *system_name = SO_OOBINLINE;
  1714. break;
  1715. #endif
  1716. case kSocketOptionNameSendBuffer:
  1717. *system_name = SO_SNDBUF;
  1718. break;
  1719. case kSocketOptionNameReceiveBuffer:
  1720. *system_name = SO_RCVBUF;
  1721. break;
  1722. case kSocketOptionNameSendLowWater:
  1723. *system_name = SO_SNDLOWAT;
  1724. break;
  1725. case kSocketOptionNameReceiveLowWater:
  1726. *system_name = SO_RCVLOWAT;
  1727. break;
  1728. case kSocketOptionNameSendTimeout:
  1729. *system_name = SO_SNDTIMEO;
  1730. break;
  1731. case kSocketOptionNameReceiveTimeout:
  1732. *system_name = SO_RCVTIMEO;
  1733. break;
  1734. case kSocketOptionNameError:
  1735. *system_name = SO_ERROR;
  1736. break;
  1737. case kSocketOptionNameType:
  1738. *system_name = SO_TYPE;
  1739. break;
  1740. case kSocketOptionNameExclusiveAddressUse:
  1741. #ifdef SO_EXCLUSIVEADDRUSE
  1742. *system_name = SO_EXCLUSIVEADDRUSE;
  1743. break;
  1744. #elif SO_REUSEADDR
  1745. *system_name = SO_REUSEADDR;
  1746. break;
  1747. #endif
  1748. case kSocketOptionNameUseLoopback:
  1749. #ifdef SO_USELOOPBACK
  1750. *system_name = SO_USELOOPBACK;
  1751. break;
  1752. #endif
  1753. case kSocketOptionNameMaxConnections:
  1754. #ifdef SO_MAXCONN
  1755. *system_name = SO_MAXCONN;
  1756. break;
  1757. #elif defined(SOMAXCONN)
  1758. *system_name = SOMAXCONN;
  1759. break;
  1760. #endif
  1761. default:
  1762. return INVALID_OPTION_NAME;
  1763. }
  1764. break;
  1765. case kSocketOptionLevelIP:
  1766. #ifdef SOL_IP
  1767. *system_level = SOL_IP;
  1768. #else
  1769. *system_level = IPPROTO_IP;
  1770. #endif
  1771. switch (name)
  1772. {
  1773. #ifdef IP_OPTIONS
  1774. case kSocketOptionNameIPOptions:
  1775. *system_name = IP_OPTIONS;
  1776. break;
  1777. #endif
  1778. case kSocketOptionNameHeaderIncluded:
  1779. *system_name = IP_HDRINCL;
  1780. break;
  1781. case kSocketOptionNameTypeOfService:
  1782. *system_name = IP_TOS;
  1783. break;
  1784. case kSocketOptionNameIpTimeToLive:
  1785. *system_name = IP_TTL;
  1786. break;
  1787. case kSocketOptionNameMulticastInterface:
  1788. *system_name = IP_MULTICAST_IF;
  1789. break;
  1790. case kSocketOptionNameMulticastTimeToLive:
  1791. *system_name = IP_MULTICAST_TTL;
  1792. break;
  1793. case kSocketOptionNameMulticastLoopback:
  1794. *system_name = IP_MULTICAST_LOOP;
  1795. break;
  1796. case kSocketOptionNameAddMembership:
  1797. *system_name = IP_ADD_MEMBERSHIP;
  1798. break;
  1799. case kSocketOptionNameDropMembership:
  1800. *system_name = IP_DROP_MEMBERSHIP;
  1801. break;
  1802. #ifdef HAVE_IP_PKTINFO
  1803. case kSocketOptionNamePacketInformation:
  1804. *system_name = IP_PKTINFO;
  1805. break;
  1806. #endif
  1807. case kSocketOptionNameDontFragment:
  1808. #ifdef IP_DONTFRAGMENT
  1809. *system_name = IP_DONTFRAGMENT;
  1810. #elif IP_MTU_DISCOVER
  1811. *system_name = IP_MTU_DISCOVER;
  1812. #elif IP_DONTFRAG
  1813. *system_name = IP_DONTFRAG;
  1814. #else
  1815. return SKIP_OPTION;
  1816. #endif
  1817. break;
  1818. case kSocketOptionNameAddSourceMembership:
  1819. case kSocketOptionNameDropSourceMembership:
  1820. case kSocketOptionNameBlockSource:
  1821. case kSocketOptionNameUnblockSource:
  1822. // Can't figure out how to map these, so fall
  1823. // through
  1824. default:
  1825. return INVALID_OPTION_NAME;
  1826. }
  1827. break;
  1828. #if IL2CPP_SUPPORT_IPV6
  1829. case kSocketOptionLevelIPv6:
  1830. #ifdef SOL_IPV6
  1831. *system_level = SOL_IPV6;
  1832. #else
  1833. *system_level = IPPROTO_IPV6;
  1834. #endif
  1835. switch (name)
  1836. {
  1837. case kSocketOptionNameMulticastInterface:
  1838. *system_name = IPV6_MULTICAST_IF;
  1839. break;
  1840. case kSocketOptionNameMulticastTimeToLive:
  1841. *system_name = IPV6_MULTICAST_HOPS;
  1842. break;
  1843. case kSocketOptionNameMulticastLoopback:
  1844. *system_name = IPV6_MULTICAST_LOOP;
  1845. break;
  1846. case kSocketOptionNameAddMembership:
  1847. *system_name = IPV6_JOIN_GROUP;
  1848. break;
  1849. case kSocketOptionNameDropMembership:
  1850. *system_name = IPV6_LEAVE_GROUP;
  1851. break;
  1852. case kSocketOptionNamePacketInformation:
  1853. #ifdef HAVE_IPV6_PKTINFO
  1854. *system_name = IPV6_PKTINFO;
  1855. break;
  1856. #endif
  1857. case kSocketOptionNameIPv6Only:
  1858. #ifdef IPV6_V6ONLY
  1859. *system_name = IPV6_V6ONLY;
  1860. break;
  1861. #endif
  1862. case kSocketOptionNameHeaderIncluded:
  1863. case kSocketOptionNameIPOptions:
  1864. case kSocketOptionNameTypeOfService:
  1865. case kSocketOptionNameDontFragment:
  1866. case kSocketOptionNameAddSourceMembership:
  1867. case kSocketOptionNameDropSourceMembership:
  1868. case kSocketOptionNameBlockSource:
  1869. case kSocketOptionNameUnblockSource:
  1870. // Can't figure out how to map these, so fall
  1871. // through
  1872. default:
  1873. return INVALID_OPTION_NAME;
  1874. }
  1875. break;
  1876. #endif // IL2CPP_SUPPORT_IPV6
  1877. case kSocketOptionLevelTcp:
  1878. #ifdef SOL_TCP
  1879. *system_level = SOL_TCP;
  1880. #else
  1881. *system_level = IPPROTO_TCP;
  1882. #endif
  1883. switch (name)
  1884. {
  1885. case kSocketOptionNameNoDelay:
  1886. *system_name = TCP_NODELAY;
  1887. break;
  1888. default:
  1889. return INVALID_OPTION_NAME;
  1890. }
  1891. break;
  1892. case kSocketOptionLevelUdp:
  1893. default:
  1894. return INVALID_OPTION_NAME;
  1895. }
  1896. return 0;
  1897. }
  1898. WaitStatus SocketImpl::GetSocketOption(SocketOptionLevel level, SocketOptionName name, uint8_t *buffer, int32_t *length)
  1899. {
  1900. int32_t system_level = 0;
  1901. int32_t system_name = 0;
  1902. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1903. if (o_res == SKIP_OPTION)
  1904. {
  1905. *((int32_t*)buffer) = 0;
  1906. *length = sizeof(int32_t);
  1907. return kWaitStatusSuccess;
  1908. }
  1909. if (o_res == INVALID_OPTION_NAME)
  1910. {
  1911. _saved_error = kWSAenoprotoopt;
  1912. return kWaitStatusFailure;
  1913. }
  1914. struct timeval tv;
  1915. uint8_t *tmp_val = buffer;
  1916. if (system_level == SOL_SOCKET && (system_name == SO_RCVTIMEO || system_name == SO_SNDTIMEO))
  1917. {
  1918. tmp_val = (uint8_t*)&tv;
  1919. *length = sizeof(tv);
  1920. }
  1921. const int32_t ret = getsockopt(_fd, system_level, system_name, tmp_val, (socklen_t*)length);
  1922. if (ret == -1)
  1923. {
  1924. StoreLastError();
  1925. return kWaitStatusFailure;
  1926. }
  1927. if (system_level == SOL_SOCKET && (system_name == SO_RCVTIMEO || system_name == SO_SNDTIMEO))
  1928. {
  1929. // milliseconds from microseconds
  1930. *((int32_t*)buffer) = (int32_t)(tv.tv_sec * 1000 + (tv.tv_usec / 1000));
  1931. *length = sizeof(int32_t);
  1932. return kWaitStatusSuccess;
  1933. }
  1934. if (system_name == SO_ERROR)
  1935. {
  1936. if (*((int32_t*)buffer) != 0)
  1937. {
  1938. StoreLastError(*((int32_t*)buffer));
  1939. }
  1940. else
  1941. {
  1942. *((int32_t*)buffer) = _saved_error;
  1943. }
  1944. }
  1945. return kWaitStatusSuccess;
  1946. }
  1947. WaitStatus SocketImpl::GetSocketOptionFull(SocketOptionLevel level, SocketOptionName name, int32_t *first, int32_t *second)
  1948. {
  1949. int32_t system_level = 0;
  1950. int32_t system_name = 0;
  1951. #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
  1952. if (level == kSocketOptionLevelSocket && name == kSocketOptionNameExclusiveAddressUse)
  1953. {
  1954. system_level = SOL_SOCKET;
  1955. system_name = SO_REUSEADDR;
  1956. }
  1957. else
  1958. #endif
  1959. {
  1960. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  1961. if (o_res == SKIP_OPTION)
  1962. {
  1963. *first = 0;
  1964. *second = 0;
  1965. return kWaitStatusSuccess;
  1966. }
  1967. if (o_res == INVALID_OPTION_NAME)
  1968. {
  1969. _saved_error = kWSAenoprotoopt;
  1970. return kWaitStatusFailure;
  1971. }
  1972. }
  1973. int32_t ret = -1;
  1974. switch (name)
  1975. {
  1976. case kSocketOptionNameLinger:
  1977. {
  1978. struct linger linger;
  1979. socklen_t lingersize = sizeof(linger);
  1980. ret = getsockopt(_fd, system_level, system_name, &linger, &lingersize);
  1981. *first = linger.l_onoff;
  1982. *second = linger.l_linger;
  1983. }
  1984. break;
  1985. case kSocketOptionNameDontLinger:
  1986. {
  1987. struct linger linger;
  1988. socklen_t lingersize = sizeof(linger);
  1989. ret = getsockopt(_fd, system_level, system_name, &linger, &lingersize);
  1990. *first = !linger.l_onoff;
  1991. }
  1992. break;
  1993. case kSocketOptionNameSendTimeout:
  1994. case kSocketOptionNameReceiveTimeout:
  1995. {
  1996. struct timeval time;
  1997. socklen_t time_size = sizeof(time);
  1998. ret = getsockopt(_fd, system_level, system_name, &time, &time_size);
  1999. // Use a 64-bit integer to avoid overflow
  2000. uint64_t timeInMilliseconds = (time.tv_sec * (uint64_t)1000) + (time.tv_usec / 1000);
  2001. // Truncate back to a 32-bit integer to return the value back to the caller.
  2002. *first = (int32_t)timeInMilliseconds;
  2003. }
  2004. break;
  2005. default:
  2006. {
  2007. socklen_t valsize = sizeof(*first);
  2008. ret = getsockopt(_fd, system_level, system_name, first, &valsize);
  2009. }
  2010. break;
  2011. }
  2012. if (ret == -1)
  2013. {
  2014. StoreLastError();
  2015. return kWaitStatusFailure;
  2016. }
  2017. #if !defined(SO_EXCLUSIVEADDRUSE) && defined(SO_REUSEADDR)
  2018. if (level == kSocketOptionLevelSocket && name == kSocketOptionNameExclusiveAddressUse)
  2019. *first = *first ? 0 : 1;
  2020. #endif
  2021. return kWaitStatusSuccess;
  2022. }
  2023. WaitStatus SocketImpl::Poll(std::vector<PollRequest> &requests, int32_t count, int32_t timeout, int32_t *result, int32_t *error)
  2024. {
  2025. const int32_t n_fd = count;
  2026. pollfd *p_fd = (pollfd*)calloc(n_fd, sizeof(pollfd));
  2027. for (int32_t i = 0; i < n_fd; ++i)
  2028. {
  2029. if (requests[i].fd == -1)
  2030. {
  2031. p_fd[i].fd = -1;
  2032. p_fd[i].events = kPollFlagsNone;
  2033. p_fd[i].revents = kPollFlagsNone;
  2034. }
  2035. else
  2036. {
  2037. p_fd[i].fd = requests[i].fd;
  2038. p_fd[i].events = posix::PollFlagsToPollEvents(requests[i].events);
  2039. p_fd[i].revents = kPollFlagsNone;
  2040. }
  2041. }
  2042. int32_t ret = os::posix::Poll(p_fd, n_fd, timeout);
  2043. *result = ret;
  2044. if (ret == -1)
  2045. {
  2046. free(p_fd);
  2047. *error = SocketErrnoToErrorCode(errno);
  2048. return kWaitStatusFailure;
  2049. }
  2050. if (ret == 0)
  2051. {
  2052. free(p_fd);
  2053. return kWaitStatusSuccess;
  2054. }
  2055. for (int32_t i = 0; i < n_fd; ++i)
  2056. {
  2057. requests[i].revents = posix::PollEventsToPollFlags(p_fd[i].revents);
  2058. }
  2059. free(p_fd);
  2060. return kWaitStatusSuccess;
  2061. }
  2062. WaitStatus SocketImpl::Poll(std::vector<PollRequest> &requests, int32_t timeout, int32_t *result, int32_t *error)
  2063. {
  2064. return Poll(requests, (int32_t)requests.size(), timeout, result, error);
  2065. }
  2066. WaitStatus SocketImpl::Poll(PollRequest& request, int32_t timeout, int32_t *result, int32_t *error)
  2067. {
  2068. std::vector<PollRequest> requests;
  2069. requests.push_back(request);
  2070. return Poll(requests, 1, timeout, result, error);
  2071. }
  2072. WaitStatus SocketImpl::SetSocketOption(SocketOptionLevel level, SocketOptionName name, int32_t value)
  2073. {
  2074. int32_t system_level = 0;
  2075. int32_t system_name = 0;
  2076. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  2077. if (o_res == SKIP_OPTION)
  2078. {
  2079. return kWaitStatusSuccess;
  2080. }
  2081. if (o_res == INVALID_OPTION_NAME)
  2082. {
  2083. _saved_error = kWSAenoprotoopt;
  2084. return kWaitStatusFailure;
  2085. }
  2086. struct linger linger;
  2087. WaitStatus ret = kWaitStatusFailure;
  2088. switch (name)
  2089. {
  2090. case kSocketOptionNameDontLinger:
  2091. linger.l_onoff = !value;
  2092. linger.l_linger = 0;
  2093. ret = SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  2094. break;
  2095. case kSocketOptionNameDontFragment:
  2096. #ifdef IP_PMTUDISC_DO
  2097. // Fiddle with the value slightly if we're turning DF on
  2098. if (value == 1)
  2099. value = IP_PMTUDISC_DO;
  2100. #endif
  2101. ret = SetSocketOptionInternal(system_level, system_name, (char*)&value, sizeof(value));
  2102. break;
  2103. default:
  2104. ret = SetSocketOptionInternal(system_level, system_name, (char*)&value, sizeof(value));
  2105. break;
  2106. }
  2107. return ret;
  2108. }
  2109. WaitStatus SocketImpl::SetSocketOptionLinger(SocketOptionLevel level, SocketOptionName name, bool enabled, int32_t seconds)
  2110. {
  2111. int32_t system_level = 0;
  2112. int32_t system_name = 0;
  2113. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  2114. if (o_res == SKIP_OPTION)
  2115. {
  2116. return kWaitStatusSuccess;
  2117. }
  2118. if (o_res == INVALID_OPTION_NAME)
  2119. {
  2120. _saved_error = kWSAenoprotoopt;
  2121. return kWaitStatusFailure;
  2122. }
  2123. struct linger linger;
  2124. linger.l_onoff = enabled;
  2125. linger.l_linger = seconds;
  2126. return SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  2127. }
  2128. WaitStatus SocketImpl::SetSocketOptionArray(SocketOptionLevel level, SocketOptionName name, const uint8_t *buffer, int32_t length)
  2129. {
  2130. int32_t system_level = 0;
  2131. int32_t system_name = 0;
  2132. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  2133. if (o_res == SKIP_OPTION)
  2134. {
  2135. return kWaitStatusSuccess;
  2136. }
  2137. if (o_res == INVALID_OPTION_NAME)
  2138. {
  2139. _saved_error = kWSAenoprotoopt;
  2140. return kWaitStatusFailure;
  2141. }
  2142. struct linger linger;
  2143. WaitStatus ret = kWaitStatusFailure;
  2144. switch (name)
  2145. {
  2146. case kSocketOptionNameDontLinger:
  2147. if (length == 1)
  2148. {
  2149. linger.l_linger = 0;
  2150. linger.l_onoff = (*((char*)buffer)) ? 0 : 1;
  2151. ret = SetSocketOptionInternal(system_level, system_name, &linger, sizeof(linger));
  2152. }
  2153. else
  2154. {
  2155. _saved_error = kWSAeinval;
  2156. return kWaitStatusFailure;
  2157. }
  2158. break;
  2159. default:
  2160. ret = SetSocketOptionInternal(system_level, system_name, buffer, length);
  2161. break;
  2162. }
  2163. return ret;
  2164. }
  2165. WaitStatus SocketImpl::SetSocketOptionMembership(SocketOptionLevel level, SocketOptionName name, uint32_t group_address, uint32_t local_address)
  2166. {
  2167. int32_t system_level = 0;
  2168. int32_t system_name = 0;
  2169. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  2170. if (o_res == SKIP_OPTION)
  2171. {
  2172. return kWaitStatusSuccess;
  2173. }
  2174. if (o_res == INVALID_OPTION_NAME)
  2175. {
  2176. _saved_error = kWSAenoprotoopt;
  2177. return kWaitStatusFailure;
  2178. }
  2179. struct ip_mreqn mreq = {{0}};
  2180. mreq.imr_multiaddr.s_addr = group_address;
  2181. mreq.imr_address.s_addr = local_address;
  2182. return SetSocketOptionInternal(system_level, system_name, &mreq, sizeof(mreq));
  2183. }
  2184. #if IL2CPP_TARGET_DARWIN || IL2CPP_TARGET_LINUX
  2185. #include <sys/types.h>
  2186. #include <ifaddrs.h>
  2187. #include <sys/socket.h>
  2188. #include <net/if.h>
  2189. static int get_local_interface_id(int family)
  2190. {
  2191. struct ifaddrs *ifap = NULL, *ptr;
  2192. int idx = 0;
  2193. if (getifaddrs(&ifap))
  2194. return 0;
  2195. for (ptr = ifap; ptr; ptr = ptr->ifa_next)
  2196. {
  2197. if (!ptr->ifa_addr || !ptr->ifa_name)
  2198. continue;
  2199. if (ptr->ifa_addr->sa_family != family)
  2200. continue;
  2201. if ((ptr->ifa_flags & IFF_LOOPBACK) != 0)
  2202. continue;
  2203. if ((ptr->ifa_flags & IFF_MULTICAST) == 0)
  2204. continue;
  2205. idx = if_nametoindex(ptr->ifa_name);
  2206. break;
  2207. }
  2208. freeifaddrs(ifap);
  2209. return idx;
  2210. }
  2211. #endif // IL2CPP_TARGET_DARWIN
  2212. #if IL2CPP_SUPPORT_IPV6
  2213. WaitStatus SocketImpl::SetSocketOptionMembership(SocketOptionLevel level, SocketOptionName name, IPv6Address ipv6, uint64_t interfaceOffset)
  2214. {
  2215. int32_t system_level = 0;
  2216. int32_t system_name = 0;
  2217. const int32_t o_res = level_and_name_to_system(level, name, &system_level, &system_name);
  2218. if (o_res == SKIP_OPTION)
  2219. {
  2220. return kWaitStatusSuccess;
  2221. }
  2222. if (o_res == INVALID_OPTION_NAME)
  2223. {
  2224. _saved_error = kWSAenoprotoopt;
  2225. return kWaitStatusFailure;
  2226. }
  2227. struct ipv6_mreq mreq6 = {{0}};
  2228. struct in6_addr in6addr;
  2229. for (int i = 0; i < 16; ++i)
  2230. in6addr.s6_addr[i] = ipv6.addr[i];
  2231. mreq6.ipv6mr_multiaddr = in6addr;
  2232. #if IL2CPP_TARGET_DARWIN || IL2CPP_TARGET_LINUX
  2233. if (interfaceOffset == 0)
  2234. interfaceOffset = get_local_interface_id(AF_INET6);
  2235. #endif
  2236. mreq6.ipv6mr_interface = interfaceOffset;
  2237. return SetSocketOptionInternal(system_level, system_name, &mreq6, sizeof(mreq6));
  2238. }
  2239. #endif
  2240. WaitStatus SocketImpl::SetSocketOptionInternal(int32_t level, int32_t name, const void *value, int32_t len)
  2241. {
  2242. const void *real_val = value;
  2243. struct timeval tv;
  2244. if (level == SOL_SOCKET && (name == SO_RCVTIMEO || name == SO_SNDTIMEO))
  2245. {
  2246. const int32_t ms = *((int32_t*)value);
  2247. tv.tv_sec = ms / 1000;
  2248. tv.tv_usec = (ms % 1000) * 1000;
  2249. real_val = &tv;
  2250. len = sizeof(tv);
  2251. }
  2252. const int32_t ret = setsockopt(_fd, level, name, real_val, (socklen_t)len);
  2253. if (ret == -1)
  2254. {
  2255. StoreLastError();
  2256. return kWaitStatusFailure;
  2257. }
  2258. #if defined(SO_REUSEPORT)
  2259. // BSD's and MacOS X multicast sockets also need SO_REUSEPORT when SO_REUSEADDR is requested.
  2260. if (level == SOL_SOCKET && name == SO_REUSEADDR)
  2261. {
  2262. int32_t type;
  2263. socklen_t type_len = sizeof(type);
  2264. if (!getsockopt(_fd, level, SO_TYPE, &type, &type_len))
  2265. {
  2266. if (type == SOCK_DGRAM)
  2267. setsockopt(_fd, level, SO_REUSEPORT, real_val, len);
  2268. }
  2269. }
  2270. #endif
  2271. return kWaitStatusSuccess;
  2272. }
  2273. #if IL2CPP_SUPPORT_IPV6_SUPPORT_QUERY
  2274. bool SocketImpl::IsIPv6Supported()
  2275. {
  2276. ifaddrs* interfaces;
  2277. if (getifaddrs(&interfaces))
  2278. return false;
  2279. bool ipv6IsSupported = false;
  2280. for (ifaddrs* iface = interfaces; iface != NULL; iface = iface->ifa_next)
  2281. {
  2282. if (iface->ifa_addr && iface->ifa_addr->sa_family == AF_INET6)
  2283. {
  2284. ipv6IsSupported = true;
  2285. break;
  2286. }
  2287. }
  2288. freeifaddrs(interfaces);
  2289. return ipv6IsSupported;
  2290. }
  2291. #endif
  2292. WaitStatus SocketImpl::SendFile(const char *filename, TransmitFileBuffers *buffers, TransmitFileOptions options)
  2293. {
  2294. #if IL2CPP_SUPPORT_SEND_FILE
  2295. int32_t file = open(filename, O_RDONLY);
  2296. if (file == -1)
  2297. {
  2298. StoreLastError();
  2299. return kWaitStatusFailure;
  2300. }
  2301. int32_t ret;
  2302. // Write the header
  2303. if (buffers != NULL && buffers->head != NULL && buffers->head_length > 0)
  2304. {
  2305. do
  2306. {
  2307. ret = (int32_t)send(_fd, (void*)buffers->head, buffers->head_length, 0);
  2308. }
  2309. while (ret == -1 && errno == EINTR);
  2310. if (ret == -1)
  2311. {
  2312. StoreLastError();
  2313. SOCK_CLOSE(file);
  2314. return kWaitStatusFailure;
  2315. }
  2316. }
  2317. struct stat statbuf;
  2318. ret = fstat(file, &statbuf);
  2319. if (ret == -1)
  2320. {
  2321. StoreLastError();
  2322. return kWaitStatusFailure;
  2323. }
  2324. do
  2325. {
  2326. #if IL2CPP_TARGET_DARWIN
  2327. ret = sendfile(file, _fd, 0, &statbuf.st_size, NULL, 0);
  2328. #else
  2329. ret = sendfile(_fd, file, NULL, statbuf.st_size);
  2330. #endif
  2331. }
  2332. while (ret != -1 && (errno == EINTR || errno == EAGAIN));
  2333. if (ret == -1)
  2334. {
  2335. StoreLastError();
  2336. SOCK_CLOSE(file);
  2337. return kWaitStatusFailure;
  2338. }
  2339. // Write the tail
  2340. if (buffers != NULL && buffers->tail != NULL && buffers->tail_length > 0)
  2341. {
  2342. do
  2343. {
  2344. ret = (int32_t)send(_fd, (void*)buffers->tail, buffers->tail_length, 0);
  2345. }
  2346. while (ret == -1 && errno == EINTR);
  2347. if (ret == -1)
  2348. {
  2349. StoreLastError();
  2350. SOCK_CLOSE(file);
  2351. return kWaitStatusFailure;
  2352. }
  2353. }
  2354. if (SOCK_CLOSE(file) == -1)
  2355. {
  2356. StoreLastError();
  2357. return kWaitStatusFailure;
  2358. }
  2359. return kWaitStatusSuccess;
  2360. #else
  2361. return kWaitStatusFailure;
  2362. #endif
  2363. }
  2364. }
  2365. }
  2366. #endif