netdb.cpp 25 KB

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