From 02692534c81b2ea07fe3b849f1454d4aa86dde77 Mon Sep 17 00:00:00 2001 From: Baptiste Wicht Date: Tue, 20 Sep 2016 19:50:07 +0200 Subject: [PATCH] Complete wget --- programs/wget/src/main.cpp | 87 +++++++++++++++++++++++++++++--------- 1 file changed, 66 insertions(+), 21 deletions(-) diff --git a/programs/wget/src/main.cpp b/programs/wget/src/main.cpp index 7a30b5f7..2be8443c 100644 --- a/programs/wget/src/main.cpp +++ b/programs/wget/src/main.cpp @@ -24,29 +24,74 @@ int wget_http(const std::string& url){ if(parts[0] == "http:"){ auto& domain = parts[1]; - auto ip = tlib::dns::resolve(domain); + tlib::ip::address ip; + if (tlib::dns::is_ip(domain)) { + auto ip_parts = std::split(domain, '.'); - if(ip){ - tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::STREAM, tlib::socket_protocol::TCP); - - sock.connect(*ip, 80); - sock.listen(true); - - if (!sock) { - tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); - return 1; - } - - //TODO - - sock.listen(false); - - if (!sock) { - tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); - return 1; - } + ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); } else { - tlib::print_line("wget: cannot resolve the domain"); + auto ip_result = tlib::dns::resolve(domain); + + if(!ip_result){ + tlib::print_line("wget: cannot resolve the domain"); + return 1; + } + + ip = *ip_result; + } + + tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::STREAM, tlib::socket_protocol::TCP); + + sock.connect(ip, 80); + sock.listen(true); + + if (!sock) { + tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); + return 1; + } + + std::string message; + + message += "GET "; + + if (parts.size() < 3) { + message += '/'; + } else { + for (size_t i = 2; i < parts.size(); ++i) { + message += '/'; + message += parts[i]; + } + } + + message += " HTTP/1.1\r\n"; + message += "Host: "; + message += domain; + message += "\r\n"; + message += "Accept: text/html text/plain\r\n"; + message += "User-Agent: wget (Thor OS)\r\n"; + message += "\r\n"; + + sock.send(message.c_str(), message.size()); + + char message_buffer[2049]; + auto size = sock.receive(message_buffer, 2048, 2000); + if (!sock) { + if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { + tlib::printf("Timeout\n"); + return 1; + } + + tlib::printf("nc: receive error: %s\n", std::error_message(sock.error())); + return 1; + } else { + message_buffer[size] = '\0'; + tlib::print(message_buffer); + } + + sock.listen(false); + + if (!sock) { + tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); return 1; } } else {