netdb.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. // Get service entry buffers and file information for the getservent() family of functions.
  45. static FILE* services_file = nullptr;
  46. static const char* services_path = "/etc/services";
  47. static bool fill_getserv_buffers(const char* line, ssize_t read);
  48. static servent __getserv_buffer;
  49. static String __getserv_name_buffer;
  50. static String __getserv_protocol_buffer;
  51. static int __getserv_port_buffer;
  52. static Vector<ByteBuffer> __getserv_alias_list_buffer;
  53. static Vector<char*> __getserv_alias_list;
  54. static bool keep_service_file_open = false;
  55. static ssize_t service_file_offset = 0;
  56. // Get protocol entry buffers and file information for the getprotent() family of functions.
  57. static FILE* protocols_file = nullptr;
  58. static const char* protocols_path = "/etc/protocols";
  59. static bool fill_getproto_buffers(const char* line, ssize_t read);
  60. static protoent __getproto_buffer;
  61. static String __getproto_name_buffer;
  62. static Vector<ByteBuffer> __getproto_alias_list_buffer;
  63. static Vector<char*> __getproto_alias_list;
  64. static int __getproto_protocol_buffer;
  65. static bool keep_protocols_file_open = false;
  66. static ssize_t protocol_file_offset = 0;
  67. static int connect_to_lookup_server()
  68. {
  69. int fd = socket(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0);
  70. if (fd < 0) {
  71. perror("socket");
  72. return -1;
  73. }
  74. sockaddr_un address {
  75. AF_LOCAL,
  76. "/tmp/portal/lookup"
  77. };
  78. if (connect(fd, (const sockaddr*)&address, sizeof(address)) < 0) {
  79. perror("connect_to_lookup_server");
  80. close(fd);
  81. return -1;
  82. }
  83. return fd;
  84. }
  85. static String gethostbyname_name_buffer;
  86. hostent* gethostbyname(const char* name)
  87. {
  88. auto ipv4_address = IPv4Address::from_string(name);
  89. if (ipv4_address.has_value()) {
  90. gethostbyname_name_buffer = ipv4_address.value().to_string();
  91. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  92. __gethostbyname_buffer.h_aliases = nullptr;
  93. __gethostbyname_buffer.h_addrtype = AF_INET;
  94. new (&__gethostbyname_address) IPv4Address(ipv4_address.value());
  95. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  96. __gethostbyname_address_list_buffer[1] = nullptr;
  97. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  98. __gethostbyname_buffer.h_length = 4;
  99. return &__gethostbyname_buffer;
  100. }
  101. int fd = connect_to_lookup_server();
  102. if (fd < 0)
  103. return nullptr;
  104. auto close_fd_on_exit = ScopeGuard([fd] {
  105. close(fd);
  106. });
  107. auto line = String::format("L%s\n", name);
  108. int nsent = write(fd, line.characters(), line.length());
  109. if (nsent < 0) {
  110. perror("write");
  111. return nullptr;
  112. }
  113. ASSERT((size_t)nsent == line.length());
  114. char buffer[1024];
  115. int nrecv = read(fd, buffer, sizeof(buffer) - 1);
  116. if (nrecv < 0) {
  117. perror("recv");
  118. return nullptr;
  119. }
  120. if (!memcmp(buffer, "Not found.", sizeof("Not found.") - 1))
  121. return nullptr;
  122. auto responses = String(buffer, nrecv).split('\n');
  123. if (responses.is_empty())
  124. return nullptr;
  125. auto& response = responses[0];
  126. int rc = inet_pton(AF_INET, response.characters(), &__gethostbyname_address);
  127. if (rc <= 0)
  128. return nullptr;
  129. gethostbyname_name_buffer = name;
  130. __gethostbyname_buffer.h_name = const_cast<char*>(gethostbyname_name_buffer.characters());
  131. __gethostbyname_buffer.h_aliases = nullptr;
  132. __gethostbyname_buffer.h_addrtype = AF_INET;
  133. __gethostbyname_address_list_buffer[0] = &__gethostbyname_address;
  134. __gethostbyname_address_list_buffer[1] = nullptr;
  135. __gethostbyname_buffer.h_addr_list = (char**)__gethostbyname_address_list_buffer;
  136. __gethostbyname_buffer.h_length = 4;
  137. return &__gethostbyname_buffer;
  138. }
  139. static String gethostbyaddr_name_buffer;
  140. hostent* gethostbyaddr(const void* addr, socklen_t addr_size, int type)
  141. {
  142. if (type != AF_INET) {
  143. errno = EAFNOSUPPORT;
  144. return nullptr;
  145. }
  146. if (addr_size < sizeof(in_addr)) {
  147. errno = EINVAL;
  148. return nullptr;
  149. }
  150. int fd = connect_to_lookup_server();
  151. if (fd < 0)
  152. return nullptr;
  153. auto close_fd_on_exit = ScopeGuard([fd] {
  154. close(fd);
  155. });
  156. IPv4Address ipv4_address((const u8*)&((const in_addr*)addr)->s_addr);
  157. auto line = String::format("R%d.%d.%d.%d.in-addr.arpa\n",
  158. ipv4_address[3],
  159. ipv4_address[2],
  160. ipv4_address[1],
  161. ipv4_address[0]);
  162. int nsent = write(fd, line.characters(), line.length());
  163. if (nsent < 0) {
  164. perror("write");
  165. return nullptr;
  166. }
  167. ASSERT((size_t)nsent == line.length());
  168. char buffer[1024];
  169. int nrecv = read(fd, buffer, sizeof(buffer) - 1);
  170. if (nrecv < 0) {
  171. perror("recv");
  172. return nullptr;
  173. }
  174. if (!memcmp(buffer, "Not found.", sizeof("Not found.") - 1))
  175. return nullptr;
  176. auto responses = String(buffer, nrecv).split('\n');
  177. if (responses.is_empty())
  178. return nullptr;
  179. gethostbyaddr_name_buffer = responses[0];
  180. __gethostbyaddr_buffer.h_name = const_cast<char*>(gethostbyaddr_name_buffer.characters());
  181. __gethostbyaddr_buffer.h_aliases = nullptr;
  182. __gethostbyaddr_buffer.h_addrtype = AF_INET;
  183. // FIXME: Should we populate the hostent's address list here with a sockaddr_in for the provided host?
  184. __gethostbyaddr_address_list_buffer[0] = nullptr;
  185. __gethostbyaddr_buffer.h_addr_list = (char**)__gethostbyaddr_address_list_buffer;
  186. __gethostbyaddr_buffer.h_length = 4;
  187. return &__gethostbyaddr_buffer;
  188. }
  189. struct servent* getservent()
  190. {
  191. //If the services file is not open, attempt to open it and return null if it fails.
  192. if (!services_file) {
  193. services_file = fopen(services_path, "r");
  194. if (!services_file) {
  195. perror("error opening services file");
  196. return nullptr;
  197. }
  198. }
  199. if (fseek(services_file, service_file_offset, SEEK_SET) != 0) {
  200. perror("error seeking file");
  201. fclose(services_file);
  202. return nullptr;
  203. }
  204. char* line = nullptr;
  205. size_t len = 0;
  206. ssize_t read;
  207. auto free_line_on_exit = ScopeGuard([line] {
  208. if (line) {
  209. free(line);
  210. }
  211. });
  212. // Read lines from services file until an actual service name is found.
  213. do {
  214. read = getline(&line, &len, services_file);
  215. service_file_offset += read;
  216. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  217. break;
  218. }
  219. } while (read != -1);
  220. if (read == -1) {
  221. fclose(services_file);
  222. services_file = nullptr;
  223. service_file_offset = 0;
  224. return nullptr;
  225. }
  226. servent* service_entry = nullptr;
  227. if (!fill_getserv_buffers(line, read))
  228. return nullptr;
  229. __getserv_buffer.s_name = const_cast<char*>(__getserv_name_buffer.characters());
  230. __getserv_buffer.s_port = __getserv_port_buffer;
  231. __getserv_buffer.s_proto = const_cast<char*>(__getserv_protocol_buffer.characters());
  232. __getserv_alias_list.clear_with_capacity();
  233. __getserv_alias_list.ensure_capacity(__getserv_alias_list_buffer.size() + 1);
  234. for (auto& alias : __getserv_alias_list_buffer)
  235. __getserv_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  236. __getserv_alias_list.unchecked_append(nullptr);
  237. __getserv_buffer.s_aliases = __getserv_alias_list.data();
  238. service_entry = &__getserv_buffer;
  239. if (!keep_service_file_open) {
  240. endservent();
  241. }
  242. return service_entry;
  243. }
  244. struct servent* getservbyname(const char* name, const char* protocol)
  245. {
  246. bool previous_file_open_setting = keep_service_file_open;
  247. setservent(1);
  248. struct servent* current_service = nullptr;
  249. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  250. if (!previous_file_open_setting) {
  251. endservent();
  252. }
  253. });
  254. while (true) {
  255. current_service = getservent();
  256. if (current_service == nullptr)
  257. break;
  258. else if (!protocol && strcmp(current_service->s_name, name) == 0)
  259. break;
  260. else if (strcmp(current_service->s_name, name) == 0 && strcmp(current_service->s_proto, protocol) == 0)
  261. break;
  262. }
  263. return current_service;
  264. }
  265. struct servent* getservbyport(int port, const char* protocol)
  266. {
  267. bool previous_file_open_setting = keep_service_file_open;
  268. setservent(1);
  269. struct servent* current_service = nullptr;
  270. auto service_file_handler = ScopeGuard([previous_file_open_setting] {
  271. if (!previous_file_open_setting) {
  272. endservent();
  273. }
  274. });
  275. while (true) {
  276. current_service = getservent();
  277. if (current_service == nullptr)
  278. break;
  279. else if (!protocol && current_service->s_port == port)
  280. break;
  281. else if (current_service->s_port == port && (strcmp(current_service->s_proto, protocol) == 0))
  282. break;
  283. }
  284. return current_service;
  285. }
  286. void setservent(int stay_open)
  287. {
  288. if (!services_file) {
  289. services_file = fopen(services_path, "r");
  290. if (!services_file) {
  291. perror("error opening services file");
  292. return;
  293. }
  294. }
  295. rewind(services_file);
  296. keep_service_file_open = stay_open;
  297. service_file_offset = 0;
  298. }
  299. void endservent()
  300. {
  301. if (!services_file) {
  302. return;
  303. }
  304. fclose(services_file);
  305. services_file = nullptr;
  306. }
  307. // Fill the service entry buffer with the information contained
  308. // in the currently read line, returns true if successful,
  309. // false if failure occurs.
  310. static bool fill_getserv_buffers(const char* line, ssize_t read)
  311. {
  312. //Splitting the line by tab delimiter and filling the servent buffers name, port, and protocol members.
  313. String string_line = String(line, read);
  314. string_line.replace(" ", "\t", true);
  315. auto split_line = string_line.split('\t');
  316. // This indicates an incorrect file format.
  317. // Services file entries should always at least contain
  318. // name and port/protocol, separated by tabs.
  319. if (split_line.size() < 2) {
  320. fprintf(stderr, "getservent(): malformed services file\n");
  321. return false;
  322. }
  323. __getserv_name_buffer = split_line[0];
  324. auto port_protocol_split = String(split_line[1]).split('/');
  325. if (port_protocol_split.size() < 2) {
  326. fprintf(stderr, "getservent(): malformed services file\n");
  327. return false;
  328. }
  329. auto number = port_protocol_split[0].to_int();
  330. if (!number.has_value())
  331. return false;
  332. __getserv_port_buffer = number.value();
  333. // Remove any annoying whitespace at the end of the protocol.
  334. port_protocol_split[1].replace(" ", "", true);
  335. port_protocol_split[1].replace("\t", "", true);
  336. port_protocol_split[1].replace("\n", "", true);
  337. __getserv_protocol_buffer = port_protocol_split[1];
  338. __getserv_alias_list_buffer.clear();
  339. // If there are aliases for the service, we will fill the alias list buffer.
  340. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  341. for (size_t i = 2; i < split_line.size(); i++) {
  342. if (split_line[i].starts_with('#')) {
  343. break;
  344. }
  345. auto alias = split_line[i].to_byte_buffer();
  346. alias.append("\0", sizeof(char));
  347. __getserv_alias_list_buffer.append(alias);
  348. }
  349. }
  350. return true;
  351. }
  352. struct protoent* getprotoent()
  353. {
  354. // If protocols file isn't open, attempt to open and return null on failure.
  355. if (!protocols_file) {
  356. protocols_file = fopen(protocols_path, "r");
  357. if (!protocols_file) {
  358. perror("error opening protocols file");
  359. return nullptr;
  360. }
  361. }
  362. if (fseek(protocols_file, protocol_file_offset, SEEK_SET) != 0) {
  363. perror("error seeking protocols file");
  364. fclose(protocols_file);
  365. return nullptr;
  366. }
  367. char* line = nullptr;
  368. size_t len = 0;
  369. ssize_t read;
  370. auto free_line_on_exit = ScopeGuard([line] {
  371. if (line) {
  372. free(line);
  373. }
  374. });
  375. do {
  376. read = getline(&line, &len, protocols_file);
  377. protocol_file_offset += read;
  378. if (read > 0 && (line[0] >= 65 && line[0] <= 122)) {
  379. break;
  380. }
  381. } while (read != -1);
  382. if (read == -1) {
  383. fclose(protocols_file);
  384. protocols_file = nullptr;
  385. protocol_file_offset = 0;
  386. return nullptr;
  387. }
  388. struct protoent* protocol_entry = nullptr;
  389. if (!fill_getproto_buffers(line, read))
  390. return nullptr;
  391. __getproto_buffer.p_name = const_cast<char*>(__getproto_name_buffer.characters());
  392. __getproto_buffer.p_proto = __getproto_protocol_buffer;
  393. __getproto_alias_list.clear_with_capacity();
  394. __getproto_alias_list.ensure_capacity(__getproto_alias_list_buffer.size() + 1);
  395. for (auto& alias : __getproto_alias_list_buffer)
  396. __getproto_alias_list.unchecked_append(reinterpret_cast<char*>(alias.data()));
  397. __getserv_alias_list.unchecked_append(nullptr);
  398. __getproto_buffer.p_aliases = __getproto_alias_list.data();
  399. protocol_entry = &__getproto_buffer;
  400. if (!keep_protocols_file_open)
  401. endprotoent();
  402. return protocol_entry;
  403. }
  404. struct protoent* getprotobyname(const char* name)
  405. {
  406. bool previous_file_open_setting = keep_protocols_file_open;
  407. setprotoent(1);
  408. struct protoent* current_protocol = nullptr;
  409. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  410. if (!previous_file_open_setting) {
  411. endprotoent();
  412. }
  413. });
  414. while (true) {
  415. current_protocol = getprotoent();
  416. if (current_protocol == nullptr)
  417. break;
  418. else if (strcmp(current_protocol->p_name, name) == 0)
  419. break;
  420. }
  421. return current_protocol;
  422. }
  423. struct protoent* getprotobynumber(int proto)
  424. {
  425. bool previous_file_open_setting = keep_protocols_file_open;
  426. setprotoent(1);
  427. struct protoent* current_protocol = nullptr;
  428. auto protocol_file_handler = ScopeGuard([previous_file_open_setting] {
  429. if (!previous_file_open_setting) {
  430. endprotoent();
  431. }
  432. });
  433. while (true) {
  434. current_protocol = getprotoent();
  435. if (current_protocol == nullptr)
  436. break;
  437. else if (current_protocol->p_proto == proto)
  438. break;
  439. }
  440. return current_protocol;
  441. }
  442. void setprotoent(int stay_open)
  443. {
  444. if (!protocols_file) {
  445. protocols_file = fopen(protocols_path, "r");
  446. if (!protocols_file) {
  447. perror("setprotoent(): error opening protocols file");
  448. return;
  449. }
  450. }
  451. rewind(protocols_file);
  452. keep_protocols_file_open = stay_open;
  453. protocol_file_offset = 0;
  454. }
  455. void endprotoent()
  456. {
  457. if (!protocols_file) {
  458. return;
  459. }
  460. fclose(protocols_file);
  461. protocols_file = nullptr;
  462. }
  463. static bool fill_getproto_buffers(const char* line, ssize_t read)
  464. {
  465. String string_line = String(line, read);
  466. string_line.replace(" ", "\t", true);
  467. auto split_line = string_line.split('\t');
  468. // This indicates an incorrect file format. Protocols file entries should
  469. // always have at least a name and a protocol.
  470. if (split_line.size() < 2) {
  471. fprintf(stderr, "getprotoent(): malformed protocols file\n");
  472. return false;
  473. }
  474. __getproto_name_buffer = split_line[0];
  475. auto number = split_line[1].to_int();
  476. if (!number.has_value())
  477. return false;
  478. __getproto_protocol_buffer = number.value();
  479. __getproto_alias_list_buffer.clear();
  480. // If there are aliases for the protocol, we will fill the alias list buffer.
  481. if (split_line.size() > 2 && !split_line[2].starts_with('#')) {
  482. for (size_t i = 2; i < split_line.size(); i++) {
  483. if (split_line[i].starts_with('#'))
  484. break;
  485. auto alias = split_line[i].to_byte_buffer();
  486. alias.append("\0", sizeof(char));
  487. __getproto_alias_list_buffer.append(alias);
  488. }
  489. }
  490. return true;
  491. }
  492. }