netdb.cpp 25 KB

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