netdb.cpp 23 KB

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