netdb.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/ByteBuffer.h>
  28. #include <AK/ScopeGuard.h>
  29. #include <AK/String.h>
  30. #include <Kernel/Net/IPv4.h>
  31. #include <arpa/inet.h>
  32. #include <netdb.h>
  33. #include <netinet/in.h>
  34. #include <stdio.h>
  35. #include <string.h>
  36. #include <unistd.h>
  37. extern "C" {
  38. int h_errno;
  39. static hostent __gethostbyname_buffer;
  40. static in_addr_t __gethostbyname_address;
  41. static in_addr_t* __gethostbyname_address_list_buffer[2];
  42. static hostent __gethostbyaddr_buffer;
  43. static in_addr_t* __gethostbyaddr_address_list_buffer[2];
  44. static constexpr i32 lookup_server_endpoint_magic = 9001;
  45. // Get service entry buffers and file information for the getservent() family of functions.
  46. static FILE* services_file = nullptr;
  47. static const char* services_path = "/etc/services";
  48. static bool fill_getserv_buffers(const char* line, ssize_t read);
  49. static servent __getserv_buffer;
  50. static String __getserv_name_buffer;
  51. static String __getserv_protocol_buffer;
  52. static int __getserv_port_buffer;
  53. static Vector<ByteBuffer> __getserv_alias_list_buffer;
  54. static Vector<char*> __getserv_alias_list;
  55. static bool keep_service_file_open = false;
  56. static ssize_t service_file_offset = 0;
  57. // Get protocol entry buffers and file information for the getprotent() family of functions.
  58. static FILE* protocols_file = nullptr;
  59. static const char* protocols_path = "/etc/protocols";
  60. static bool fill_getproto_buffers(const char* line, ssize_t read);
  61. static protoent __getproto_buffer;
  62. static String __getproto_name_buffer;
  63. static Vector<ByteBuffer> __getproto_alias_list_buffer;
  64. static Vector<char*> __getproto_alias_list;
  65. static int __getproto_protocol_buffer;
  66. static bool keep_protocols_file_open = false;
  67. static ssize_t protocol_file_offset = 0;
  68. static int connect_to_lookup_server()
  69. {
  70. int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
  71. if (fd < 0) {
  72. perror("socket");
  73. return -1;
  74. }
  75. sockaddr_un address {
  76. AF_LOCAL,
  77. "/tmp/portal/lookup"
  78. };
  79. if (connect(fd, (const sockaddr*)&address, sizeof(address)) < 0) {
  80. perror("connect_to_lookup_server");
  81. close(fd);
  82. return -1;
  83. }
  84. return fd;
  85. }
  86. static String gethostbyname_name_buffer;
  87. hostent* gethostbyname(const char* name)
  88. {
  89. auto ipv4_address = IPv4Address::from_string(name);
  90. if (ipv4_address.has_value()) {
  91. gethostbyname_name_buffer = ipv4_address.value().to_string();
  92. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  93. __gethostbyname_buffer.h_aliases = nullptr;
  94. __gethostbyname_buffer.h_addrtype = AF_INET;
  95. new (&__gethostbyname_address) IPv4Address(ipv4_address.value());
  96. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  97. __gethostbyname_address_list_buffer[1] = nullptr;
  98. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  99. __gethostbyname_buffer.h_length = 4;
  100. return &__gethostbyname_buffer;
  101. }
  102. int fd = connect_to_lookup_server();
  103. if (fd < 0)
  104. return nullptr;
  105. auto close_fd_on_exit = ScopeGuard([fd] {
  106. close(fd);
  107. });
  108. size_t name_length = strlen(name);
  109. struct [[gnu::packed]] {
  110. u32 message_size;
  111. i32 endpoint_magic;
  112. i32 message_id;
  113. i32 name_length;
  114. } request_header = {
  115. sizeof(request_header) - sizeof(request_header.message_size) + name_length,
  116. lookup_server_endpoint_magic,
  117. 1,
  118. (i32)name_length,
  119. };
  120. int nsent = write(fd, &request_header, sizeof(request_header));
  121. if (nsent < 0) {
  122. perror("write");
  123. return nullptr;
  124. }
  125. ASSERT((size_t)nsent == sizeof(request_header));
  126. nsent = write(fd, name, name_length);
  127. if (nsent < 0) {
  128. perror("write");
  129. return nullptr;
  130. }
  131. ASSERT((size_t)nsent == name_length);
  132. struct [[gnu::packed]] {
  133. u32 message_size;
  134. i32 endpoint_magic;
  135. i32 message_id;
  136. i32 code;
  137. u64 addresses_count;
  138. } response_header;
  139. int nrecv = read(fd, &response_header, sizeof(response_header));
  140. if (nrecv < 0) {
  141. perror("recv");
  142. return nullptr;
  143. }
  144. ASSERT((size_t)nrecv == sizeof(response_header));
  145. if (response_header.endpoint_magic != lookup_server_endpoint_magic || response_header.message_id != 2) {
  146. dbgln("Received an unexpected message");
  147. return nullptr;
  148. }
  149. if (response_header.code != 0) {
  150. // TODO: return a specific error.
  151. return nullptr;
  152. }
  153. ASSERT(response_header.addresses_count > 0);
  154. i32 response_length;
  155. nrecv = read(fd, &response_length, sizeof(response_length));
  156. if (nrecv < 0) {
  157. perror("recv");
  158. return nullptr;
  159. }
  160. ASSERT((size_t)nrecv == sizeof(response_length));
  161. ASSERT(response_length == sizeof(__gethostbyname_address));
  162. nrecv = read(fd, &__gethostbyname_address, response_length);
  163. if (nrecv < 0) {
  164. perror("recv");
  165. return nullptr;
  166. }
  167. ASSERT(nrecv == response_length);
  168. gethostbyname_name_buffer = name;
  169. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  170. __gethostbyname_buffer.h_aliases = nullptr;
  171. __gethostbyname_buffer.h_addrtype = AF_INET;
  172. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  173. __gethostbyname_address_list_buffer[1] = nullptr;
  174. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  175. __gethostbyname_buffer.h_length = 4;
  176. return &__gethostbyname_buffer;
  177. }
  178. static String gethostbyaddr_name_buffer;
  179. hostent* gethostbyaddr(const void* addr, socklen_t addr_size, int type)
  180. {
  181. if (type != AF_INET) {
  182. errno = EAFNOSUPPORT;
  183. return nullptr;
  184. }
  185. if (addr_size < sizeof(in_addr)) {
  186. errno = EINVAL;
  187. return nullptr;
  188. }
  189. int fd = connect_to_lookup_server();
  190. if (fd < 0)
  191. return nullptr;
  192. auto close_fd_on_exit = ScopeGuard([fd] {
  193. close(fd);
  194. });
  195. const in_addr_t& in_addr = ((const struct in_addr*)addr)->s_addr;
  196. struct [[gnu::packed]] {
  197. u32 message_size;
  198. i32 endpoint_magic;
  199. i32 message_id;
  200. i32 address_length;
  201. } request_header = {
  202. sizeof(request_header) - sizeof(request_header.message_size) + sizeof(in_addr),
  203. lookup_server_endpoint_magic,
  204. 3,
  205. (i32)sizeof(in_addr),
  206. };
  207. int nsent = write(fd, &request_header, sizeof(request_header));
  208. if (nsent < 0) {
  209. perror("write");
  210. return nullptr;
  211. }
  212. ASSERT((size_t)nsent == sizeof(request_header));
  213. nsent = write(fd, &in_addr, sizeof(in_addr));
  214. if (nsent < 0) {
  215. perror("write");
  216. return nullptr;
  217. }
  218. ASSERT((size_t)nsent == sizeof(in_addr));
  219. struct [[gnu::packed]] {
  220. u32 message_size;
  221. i32 endpoint_magic;
  222. i32 message_id;
  223. i32 code;
  224. i32 name_length;
  225. } response_header;
  226. int nrecv = read(fd, &response_header, sizeof(response_header));
  227. if (nrecv < 0) {
  228. perror("recv");
  229. return nullptr;
  230. }
  231. ASSERT((size_t)nrecv == sizeof(response_header));
  232. if (response_header.endpoint_magic != lookup_server_endpoint_magic || response_header.message_id != 4) {
  233. dbgln("Received an unexpected message");
  234. return nullptr;
  235. }
  236. if (response_header.code != 0) {
  237. // TODO: return a specific error.
  238. return nullptr;
  239. }
  240. char* buffer;
  241. auto string_impl = StringImpl::create_uninitialized(response_header.name_length, buffer);
  242. nrecv = read(fd, buffer, response_header.name_length);
  243. if (nrecv < 0) {
  244. perror("recv");
  245. return nullptr;
  246. }
  247. ASSERT(nrecv == response_header.name_length);
  248. gethostbyaddr_name_buffer = move(string_impl);
  249. __gethostbyaddr_buffer.h_name = buffer;
  250. __gethostbyaddr_buffer.h_aliases = nullptr;
  251. __gethostbyaddr_buffer.h_addrtype = AF_INET;
  252. // FIXME: Should we populate the hostent's address list here with a sockaddr_in for the provided host?
  253. __gethostbyaddr_address_list_buffer[0] = nullptr;
  254. __gethostbyaddr_buffer.h_addr_list = (char**)__gethostbyaddr_address_list_buffer;
  255. __gethostbyaddr_buffer.h_length = 4;
  256. return &__gethostbyaddr_buffer;
  257. }
  258. struct servent* getservent()
  259. {
  260. //If the services file is not open, attempt to open it and return null if it fails.
  261. if (!services_file) {
  262. services_file = fopen(services_path, "r");
  263. if (!services_file) {
  264. perror("error opening services file");
  265. return nullptr;
  266. }
  267. }
  268. if (fseek(services_file, service_file_offset, SEEK_SET) != 0) {
  269. perror("error seeking file");
  270. fclose(services_file);
  271. return nullptr;
  272. }
  273. char* line = nullptr;
  274. size_t len = 0;
  275. ssize_t read;
  276. auto free_line_on_exit = ScopeGuard([line] {
  277. if (line) {
  278. free(line);
  279. }
  280. });
  281. // Read lines from services file until an actual service name is found.
  282. do {
  283. read = getline(&line, &len, services_file);
  284. service_file_offset += read;
  285. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  286. break;
  287. }
  288. } while (read != -1);
  289. if (read == -1) {
  290. fclose(services_file);
  291. services_file = nullptr;
  292. service_file_offset = 0;
  293. return nullptr;
  294. }
  295. servent* service_entry = nullptr;
  296. if (!fill_getserv_buffers(line, read))
  297. return nullptr;
  298. __getserv_buffer.s_name = const_cast<char*>(__getserv_name_buffer.characters());
  299. __getserv_buffer.s_port = __getserv_port_buffer;
  300. __getserv_buffer.s_proto = const_cast<char*>(__getserv_protocol_buffer.characters());
  301. __getserv_alias_list.clear_with_capacity();
  302. __getserv_alias_list.ensure_capacity(__getserv_alias_list_buffer.size() + 1);
  303. for (auto& alias : __getserv_alias_list_buffer)
  304. __getserv_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  305. __getserv_alias_list.unchecked_append(nullptr);
  306. __getserv_buffer.s_aliases = __getserv_alias_list.data();
  307. service_entry = &__getserv_buffer;
  308. if (!keep_service_file_open) {
  309. endservent();
  310. }
  311. return service_entry;
  312. }
  313. struct servent* getservbyname(const char* name, const char* protocol)
  314. {
  315. bool previous_file_open_setting = keep_service_file_open;
  316. setservent(1);
  317. struct servent* current_service = nullptr;
  318. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  319. if (!previous_file_open_setting) {
  320. endservent();
  321. }
  322. });
  323. while (true) {
  324. current_service = getservent();
  325. if (current_service == nullptr)
  326. break;
  327. else if (!protocol && strcmp(current_service->s_name, name) == 0)
  328. break;
  329. else if (strcmp(current_service->s_name, name) == 0 && strcmp(current_service->s_proto, protocol) == 0)
  330. break;
  331. }
  332. return current_service;
  333. }
  334. struct servent* getservbyport(int port, const char* protocol)
  335. {
  336. bool previous_file_open_setting = keep_service_file_open;
  337. setservent(1);
  338. struct servent* current_service = nullptr;
  339. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  340. if (!previous_file_open_setting) {
  341. endservent();
  342. }
  343. });
  344. while (true) {
  345. current_service = getservent();
  346. if (current_service == nullptr)
  347. break;
  348. else if (!protocol && current_service->s_port == port)
  349. break;
  350. else if (current_service->s_port == port && (strcmp(current_service->s_proto, protocol) == 0))
  351. break;
  352. }
  353. return current_service;
  354. }
  355. void setservent(int stay_open)
  356. {
  357. if (!services_file) {
  358. services_file = fopen(services_path, "r");
  359. if (!services_file) {
  360. perror("error opening services file");
  361. return;
  362. }
  363. }
  364. rewind(services_file);
  365. keep_service_file_open = stay_open;
  366. service_file_offset = 0;
  367. }
  368. void endservent()
  369. {
  370. if (!services_file) {
  371. return;
  372. }
  373. fclose(services_file);
  374. services_file = nullptr;
  375. }
  376. // Fill the service entry buffer with the information contained
  377. // in the currently read line, returns true if successful,
  378. // false if failure occurs.
  379. static bool fill_getserv_buffers(const char* line, ssize_t read)
  380. {
  381. //Splitting the line by tab delimiter and filling the servent buffers name, port, and protocol members.
  382. String string_line = String(line, read);
  383. string_line.replace(" ", "\t", true);
  384. auto split_line = string_line.split('\t');
  385. // This indicates an incorrect file format.
  386. // Services file entries should always at least contain
  387. // name and port/protocol, separated by tabs.
  388. if (split_line.size() < 2) {
  389. fprintf(stderr, "getservent(): malformed services file\n");
  390. return false;
  391. }
  392. __getserv_name_buffer = split_line[0];
  393. auto port_protocol_split = String(split_line[1]).split('/');
  394. if (port_protocol_split.size() < 2) {
  395. fprintf(stderr, "getservent(): malformed services file\n");
  396. return false;
  397. }
  398. auto number = port_protocol_split[0].to_int();
  399. if (!number.has_value())
  400. return false;
  401. __getserv_port_buffer = number.value();
  402. // Remove any annoying whitespace at the end of the protocol.
  403. port_protocol_split[1].replace(" ", "", true);
  404. port_protocol_split[1].replace("\t", "", true);
  405. port_protocol_split[1].replace("\n", "", true);
  406. __getserv_protocol_buffer = port_protocol_split[1];
  407. __getserv_alias_list_buffer.clear();
  408. // If there are aliases for the service, we will fill the alias list buffer.
  409. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  410. for (size_t i = 2; i < split_line.size(); i++) {
  411. if (split_line[i].starts_with('#')) {
  412. break;
  413. }
  414. auto alias = split_line[i].to_byte_buffer();
  415. alias.append("\0", sizeof(char));
  416. __getserv_alias_list_buffer.append(alias);
  417. }
  418. }
  419. return true;
  420. }
  421. struct protoent* getprotoent()
  422. {
  423. // If protocols file isn't open, attempt to open and return null on failure.
  424. if (!protocols_file) {
  425. protocols_file = fopen(protocols_path, "r");
  426. if (!protocols_file) {
  427. perror("error opening protocols file");
  428. return nullptr;
  429. }
  430. }
  431. if (fseek(protocols_file, protocol_file_offset, SEEK_SET) != 0) {
  432. perror("error seeking protocols file");
  433. fclose(protocols_file);
  434. return nullptr;
  435. }
  436. char* line = nullptr;
  437. size_t len = 0;
  438. ssize_t read;
  439. auto free_line_on_exit = ScopeGuard([line] {
  440. if (line) {
  441. free(line);
  442. }
  443. });
  444. do {
  445. read = getline(&line, &len, protocols_file);
  446. protocol_file_offset += read;
  447. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  448. break;
  449. }
  450. } while (read != -1);
  451. if (read == -1) {
  452. fclose(protocols_file);
  453. protocols_file = nullptr;
  454. protocol_file_offset = 0;
  455. return nullptr;
  456. }
  457. struct protoent* protocol_entry = nullptr;
  458. if (!fill_getproto_buffers(line, read))
  459. return nullptr;
  460. __getproto_buffer.p_name = const_cast<char*>(__getproto_name_buffer.characters());
  461. __getproto_buffer.p_proto = __getproto_protocol_buffer;
  462. __getproto_alias_list.clear_with_capacity();
  463. __getproto_alias_list.ensure_capacity(__getproto_alias_list_buffer.size() + 1);
  464. for (auto& alias : __getproto_alias_list_buffer)
  465. __getproto_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  466. __getserv_alias_list.unchecked_append(nullptr);
  467. __getproto_buffer.p_aliases = __getproto_alias_list.data();
  468. protocol_entry = &__getproto_buffer;
  469. if (!keep_protocols_file_open)
  470. endprotoent();
  471. return protocol_entry;
  472. }
  473. struct protoent* getprotobyname(const char* name)
  474. {
  475. bool previous_file_open_setting = keep_protocols_file_open;
  476. setprotoent(1);
  477. struct protoent* current_protocol = nullptr;
  478. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  479. if (!previous_file_open_setting) {
  480. endprotoent();
  481. }
  482. });
  483. while (true) {
  484. current_protocol = getprotoent();
  485. if (current_protocol == nullptr)
  486. break;
  487. else if (strcmp(current_protocol->p_name, name) == 0)
  488. break;
  489. }
  490. return current_protocol;
  491. }
  492. struct protoent* getprotobynumber(int proto)
  493. {
  494. bool previous_file_open_setting = keep_protocols_file_open;
  495. setprotoent(1);
  496. struct protoent* current_protocol = nullptr;
  497. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  498. if (!previous_file_open_setting) {
  499. endprotoent();
  500. }
  501. });
  502. while (true) {
  503. current_protocol = getprotoent();
  504. if (current_protocol == nullptr)
  505. break;
  506. else if (current_protocol->p_proto == proto)
  507. break;
  508. }
  509. return current_protocol;
  510. }
  511. void setprotoent(int stay_open)
  512. {
  513. if (!protocols_file) {
  514. protocols_file = fopen(protocols_path, "r");
  515. if (!protocols_file) {
  516. perror("setprotoent(): error opening protocols file");
  517. return;
  518. }
  519. }
  520. rewind(protocols_file);
  521. keep_protocols_file_open = stay_open;
  522. protocol_file_offset = 0;
  523. }
  524. void endprotoent()
  525. {
  526. if (!protocols_file) {
  527. return;
  528. }
  529. fclose(protocols_file);
  530. protocols_file = nullptr;
  531. }
  532. static bool fill_getproto_buffers(const char* line, ssize_t read)
  533. {
  534. String string_line = String(line, read);
  535. string_line.replace(" ", "\t", true);
  536. auto split_line = string_line.split('\t');
  537. // This indicates an incorrect file format. Protocols file entries should
  538. // always have at least a name and a protocol.
  539. if (split_line.size() < 2) {
  540. fprintf(stderr, "getprotoent(): malformed protocols file\n");
  541. return false;
  542. }
  543. __getproto_name_buffer = split_line[0];
  544. auto number = split_line[1].to_int();
  545. if (!number.has_value())
  546. return false;
  547. __getproto_protocol_buffer = number.value();
  548. __getproto_alias_list_buffer.clear();
  549. // If there are aliases for the protocol, we will fill the alias list buffer.
  550. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  551. for (size_t i = 2; i < split_line.size(); i++) {
  552. if (split_line[i].starts_with('#'))
  553. break;
  554. auto alias = split_line[i].to_byte_buffer();
  555. alias.append("\0", sizeof(char));
  556. __getproto_alias_list_buffer.append(alias);
  557. }
  558. }
  559. return true;
  560. }
  561. }