netdb.cpp 25 KB

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