diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index e57f969..69c66dc 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -65,6 +65,20 @@ Sample response } ``` +[GET] /proc/sys/kernel/hostname +-------------------------------- + +* returns hostname +* Same as /proc/sys/kernel/hostname file + +Sample response + +``` +{ + "hostname": "Samplebox" +} +``` + Special formatted responses =========================== @@ -94,3 +108,8 @@ Sample response "memavailable" : 12324924, } ``` + +[GET] /hostname +--------------- + +* Returns redirect to /proc/sys/kernel/hostname diff --git a/src/components/state.cpp b/src/components/state.cpp index c20ecbc..5ce4535 100644 --- a/src/components/state.cpp +++ b/src/components/state.cpp @@ -90,3 +90,33 @@ bool state::getRawLoadAvg(std::string& ret){ return true; } + +bool state::getHostname(crow::json::wvalue& ret){ + std::ifstream f (prochostnamepath); + std::string line; + if(f.is_open()){ + std::getline(f, line); + + ret["hostname"] = line; + f.close(); + } else { + ret["message"] = "Failed to open proc filesystem"; + return false; + } + + return true; +} + +bool state::getRawHostname(std::string& ret){ + std::ifstream f (prochostnamepath); + if(f.is_open()){ + std::getline(f, ret); + ret += '\n'; + f.close(); + } else { + ret = "Failed to open proc filesystem"; + return false; + } + + return true; +} diff --git a/src/components/state.hpp b/src/components/state.hpp index 01603a7..1a17d7a 100644 --- a/src/components/state.hpp +++ b/src/components/state.hpp @@ -13,10 +13,13 @@ constexpr char procuptimepath[] = "/proc/uptime"; constexpr char procloadavgpath[] = "/proc/loadavg"; +constexpr char prochostnamepath[] = "/proc/sys/kernel/hostname"; namespace state{ bool getUptime(crow::json::wvalue&); bool getRawUptime(std::string&); bool getLoadAvg(crow::json::wvalue&); bool getRawLoadAvg(std::string&); + bool getHostname(crow::json::wvalue&); + bool getRawHostname(std::string&); } diff --git a/src/routes.cpp b/src/routes.cpp index 1eeb7ba..563b782 100644 --- a/src/routes.cpp +++ b/src/routes.cpp @@ -79,6 +79,29 @@ void setRoutes(crow::SimpleApp& app){ return ret; }); + CROW_ROUTE(app, "/proc/sys/kernel/hostname")([](const crow::request& req){ + bool status; + std::string accept = req.get_header_value("Accept"); + + std::transform(accept.begin(), accept.end(), accept.begin(), ::tolower); + + if(accept == "text/plain"){ + accept.clear(); + status = state::getRawHostname(accept); + return crow::response(status ? 200 : 503, accept); + } else { + crow::json::wvalue json; + status = state::getHostname(json); + return crow::response(status ? 200 : 503, json.dump()); + } + }); + + CROW_ROUTE(app, "/hostname")([](){ + crow::response ret; + ret.moved_perm("/proc/sys/kernel/hostname"); + return ret; + }); + //catchall route CROW_CATCHALL_ROUTE(app)([](){ crow::json::wvalue ret;