netdb.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/String.h>
  10. #include <Kernel/Net/IPv4.h>
  11. #include <arpa/inet.h>
  12. #include <errno.h>
  13. #include <netdb.h>
  14. #include <netinet/in.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. extern "C" {
  19. int h_errno;
  20. static hostent __gethostbyname_buffer;
  21. static in_addr_t __gethostbyname_address;
  22. static in_addr_t* __gethostbyname_address_list_buffer[2];
  23. static hostent __gethostbyaddr_buffer;
  24. static in_addr_t* __gethostbyaddr_address_list_buffer[2];
  25. // IPCCompiler depends on LibC. Because of this, it cannot be compiled
  26. // before LibC is. However, the lookup magic can only be obtained from the
  27. // endpoint itself if IPCCompiler has compiled the IPC file, so this creates
  28. // a chicken-and-egg situation. Because of this, the LookupServer endpoint magic
  29. // is hardcoded here.
  30. // Keep the name synchronized with LookupServer/LookupServer.ipc.
  31. static constexpr u32 lookup_server_endpoint_magic = "LookupServer"sv.hash();
  32. // Get service entry buffers and file information for the getservent() family of functions.
  33. static FILE* services_file = nullptr;
  34. static const char* services_path = "/etc/services";
  35. static bool fill_getserv_buffers(const char* line, ssize_t read);
  36. static servent __getserv_buffer;
  37. static String __getserv_name_buffer;
  38. static String __getserv_protocol_buffer;
  39. static int __getserv_port_buffer;
  40. static Vector<ByteBuffer> __getserv_alias_list_buffer;
  41. static Vector<char*> __getserv_alias_list;
  42. static bool keep_service_file_open = false;
  43. static ssize_t service_file_offset = 0;
  44. // Get protocol entry buffers and file information for the getprotent() family of functions.
  45. static FILE* protocols_file = nullptr;
  46. static const char* protocols_path = "/etc/protocols";
  47. static bool fill_getproto_buffers(const char* line, ssize_t read);
  48. static protoent __getproto_buffer;
  49. static String __getproto_name_buffer;
  50. static Vector<ByteBuffer> __getproto_alias_list_buffer;
  51. static Vector<char*> __getproto_alias_list;
  52. static int __getproto_protocol_buffer;
  53. static bool keep_protocols_file_open = false;
  54. static ssize_t protocol_file_offset = 0;
  55. static int connect_to_lookup_server()
  56. {
  57. int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
  58. if (fd < 0) {
  59. perror("socket");
  60. return -1;
  61. }
  62. sockaddr_un address {
  63. AF_LOCAL,
  64. "/tmp/portal/lookup"
  65. };
  66. if (connect(fd, (const sockaddr*)&address, sizeof(address)) < 0) {
  67. perror("connect_to_lookup_server");
  68. close(fd);
  69. return -1;
  70. }
  71. return fd;
  72. }
  73. static String gethostbyname_name_buffer;
  74. hostent* gethostbyname(const char* name)
  75. {
  76. h_errno = 0;
  77. auto ipv4_address = IPv4Address::from_string(name);
  78. if (ipv4_address.has_value()) {
  79. gethostbyname_name_buffer = ipv4_address.value().to_string();
  80. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  81. __gethostbyname_buffer.h_aliases = nullptr;
  82. __gethostbyname_buffer.h_addrtype = AF_INET;
  83. new (&__gethostbyname_address) IPv4Address(ipv4_address.value());
  84. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  85. __gethostbyname_address_list_buffer[1] = nullptr;
  86. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  87. __gethostbyname_buffer.h_length = 4;
  88. return &__gethostbyname_buffer;
  89. }
  90. int fd = connect_to_lookup_server();
  91. if (fd < 0) {
  92. h_errno = TRY_AGAIN;
  93. return nullptr;
  94. }
  95. auto close_fd_on_exit = ScopeGuard([fd] {
  96. close(fd);
  97. });
  98. size_t unsigned_name_length = strlen(name);
  99. VERIFY(unsigned_name_length <= NumericLimits<i32>::max());
  100. i32 name_length = static_cast<i32>(unsigned_name_length);
  101. struct [[gnu::packed]] {
  102. u32 message_size;
  103. u32 endpoint_magic;
  104. i32 message_id;
  105. i32 name_length;
  106. } request_header = {
  107. (u32)(sizeof(request_header) - sizeof(request_header.message_size) + name_length),
  108. lookup_server_endpoint_magic,
  109. 1,
  110. name_length,
  111. };
  112. if (auto nsent = write(fd, &request_header, sizeof(request_header)); nsent < 0) {
  113. h_errno = TRY_AGAIN;
  114. return nullptr;
  115. } else if (nsent != sizeof(request_header)) {
  116. h_errno = NO_RECOVERY;
  117. return nullptr;
  118. }
  119. if (auto nsent = write(fd, name, name_length); nsent < 0) {
  120. h_errno = TRY_AGAIN;
  121. return nullptr;
  122. } else if (nsent != name_length) {
  123. h_errno = NO_RECOVERY;
  124. return nullptr;
  125. }
  126. struct [[gnu::packed]] {
  127. u32 message_size;
  128. u32 endpoint_magic;
  129. i32 message_id;
  130. i32 code;
  131. u64 addresses_count;
  132. } response_header;
  133. if (auto nreceived = read(fd, &response_header, sizeof(response_header)); nreceived < 0) {
  134. h_errno = TRY_AGAIN;
  135. return nullptr;
  136. } else if (nreceived != sizeof(response_header)) {
  137. h_errno = NO_RECOVERY;
  138. return nullptr;
  139. }
  140. if (response_header.endpoint_magic != lookup_server_endpoint_magic || response_header.message_id != 2) {
  141. h_errno = NO_RECOVERY;
  142. return nullptr;
  143. }
  144. if (response_header.code != 0) {
  145. h_errno = NO_RECOVERY;
  146. return nullptr;
  147. }
  148. if (response_header.addresses_count == 0) {
  149. h_errno = HOST_NOT_FOUND;
  150. return nullptr;
  151. }
  152. i32 response_length;
  153. if (auto nreceived = read(fd, &response_length, sizeof(response_length)); nreceived < 0) {
  154. h_errno = TRY_AGAIN;
  155. return nullptr;
  156. } else if (nreceived != sizeof(response_length)
  157. || response_length != sizeof(__gethostbyname_address)) {
  158. h_errno = NO_RECOVERY;
  159. return nullptr;
  160. }
  161. if (auto nreceived = read(fd, &__gethostbyname_address, response_length); nreceived < 0) {
  162. h_errno = TRY_AGAIN;
  163. return nullptr;
  164. } else if (nreceived != response_length) {
  165. h_errno = NO_RECOVERY;
  166. return nullptr;
  167. }
  168. gethostbyname_name_buffer = name;
  169. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  170. __gethostbyname_buffer.h_aliases = nullptr;
  171. __gethostbyname_buffer.h_addrtype = AF_INET;
  172. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  173. __gethostbyname_address_list_buffer[1] = nullptr;
  174. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  175. __gethostbyname_buffer.h_length = 4;
  176. return &__gethostbyname_buffer;
  177. }
  178. static String gethostbyaddr_name_buffer;
  179. hostent* gethostbyaddr(const void* addr, socklen_t addr_size, int type)
  180. {
  181. h_errno = 0;
  182. if (type != AF_INET) {
  183. errno = EAFNOSUPPORT;
  184. return nullptr;
  185. }
  186. if (addr_size < sizeof(in_addr)) {
  187. errno = EINVAL;
  188. return nullptr;
  189. }
  190. int fd = connect_to_lookup_server();
  191. if (fd < 0) {
  192. h_errno = TRY_AGAIN;
  193. return nullptr;
  194. }
  195. auto close_fd_on_exit = ScopeGuard([fd] {
  196. close(fd);
  197. });
  198. const in_addr_t& in_addr = ((const struct in_addr*)addr)->s_addr;
  199. struct [[gnu::packed]] {
  200. u32 message_size;
  201. u32 endpoint_magic;
  202. i32 message_id;
  203. i32 address_length;
  204. } request_header = {
  205. sizeof(request_header) - sizeof(request_header.message_size) + sizeof(in_addr),
  206. lookup_server_endpoint_magic,
  207. 3,
  208. sizeof(in_addr),
  209. };
  210. if (auto nsent = write(fd, &request_header, sizeof(request_header)); nsent < 0) {
  211. h_errno = TRY_AGAIN;
  212. return nullptr;
  213. } else if (nsent != sizeof(request_header)) {
  214. h_errno = NO_RECOVERY;
  215. return nullptr;
  216. }
  217. if (auto nsent = write(fd, &in_addr, sizeof(in_addr)); nsent < 0) {
  218. h_errno = TRY_AGAIN;
  219. return nullptr;
  220. } else if (nsent != sizeof(in_addr)) {
  221. h_errno = TRY_AGAIN;
  222. return nullptr;
  223. }
  224. struct [[gnu::packed]] {
  225. u32 message_size;
  226. u32 endpoint_magic;
  227. i32 message_id;
  228. i32 code;
  229. i32 name_length;
  230. } response_header;
  231. if (auto nreceived = read(fd, &response_header, sizeof(response_header)); nreceived < 0) {
  232. h_errno = TRY_AGAIN;
  233. return nullptr;
  234. } else if (nreceived != sizeof(response_header)) {
  235. h_errno = NO_RECOVERY;
  236. return nullptr;
  237. }
  238. if (response_header.endpoint_magic != lookup_server_endpoint_magic
  239. || response_header.message_id != 4
  240. || response_header.code != 0) {
  241. h_errno = NO_RECOVERY;
  242. return nullptr;
  243. }
  244. char* buffer;
  245. auto string_impl = StringImpl::create_uninitialized(response_header.name_length, buffer);
  246. if (auto nreceived = read(fd, buffer, response_header.name_length); nreceived < 0) {
  247. h_errno = TRY_AGAIN;
  248. return nullptr;
  249. } else if (nreceived != response_header.name_length) {
  250. h_errno = NO_RECOVERY;
  251. return nullptr;
  252. }
  253. gethostbyaddr_name_buffer = move(string_impl);
  254. __gethostbyaddr_buffer.h_name = buffer;
  255. __gethostbyaddr_buffer.h_aliases = nullptr;
  256. __gethostbyaddr_buffer.h_addrtype = AF_INET;
  257. // FIXME: Should we populate the hostent's address list here with a sockaddr_in for the provided host?
  258. __gethostbyaddr_address_list_buffer[0] = nullptr;
  259. __gethostbyaddr_buffer.h_addr_list = (char**)__gethostbyaddr_address_list_buffer;
  260. __gethostbyaddr_buffer.h_length = 4;
  261. return &__gethostbyaddr_buffer;
  262. }
  263. struct servent* getservent()
  264. {
  265. // If the services file is not open, attempt to open it and return null if it fails.
  266. if (!services_file) {
  267. services_file = fopen(services_path, "r");
  268. if (!services_file) {
  269. perror("error opening services file");
  270. return nullptr;
  271. }
  272. }
  273. if (fseek(services_file, service_file_offset, SEEK_SET) != 0) {
  274. perror("error seeking file");
  275. fclose(services_file);
  276. return nullptr;
  277. }
  278. char* line = nullptr;
  279. size_t len = 0;
  280. ssize_t read;
  281. auto free_line_on_exit = ScopeGuard([line] {
  282. if (line) {
  283. free(line);
  284. }
  285. });
  286. // Read lines from services file until an actual service name is found.
  287. do {
  288. read = getline(&line, &len, services_file);
  289. service_file_offset += read;
  290. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  291. break;
  292. }
  293. } while (read != -1);
  294. if (read == -1) {
  295. fclose(services_file);
  296. services_file = nullptr;
  297. service_file_offset = 0;
  298. return nullptr;
  299. }
  300. servent* service_entry = nullptr;
  301. if (!fill_getserv_buffers(line, read))
  302. return nullptr;
  303. __getserv_buffer.s_name = const_cast<char*>(__getserv_name_buffer.characters());
  304. __getserv_buffer.s_port = htons(__getserv_port_buffer);
  305. __getserv_buffer.s_proto = const_cast<char*>(__getserv_protocol_buffer.characters());
  306. __getserv_alias_list.clear_with_capacity();
  307. __getserv_alias_list.ensure_capacity(__getserv_alias_list_buffer.size() + 1);
  308. for (auto& alias : __getserv_alias_list_buffer)
  309. __getserv_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  310. __getserv_alias_list.unchecked_append(nullptr);
  311. __getserv_buffer.s_aliases = __getserv_alias_list.data();
  312. service_entry = &__getserv_buffer;
  313. if (!keep_service_file_open) {
  314. endservent();
  315. }
  316. return service_entry;
  317. }
  318. struct servent* getservbyname(const char* name, const char* protocol)
  319. {
  320. if (name == nullptr)
  321. return nullptr;
  322. bool previous_file_open_setting = keep_service_file_open;
  323. setservent(1);
  324. struct servent* current_service = nullptr;
  325. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  326. if (!previous_file_open_setting) {
  327. endservent();
  328. }
  329. });
  330. while (true) {
  331. current_service = getservent();
  332. if (current_service == nullptr)
  333. break;
  334. else if (!protocol && strcmp(current_service->s_name, name) == 0)
  335. break;
  336. else if (strcmp(current_service->s_name, name) == 0 && strcmp(current_service->s_proto, protocol) == 0)
  337. break;
  338. }
  339. return current_service;
  340. }
  341. struct servent* getservbyport(int port, const char* protocol)
  342. {
  343. bool previous_file_open_setting = keep_service_file_open;
  344. setservent(1);
  345. struct servent* current_service = nullptr;
  346. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  347. if (!previous_file_open_setting) {
  348. endservent();
  349. }
  350. });
  351. while (true) {
  352. current_service = getservent();
  353. if (current_service == nullptr)
  354. break;
  355. else if (!protocol && current_service->s_port == port)
  356. break;
  357. else if (current_service->s_port == port && (strcmp(current_service->s_proto, protocol) == 0))
  358. break;
  359. }
  360. return current_service;
  361. }
  362. void setservent(int stay_open)
  363. {
  364. if (!services_file) {
  365. services_file = fopen(services_path, "r");
  366. if (!services_file) {
  367. perror("error opening services file");
  368. return;
  369. }
  370. }
  371. rewind(services_file);
  372. keep_service_file_open = stay_open;
  373. service_file_offset = 0;
  374. }
  375. void endservent()
  376. {
  377. if (!services_file) {
  378. return;
  379. }
  380. fclose(services_file);
  381. services_file = nullptr;
  382. }
  383. // Fill the service entry buffer with the information contained
  384. // in the currently read line, returns true if successful,
  385. // false if failure occurs.
  386. static bool fill_getserv_buffers(const char* line, ssize_t read)
  387. {
  388. // Splitting the line by tab delimiter and filling the servent buffers name, port, and protocol members.
  389. auto split_line = StringView(line, read).replace(" ", "\t", true).split('\t');
  390. // This indicates an incorrect file format.
  391. // Services file entries should always at least contain
  392. // name and port/protocol, separated by tabs.
  393. if (split_line.size() < 2) {
  394. warnln("getservent(): malformed services file");
  395. return false;
  396. }
  397. __getserv_name_buffer = split_line[0];
  398. auto port_protocol_split = String(split_line[1]).split('/');
  399. if (port_protocol_split.size() < 2) {
  400. warnln("getservent(): malformed services file");
  401. return false;
  402. }
  403. auto number = port_protocol_split[0].to_int();
  404. if (!number.has_value())
  405. return false;
  406. __getserv_port_buffer = number.value();
  407. // Remove any annoying whitespace at the end of the protocol.
  408. __getserv_protocol_buffer = port_protocol_split[1].replace(" ", "", true).replace("\t", "", true).replace("\n", "", true);
  409. __getserv_alias_list_buffer.clear();
  410. // If there are aliases for the service, we will fill the alias list buffer.
  411. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  412. for (size_t i = 2; i < split_line.size(); i++) {
  413. if (split_line[i].starts_with('#')) {
  414. break;
  415. }
  416. auto alias = split_line[i].to_byte_buffer();
  417. if (alias.try_append("\0", sizeof(char)).is_error())
  418. return false;
  419. __getserv_alias_list_buffer.append(move(alias));
  420. }
  421. }
  422. return true;
  423. }
  424. struct protoent* getprotoent()
  425. {
  426. // If protocols file isn't open, attempt to open and return null on failure.
  427. if (!protocols_file) {
  428. protocols_file = fopen(protocols_path, "r");
  429. if (!protocols_file) {
  430. perror("error opening protocols file");
  431. return nullptr;
  432. }
  433. }
  434. if (fseek(protocols_file, protocol_file_offset, SEEK_SET) != 0) {
  435. perror("error seeking protocols file");
  436. fclose(protocols_file);
  437. return nullptr;
  438. }
  439. char* line = nullptr;
  440. size_t len = 0;
  441. ssize_t read;
  442. auto free_line_on_exit = ScopeGuard([line] {
  443. if (line) {
  444. free(line);
  445. }
  446. });
  447. do {
  448. read = getline(&line, &len, protocols_file);
  449. protocol_file_offset += read;
  450. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  451. break;
  452. }
  453. } while (read != -1);
  454. if (read == -1) {
  455. fclose(protocols_file);
  456. protocols_file = nullptr;
  457. protocol_file_offset = 0;
  458. return nullptr;
  459. }
  460. struct protoent* protocol_entry = nullptr;
  461. if (!fill_getproto_buffers(line, read))
  462. return nullptr;
  463. __getproto_buffer.p_name = const_cast<char*>(__getproto_name_buffer.characters());
  464. __getproto_buffer.p_proto = __getproto_protocol_buffer;
  465. __getproto_alias_list.clear_with_capacity();
  466. __getproto_alias_list.ensure_capacity(__getproto_alias_list_buffer.size() + 1);
  467. for (auto& alias : __getproto_alias_list_buffer)
  468. __getproto_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  469. __getserv_alias_list.unchecked_append(nullptr);
  470. __getproto_buffer.p_aliases = __getproto_alias_list.data();
  471. protocol_entry = &__getproto_buffer;
  472. if (!keep_protocols_file_open)
  473. endprotoent();
  474. return protocol_entry;
  475. }
  476. struct protoent* getprotobyname(const char* name)
  477. {
  478. bool previous_file_open_setting = keep_protocols_file_open;
  479. setprotoent(1);
  480. struct protoent* current_protocol = nullptr;
  481. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  482. if (!previous_file_open_setting) {
  483. endprotoent();
  484. }
  485. });
  486. while (true) {
  487. current_protocol = getprotoent();
  488. if (current_protocol == nullptr)
  489. break;
  490. else if (strcmp(current_protocol->p_name, name) == 0)
  491. break;
  492. }
  493. return current_protocol;
  494. }
  495. struct protoent* getprotobynumber(int proto)
  496. {
  497. bool previous_file_open_setting = keep_protocols_file_open;
  498. setprotoent(1);
  499. struct protoent* current_protocol = nullptr;
  500. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  501. if (!previous_file_open_setting) {
  502. endprotoent();
  503. }
  504. });
  505. while (true) {
  506. current_protocol = getprotoent();
  507. if (current_protocol == nullptr)
  508. break;
  509. else if (current_protocol->p_proto == proto)
  510. break;
  511. }
  512. return current_protocol;
  513. }
  514. void setprotoent(int stay_open)
  515. {
  516. if (!protocols_file) {
  517. protocols_file = fopen(protocols_path, "r");
  518. if (!protocols_file) {
  519. perror("setprotoent(): error opening protocols file");
  520. return;
  521. }
  522. }
  523. rewind(protocols_file);
  524. keep_protocols_file_open = stay_open;
  525. protocol_file_offset = 0;
  526. }
  527. void endprotoent()
  528. {
  529. if (!protocols_file) {
  530. return;
  531. }
  532. fclose(protocols_file);
  533. protocols_file = nullptr;
  534. }
  535. static bool fill_getproto_buffers(const char* line, ssize_t read)
  536. {
  537. String string_line = String(line, read);
  538. auto split_line = string_line.replace(" ", "\t", true).split('\t');
  539. // This indicates an incorrect file format. Protocols file entries should
  540. // always have at least a name and a protocol.
  541. if (split_line.size() < 2) {
  542. warnln("getprotoent(): malformed protocols file");
  543. return false;
  544. }
  545. __getproto_name_buffer = split_line[0];
  546. auto number = split_line[1].to_int();
  547. if (!number.has_value())
  548. return false;
  549. __getproto_protocol_buffer = number.value();
  550. __getproto_alias_list_buffer.clear();
  551. // If there are aliases for the protocol, we will fill the alias list buffer.
  552. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  553. for (size_t i = 2; i < split_line.size(); i++) {
  554. if (split_line[i].starts_with('#'))
  555. break;
  556. auto alias = split_line[i].to_byte_buffer();
  557. if (alias.try_append("\0", sizeof(char)).is_error())
  558. return false;
  559. __getproto_alias_list_buffer.append(move(alias));
  560. }
  561. }
  562. return true;
  563. }
  564. int getaddrinfo(const char* __restrict node, const char* __restrict service, const struct addrinfo* __restrict hints, struct addrinfo** __restrict res)
  565. {
  566. *res = nullptr;
  567. if (hints && hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC)
  568. return EAI_FAMILY;
  569. if (!node) {
  570. if (hints && hints->ai_flags & AI_PASSIVE)
  571. node = "0.0.0.0";
  572. else
  573. node = "127.0.0.1";
  574. }
  575. auto host_ent = gethostbyname(node);
  576. if (!host_ent)
  577. return EAI_FAIL;
  578. const char* proto = nullptr;
  579. if (hints && hints->ai_socktype) {
  580. switch (hints->ai_socktype) {
  581. case SOCK_STREAM:
  582. proto = "tcp";
  583. break;
  584. case SOCK_DGRAM:
  585. proto = "udp";
  586. break;
  587. default:
  588. return EAI_SOCKTYPE;
  589. }
  590. }
  591. long port;
  592. int socktype;
  593. servent* svc_ent = nullptr;
  594. if (!hints || (hints->ai_flags & AI_NUMERICSERV) == 0) {
  595. svc_ent = getservbyname(service, proto);
  596. }
  597. if (!svc_ent) {
  598. if (service) {
  599. char* end;
  600. port = htons(strtol(service, &end, 10));
  601. if (*end)
  602. return EAI_FAIL;
  603. } else {
  604. port = htons(0);
  605. }
  606. if (hints && hints->ai_socktype != 0)
  607. socktype = hints->ai_socktype;
  608. else
  609. socktype = SOCK_STREAM;
  610. } else {
  611. port = svc_ent->s_port;
  612. socktype = strcmp(svc_ent->s_proto, "tcp") ? SOCK_STREAM : SOCK_DGRAM;
  613. }
  614. addrinfo* first_info = nullptr;
  615. addrinfo* prev_info = nullptr;
  616. for (int host_index = 0; host_ent->h_addr_list[host_index]; host_index++) {
  617. sockaddr_in* sin = new sockaddr_in;
  618. sin->sin_family = AF_INET;
  619. sin->sin_port = port;
  620. memcpy(&sin->sin_addr.s_addr, host_ent->h_addr_list[host_index], host_ent->h_length);
  621. addrinfo* info = new addrinfo;
  622. info->ai_flags = 0;
  623. info->ai_family = AF_INET;
  624. info->ai_socktype = socktype;
  625. info->ai_protocol = PF_INET;
  626. info->ai_addrlen = sizeof(*sin);
  627. info->ai_addr = reinterpret_cast<sockaddr*>(sin);
  628. if (hints && hints->ai_flags & AI_CANONNAME)
  629. info->ai_canonname = strdup(host_ent->h_name);
  630. else
  631. info->ai_canonname = nullptr;
  632. info->ai_next = nullptr;
  633. if (!first_info)
  634. first_info = info;
  635. if (prev_info)
  636. prev_info->ai_next = info;
  637. prev_info = info;
  638. }
  639. if (first_info) {
  640. *res = first_info;
  641. return 0;
  642. } else
  643. return EAI_NONAME;
  644. }
  645. void freeaddrinfo(struct addrinfo* res)
  646. {
  647. if (res) {
  648. delete reinterpret_cast<sockaddr_in*>(res->ai_addr);
  649. free(res->ai_canonname);
  650. freeaddrinfo(res->ai_next);
  651. delete res;
  652. }
  653. }
  654. const char* gai_strerror(int errcode)
  655. {
  656. switch (errcode) {
  657. case EAI_ADDRFAMILY:
  658. return "no address for this address family available";
  659. case EAI_AGAIN:
  660. return "name server returned temporary failure";
  661. case EAI_BADFLAGS:
  662. return "invalid flags";
  663. case EAI_FAIL:
  664. return "name server returned permanent failure";
  665. case EAI_FAMILY:
  666. return "unsupported address family";
  667. case EAI_MEMORY:
  668. return "out of memory";
  669. case EAI_NODATA:
  670. return "no address available";
  671. case EAI_NONAME:
  672. return "node or service is not known";
  673. case EAI_SERVICE:
  674. return "service not available";
  675. case EAI_SOCKTYPE:
  676. return "unsupported socket type";
  677. case EAI_SYSTEM:
  678. return "system error";
  679. case EAI_OVERFLOW:
  680. return "buffer too small";
  681. default:
  682. return "invalid error code";
  683. }
  684. }
  685. int getnameinfo(const struct sockaddr* __restrict addr, socklen_t addrlen, char* __restrict host, socklen_t hostlen, char* __restrict serv, socklen_t servlen, int flags)
  686. {
  687. if (addr->sa_family != AF_INET || addrlen < sizeof(sockaddr_in))
  688. return EAI_FAMILY;
  689. const sockaddr_in* sin = reinterpret_cast<const sockaddr_in*>(addr);
  690. if (host && hostlen > 0) {
  691. if (flags != 0)
  692. dbgln("getnameinfo flags are not implemented: {:#x}", flags);
  693. if (!inet_ntop(AF_INET, &sin->sin_addr, host, hostlen)) {
  694. if (errno == ENOSPC)
  695. return EAI_OVERFLOW;
  696. else
  697. return EAI_SYSTEM;
  698. }
  699. }
  700. if (serv && servlen > 0) {
  701. if (snprintf(serv, servlen, "%d", (int)ntohs(sin->sin_port)) > (int)servlen)
  702. return EAI_OVERFLOW;
  703. }
  704. return 0;
  705. }
  706. }