netdb.cpp 23 KB

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