netdb.cpp 23 KB

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