[3551804] | 1 | <?php |
---|
[7100d82] | 2 | |
---|
[3551804] | 3 | /** |
---|
| 4 | * @file index.php |
---|
[1ab1b31d] | 5 | * @brief OpenGnsys REST API: common functions and routes |
---|
[3551804] | 6 | * @warning All input and output messages are formatted in JSON. |
---|
| 7 | * @note Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx. |
---|
| 8 | * @license GNU GPLv3+ |
---|
| 9 | * @author Ramón M. Gómez, ETSII Univ. Sevilla |
---|
| 10 | * @version 1.1.0 - First version |
---|
| 11 | * @date 2016-11-17 |
---|
| 12 | */ |
---|
| 13 | |
---|
| 14 | |
---|
[13dc959] | 15 | // Common constants. |
---|
| 16 | define('REST_LOGFILE', '/opt/opengnsys/log/rest.log'); |
---|
[c008325] | 17 | define('VERSION_FILE', '/opt/opengnsys/doc/VERSION.json'); |
---|
[13dc959] | 18 | |
---|
[7e7c0cd] | 19 | // Set time zone. |
---|
| 20 | if (function_exists("date_default_timezone_set")) { |
---|
| 21 | if (exec("timedatectl status | awk '/Time zone/ {print $3}'", $out, $err)) { |
---|
| 22 | date_default_timezone_set($out[0]); |
---|
| 23 | } |
---|
| 24 | } |
---|
[13dc959] | 25 | |
---|
[1ab1b31d] | 26 | // Common functions. |
---|
| 27 | |
---|
[3551804] | 28 | /** |
---|
[13dc959] | 29 | * @brief Function to write a line into log file. |
---|
| 30 | * @param string message Message to log. |
---|
| 31 | * warning Line format: "Date: ClientIP: UserId: Status: Method Route: Message" |
---|
| 32 | */ |
---|
[7100d82] | 33 | function writeRestLog($message = "") |
---|
| 34 | { |
---|
| 35 | global $userid; |
---|
| 36 | if (is_writable(REST_LOGFILE)) { |
---|
| 37 | $app = \Slim\Slim::getInstance(); |
---|
| 38 | file_put_contents( |
---|
| 39 | REST_LOGFILE, |
---|
| 40 | date(DATE_ISO8601) . ": " . |
---|
| 41 | $_SERVER['REMOTE_ADDR'] . ": " . |
---|
| 42 | (isset($userid) ? $userid : "-") . ": " . |
---|
| 43 | $app->response->getStatus() . ": " . |
---|
| 44 | $app->request->getMethod() . " " . |
---|
| 45 | $app->request->getPathInfo() . ": $message\n", |
---|
| 46 | FILE_APPEND |
---|
| 47 | ); |
---|
| 48 | } |
---|
[13dc959] | 49 | } |
---|
| 50 | |
---|
| 51 | /** |
---|
[3551804] | 52 | * @brief Compose JSON response. |
---|
| 53 | * @param int status Status code for HTTP response. |
---|
| 54 | * @param array response Response data. |
---|
[5ff84a5] | 55 | * @param int opts Options to encode JSON data. |
---|
[3551804] | 56 | * @return string JSON response. |
---|
[1ab1b31d] | 57 | */ |
---|
[7100d82] | 58 | function jsonResponse($status, $response, $opts = 0) |
---|
| 59 | { |
---|
| 60 | $app = \Slim\Slim::getInstance(); |
---|
| 61 | // HTTP status code. |
---|
| 62 | $app->status($status); |
---|
| 63 | // Content-type HTTP header. |
---|
| 64 | $app->contentType('application/json; charset=utf-8'); |
---|
| 65 | // JSON response. |
---|
| 66 | echo json_encode($response, $opts); |
---|
[3551804] | 67 | } |
---|
| 68 | |
---|
[1ab1b31d] | 69 | /** |
---|
[8ba8712] | 70 | * @brief Print immediately JSON response to continue processing. |
---|
| 71 | * @param int status Status code for HTTP response. |
---|
| 72 | * @param array response Response data. |
---|
| 73 | * @param int opts Options to encode JSON data. |
---|
| 74 | * @return string JSON response. |
---|
| 75 | */ |
---|
[7100d82] | 76 | function jsonResponseNow($status, $response, $opts = 0) |
---|
| 77 | { |
---|
| 78 | // Compose headers and content. |
---|
| 79 | ignore_user_abort(); |
---|
| 80 | http_response_code((int)$status); |
---|
| 81 | header('Content-type: application/json; charset=utf-8'); |
---|
| 82 | ob_start(); |
---|
| 83 | echo json_encode($response, $opts); |
---|
| 84 | $size = ob_get_length(); |
---|
| 85 | header("Content-Length: $size"); |
---|
| 86 | // Print content. |
---|
| 87 | ob_end_flush(); |
---|
| 88 | flush(); |
---|
| 89 | session_write_close(); |
---|
[8ba8712] | 90 | } |
---|
| 91 | |
---|
| 92 | /** |
---|
[1ab1b31d] | 93 | * @brief Validate API key included in "Authorization" HTTP header. |
---|
[195753c] | 94 | * @return string JSON response on error. |
---|
[1ab1b31d] | 95 | */ |
---|
[7100d82] | 96 | function validateApiKey() |
---|
| 97 | { |
---|
| 98 | global $cmd; |
---|
| 99 | global $userid; |
---|
| 100 | $response = []; |
---|
| 101 | $app = \Slim\Slim::getInstance(); |
---|
| 102 | // Read Authorization HTTP header. |
---|
| 103 | if (!empty($_SERVER['HTTP_AUTHORIZATION'])) { |
---|
| 104 | // Assign user id. that match this key to global variable. |
---|
| 105 | $apikey = htmlspecialchars($_SERVER['HTTP_AUTHORIZATION']); |
---|
| 106 | $cmd->texto = "SELECT idusuario |
---|
[1ab1b31d] | 107 | FROM usuarios |
---|
| 108 | WHERE apikey='$apikey' LIMIT 1"; |
---|
[7100d82] | 109 | $rs = new Recordset; |
---|
| 110 | $rs->Comando = &$cmd; |
---|
| 111 | if ($rs->Abrir()) { |
---|
| 112 | $rs->Primero(); |
---|
| 113 | if (!$rs->EOF) { |
---|
| 114 | // Fetch user id. |
---|
| 115 | $userid = $rs->campos["idusuario"]; |
---|
| 116 | } else { |
---|
| 117 | // Credentials error. |
---|
| 118 | $response['message'] = 'Login failed, incorrect credentials'; |
---|
| 119 | jsonResponse(401, $response); |
---|
| 120 | $app->stop(); |
---|
| 121 | } |
---|
| 122 | $rs->Cerrar(); |
---|
| 123 | } else { |
---|
| 124 | // Database error. |
---|
| 125 | $response['message'] = "An error occurred, please try again"; |
---|
| 126 | jsonResponse(500, $response); |
---|
| 127 | } |
---|
| 128 | } else { |
---|
| 129 | // Error: missing API key. |
---|
| 130 | $response['message'] = 'Missing API key'; |
---|
| 131 | jsonResponse(400, $response); |
---|
| 132 | $app->stop(); |
---|
| 133 | } |
---|
[1ab1b31d] | 134 | } |
---|
| 135 | |
---|
| 136 | /** |
---|
| 137 | * @brief Check if parameter is set and print error messages if empty. |
---|
| 138 | * @param string param Parameter to check. |
---|
| 139 | * @return boolean "false" if parameter is null, otherwise "true". |
---|
| 140 | */ |
---|
[7100d82] | 141 | function checkParameter($param) |
---|
| 142 | { |
---|
| 143 | $response = []; |
---|
| 144 | if (isset($param)) { |
---|
| 145 | return true; |
---|
| 146 | } else { |
---|
| 147 | // Print error message. |
---|
| 148 | $response['message'] = 'Parameter not found'; |
---|
| 149 | jsonResponse(400, $response); |
---|
| 150 | return false; |
---|
| 151 | } |
---|
[1ab1b31d] | 152 | } |
---|
| 153 | |
---|
| 154 | /** |
---|
[d8b6c70] | 155 | * @brief Check if all parameters are positive integer numbers. |
---|
| 156 | * @param int id ... Identificators to check (variable number of parameters). |
---|
| 157 | * @return boolean "true" if all ids are int>0, otherwise "false". |
---|
| 158 | */ |
---|
[7100d82] | 159 | function checkIds() |
---|
| 160 | { |
---|
| 161 | $opts = ['options' => ['min_range' => 1]]; // Check for int>0 |
---|
| 162 | foreach (func_get_args() as $id) { |
---|
| 163 | if (filter_var($id, FILTER_VALIDATE_INT, $opts) === false) { |
---|
| 164 | return false; |
---|
| 165 | } |
---|
| 166 | } |
---|
| 167 | return true; |
---|
[d8b6c70] | 168 | } |
---|
| 169 | |
---|
| 170 | /** |
---|
[357352b] | 171 | * @brief Show custom message for "not found" error (404). |
---|
| 172 | */ |
---|
[195753c] | 173 | $app->notFound( |
---|
[7100d82] | 174 | function () { |
---|
[195753c] | 175 | $response['message'] = 'REST route not found'; |
---|
| 176 | jsonResponse(404, $response); |
---|
[7100d82] | 177 | } |
---|
[357352b] | 178 | ); |
---|
| 179 | |
---|
| 180 | /** |
---|
[13dc959] | 181 | * @brief Hook to write an error log message and a REST exit log message if debug is enabled. |
---|
| 182 | * @warning Error message will be written in web server's error file. |
---|
| 183 | * @warning REST message will be written in REST log file. |
---|
[1ab1b31d] | 184 | */ |
---|
[7100d82] | 185 | $app->hook( |
---|
| 186 | 'slim.after', |
---|
| 187 | function () use ($app) { |
---|
| 188 | if ($app->response->getStatus() != 200) { |
---|
| 189 | // Compose error message (truncating long lines). |
---|
| 190 | $app->log->error(date(DATE_ISO8601) . ': ' . |
---|
| 191 | $app->getName() . ': ' . |
---|
| 192 | $_SERVER['REMOTE_ADDR'] . ": " . |
---|
| 193 | (isset($userid) ? $userid : "-") . ": " . |
---|
| 194 | $app->response->getStatus() . ': ' . |
---|
| 195 | $app->request->getMethod() . ' ' . |
---|
| 196 | $app->request->getPathInfo() . ': ' . |
---|
| 197 | substr($app->response->getBody(), 0, 100)); |
---|
| 198 | } |
---|
| 199 | if ($app->settings['debug']) |
---|
| 200 | writeRestLog(substr($app->response->getBody(), 0, 30)); |
---|
| 201 | } |
---|
[1ab1b31d] | 202 | ); |
---|
| 203 | |
---|
| 204 | |
---|
[3551804] | 205 | // Common routes. |
---|
| 206 | |
---|
| 207 | /** |
---|
| 208 | * @brief Get general server information |
---|
| 209 | * @note Route: /info, Method: GET |
---|
[195753c] | 210 | * @return string JSON object with basic server information (version, services, etc.) |
---|
[3551804] | 211 | */ |
---|
[7100d82] | 212 | $app->get( |
---|
| 213 | '/info', |
---|
| 214 | function () { |
---|
| 215 | $hasOglive = false; |
---|
| 216 | $response = new \stdClass; |
---|
| 217 | // Reading version file. |
---|
| 218 | $data = json_decode(@file_get_contents(VERSION_FILE)); |
---|
| 219 | if (isset($data->project)) { |
---|
| 220 | $response = $data; |
---|
| 221 | } else { |
---|
| 222 | $response->project = 'OpenGnsys'; |
---|
| 223 | } |
---|
| 224 | // Getting actived services. |
---|
| 225 | @$services = parse_ini_file('/etc/default/opengnsys'); |
---|
| 226 | $response->services = []; |
---|
| 227 | if (@$services["RUN_OGADMSERVER"] === "yes") { |
---|
| 228 | array_push($response->services, "server"); |
---|
| 229 | $hasOglive = true; |
---|
| 230 | } |
---|
| 231 | if (@$services["RUN_OGADMREPO"] === "yes") array_push($response->services, "repository"); |
---|
| 232 | if (@$services["RUN_BTTRACKER"] === "yes") array_push($response->services, "tracker"); |
---|
| 233 | // Reading installed ogLive information file. |
---|
| 234 | if ($hasOglive === true) { |
---|
| 235 | $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json')); |
---|
| 236 | if (isset($data->oglive)) { |
---|
| 237 | $response->oglive = $data->oglive; |
---|
| 238 | } |
---|
| 239 | } |
---|
| 240 | jsonResponse(200, $response); |
---|
| 241 | } |
---|
[3551804] | 242 | ); |
---|
| 243 | |
---|
[c069a28] | 244 | |
---|
[7100d82] | 245 | function backupConfig() |
---|
| 246 | { |
---|
[c069a28] | 247 | $get_command = 'config-get'; |
---|
| 248 | $get_output = executeCurlCommand($get_command); |
---|
[dd181cc] | 249 | if ($get_output == false || $get_output[0]["result"] != 0) { |
---|
[c069a28] | 250 | throw new Exception('Error al obtener la configuración actual de Kea DHCP'); |
---|
| 251 | } |
---|
[7100d82] | 252 | $config_text = json_encode($get_output[0]['arguments']); |
---|
| 253 | $configurationParsed = str_replace('\\', '', $config_text); |
---|
[c069a28] | 254 | |
---|
| 255 | $backup_dir = '/opt/opengnsys/etc/kea/backup'; |
---|
[5727130] | 256 | if (!is_dir($backup_dir)) { |
---|
| 257 | throw new Exception('El directorio de backup no existe'); |
---|
| 258 | } |
---|
| 259 | if (!is_writable($backup_dir)) { |
---|
| 260 | throw new Exception('El directorio de backup no tiene permisos de escritura'); |
---|
| 261 | } |
---|
[c069a28] | 262 | $backup_files = glob($backup_dir . '/*.conf'); |
---|
| 263 | if (count($backup_files) >= 10) { |
---|
[7100d82] | 264 | usort($backup_files, function ($a, $b) { |
---|
[c069a28] | 265 | return filemtime($a) - filemtime($b); |
---|
| 266 | }); |
---|
| 267 | unlink($backup_files[0]); |
---|
| 268 | } |
---|
| 269 | $backup_file = $backup_dir . '/' . date('Y-m-d_H-i-s') . '.conf'; |
---|
| 270 | if (!file_put_contents($backup_file, $configurationParsed)) { |
---|
| 271 | throw new Exception('Error al guardar la configuración de backup'); |
---|
| 272 | } |
---|
| 273 | } |
---|
| 274 | |
---|
[7100d82] | 275 | function executeCurlCommand($command, $arguments = null, $create_backup = true) |
---|
| 276 | { |
---|
[dd181cc] | 277 | $apiUrl = getenv('DHCP_IP'); |
---|
| 278 | if (!$apiUrl) { |
---|
| 279 | $apiUrl = 'http://localhost:8000/'; |
---|
[d7c02f4] | 280 | } |
---|
| 281 | |
---|
[99cefa0] | 282 | if ($command == 'config-get' || $command == 'config-write') { |
---|
[b61fee8] | 283 | $requestData = array( |
---|
| 284 | 'command' => $command, |
---|
| 285 | 'service' => array('dhcp4'), |
---|
| 286 | ); |
---|
| 287 | } elseif ($command == 'config-set' || $command == 'config-test') { |
---|
| 288 | $requestData = array( |
---|
| 289 | 'command' => $command, |
---|
| 290 | 'service' => array('dhcp4'), |
---|
| 291 | 'arguments' => $arguments, |
---|
| 292 | ); |
---|
| 293 | } else { |
---|
| 294 | return "Error: Comando no válido"; |
---|
| 295 | } |
---|
[7100d82] | 296 | if (($command == 'config-set' || $command == 'config-write') && $create_backup) { |
---|
| 297 | backupConfig(); |
---|
| 298 | } |
---|
[b61fee8] | 299 | $jsonData = json_encode($requestData); |
---|
[7100d82] | 300 | try { |
---|
[0eb2e98] | 301 | $ch = curl_init(); |
---|
| 302 | curl_setopt($ch, CURLOPT_URL, $apiUrl); |
---|
| 303 | curl_setopt($ch, CURLOPT_POST, 1); |
---|
| 304 | curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); |
---|
| 305 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
---|
[a4f75938] | 306 | curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:')); |
---|
[0eb2e98] | 307 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); |
---|
| 308 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
---|
[7d49912] | 309 | curl_setopt($ch, CURLOPT_TIMEOUT, 10); |
---|
[7100d82] | 310 | curl_setopt($ch, CURLOPT_POST, true); |
---|
[0eb2e98] | 311 | $response = curl_exec($ch); |
---|
| 312 | $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
---|
| 313 | $output = json_decode($response, true); |
---|
[b61fee8] | 314 | |
---|
[0eb2e98] | 315 | if ($httpCode >= 200 && $httpCode < 300) { |
---|
[d7c02f4] | 316 | |
---|
[7100d82] | 317 | return $output; |
---|
[0eb2e98] | 318 | } else { |
---|
[7d49912] | 319 | $error = curl_error($ch); |
---|
| 320 | throw new Exception($error); |
---|
| 321 | //return false; |
---|
[0eb2e98] | 322 | } |
---|
| 323 | } catch (Exception $e) { |
---|
[7d49912] | 324 | throw new Exception($e->getMessage()); |
---|
[a8775ca] | 325 | } |
---|
| 326 | } |
---|
| 327 | |
---|
[f78659d] | 328 | |
---|
| 329 | /** |
---|
[bec1753] | 330 | * @brief Get configuration of kea dhcp server |
---|
| 331 | * @note Route: /dhcp, Method: GET |
---|
| 332 | * @return string JSON object with all kea configuration |
---|
[f78659d] | 333 | */ |
---|
[7100d82] | 334 | $app->get('/dhcp', function () { |
---|
| 335 | try { |
---|
[5727130] | 336 | $response = executeCurlCommand('config-get'); |
---|
[f78659d] | 337 | |
---|
[7100d82] | 338 | if (!$response) { |
---|
[5727130] | 339 | $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf'; |
---|
[bec1753] | 340 | jsonResponse(400, $responseError); |
---|
[7100d82] | 341 | } else { |
---|
[5727130] | 342 | $result_code = $response[0]["result"]; |
---|
[7100d82] | 343 | if ($result_code == 0) { |
---|
[5727130] | 344 | $arrayDhcp4 = $response[0]['arguments']; |
---|
[7100d82] | 345 | jsonResponse(200, $arrayDhcp4, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
---|
| 346 | } else { |
---|
| 347 | $responseError = "Error kea configuration invalid: " . $response[0]["text"]; |
---|
[5727130] | 348 | jsonResponse(400, $responseError); |
---|
| 349 | } |
---|
[a8775ca] | 350 | } |
---|
[7100d82] | 351 | } catch (Exception $e) { |
---|
| 352 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 353 | jsonResponse(400, $responseError); |
---|
[7100d82] | 354 | } |
---|
[a8775ca] | 355 | }); |
---|
[8a00e28] | 356 | |
---|
[bec1753] | 357 | /** |
---|
| 358 | * @brief Get hosts from kea configuration |
---|
| 359 | * @note Route: /dhcp/hosts, Method: GET |
---|
| 360 | * @return string JSON object with all hosts in kea configuration |
---|
| 361 | */ |
---|
| 362 | |
---|
[7100d82] | 363 | $app->get('/dhcp/hosts', function () { |
---|
| 364 | try { |
---|
| 365 | $response = executeCurlCommand('config-get'); |
---|
[8a00e28] | 366 | |
---|
[7100d82] | 367 | if (!$response) { |
---|
[5727130] | 368 | $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf'; |
---|
| 369 | jsonResponse(400, $response); |
---|
[7100d82] | 370 | } else { |
---|
[5727130] | 371 | $result_code = $response[0]["result"]; |
---|
[7100d82] | 372 | if ($result_code == 0) { |
---|
[dd181cc] | 373 | if (!isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 374 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
| 375 | jsonResponse(400, $responseError); |
---|
| 376 | } else { |
---|
| 377 | $arrayReservations = $response[0]['arguments']['Dhcp4']['reservations']; |
---|
| 378 | jsonResponse(200, $arrayReservations, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
---|
| 379 | } |
---|
[7100d82] | 380 | } else { |
---|
| 381 | $responseError = "Error kea configuration invalid: " . $response[0]["text"]; |
---|
[5727130] | 382 | jsonResponse(400, $responseError); |
---|
| 383 | } |
---|
[7100d82] | 384 | } |
---|
| 385 | } catch (Exception $e) { |
---|
| 386 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 387 | jsonResponse(400, $responseError); |
---|
| 388 | } |
---|
[a8775ca] | 389 | }); |
---|
[8a00e28] | 390 | |
---|
[bec1753] | 391 | /** |
---|
| 392 | * @brief Update kea configuration |
---|
| 393 | * @note Route: /dhcp/save, Method: POST |
---|
| 394 | * @param string configurationText |
---|
| 395 | * @return string JSON object with all hosts in kea configuration |
---|
| 396 | */ |
---|
| 397 | |
---|
[7100d82] | 398 | $app->post('/dhcp/save', function () use ($app) { |
---|
| 399 | try { |
---|
| 400 | $input = json_decode($app->request()->getBody()); |
---|
| 401 | $configurationText = htmlspecialchars($input->configurationText); |
---|
| 402 | } catch (Exception $e) { |
---|
| 403 | $response["message"] = $e->getMessage(); |
---|
| 404 | jsonResponse(400, $response); |
---|
| 405 | $app->stop(); |
---|
| 406 | } |
---|
| 407 | |
---|
| 408 | $configurationParsed = str_replace(' ', '', $configurationText); |
---|
[deffac7] | 409 | $configurationParsed = str_replace("\n", '', $configurationParsed); |
---|
[7100d82] | 410 | $configurationParsed = str_replace('"', '"', $configurationParsed); |
---|
[deffac7] | 411 | $configuration = json_decode($configurationParsed); |
---|
| 412 | |
---|
[dd181cc] | 413 | if ($configuration === null || json_last_error() !== JSON_ERROR_NONE) { |
---|
[bec1753] | 414 | $responseError = "Error: El texto proporcionado no es un JSON válido."; |
---|
[7100d82] | 415 | jsonResponse(400, $responseError); |
---|
| 416 | } else { |
---|
| 417 | try { |
---|
[5727130] | 418 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
[7100d82] | 419 | if ($responseTest[0]["result"] == 0) { |
---|
| 420 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
[dd181cc] | 421 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
[5727130] | 422 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 423 | jsonResponse(400, $responseError); |
---|
[7100d82] | 424 | } else { |
---|
[5727130] | 425 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 426 | jsonResponse(200, $responseSuccess); |
---|
| 427 | } |
---|
[7100d82] | 428 | } else { |
---|
[5727130] | 429 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 430 | jsonResponse(400, $responseError); |
---|
[bec1753] | 431 | } |
---|
[7100d82] | 432 | } catch (Exception $e) { |
---|
| 433 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[bec1753] | 434 | jsonResponse(400, $responseError); |
---|
| 435 | } |
---|
[deffac7] | 436 | } |
---|
[b61fee8] | 437 | }); |
---|
[a8775ca] | 438 | |
---|
| 439 | |
---|
[7100d82] | 440 | $app->post( |
---|
| 441 | '/dhcp/add', |
---|
| 442 | function () use ($app) { |
---|
[a8775ca] | 443 | try { |
---|
[7100d82] | 444 | $input = json_decode($app->request()->getBody()); |
---|
| 445 | $host = htmlspecialchars($input->host); |
---|
| 446 | $macAddress = htmlspecialchars($input->macAddress); |
---|
| 447 | $address = htmlspecialchars($input->address); |
---|
| 448 | $nextServer = htmlspecialchars($input->nextServer); |
---|
[a8775ca] | 449 | } catch (Exception $e) { |
---|
[7100d82] | 450 | $response["message"] = $e->getMessage(); |
---|
| 451 | jsonResponse(400, $response); |
---|
| 452 | $app->stop(); |
---|
[a8775ca] | 453 | } |
---|
[7100d82] | 454 | try { |
---|
| 455 | $response = executeCurlCommand('config-get'); |
---|
| 456 | $nuevoHost = [ |
---|
| 457 | "hostname" => $host, |
---|
| 458 | "hw-address" => $macAddress, |
---|
| 459 | "ip-address" => $address, |
---|
| 460 | "next-server" => $nextServer |
---|
| 461 | ]; |
---|
| 462 | //En caso de que no esté declarado el array de reservations, lo inicializamos |
---|
| 463 | if (!isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 464 | $response[0]['arguments']['Dhcp4']['reservations'] = []; |
---|
[dd181cc] | 465 | } |
---|
[7100d82] | 466 | $existe = False; |
---|
| 467 | $existe = array_reduce($response[0]['arguments']['Dhcp4']['reservations'], function ($existe, $reserva) use ($host) { |
---|
| 468 | return $existe || ($reserva['hostname'] === $host); |
---|
| 469 | }); |
---|
| 470 | |
---|
| 471 | if ($existe) { |
---|
| 472 | $response = "Error: El host con el hostname '$host' ya existe en las reservaciones."; |
---|
| 473 | jsonResponse(400, $response); |
---|
| 474 | } else { |
---|
| 475 | $response[0]['arguments']['Dhcp4']['reservations'][] = $nuevoHost; |
---|
[dd181cc] | 476 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 477 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 478 | $configuration = json_decode($configurationParsed); |
---|
[7100d82] | 479 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
[deffac7] | 480 | |
---|
[7100d82] | 481 | if ($responseTest[0]["result"] == 0) { |
---|
| 482 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
[dd181cc] | 483 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
| 484 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 485 | jsonResponse(400, $responseError); |
---|
[7100d82] | 486 | } else { |
---|
[dd181cc] | 487 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 488 | jsonResponse(200, $responseSuccess); |
---|
| 489 | } |
---|
[7100d82] | 490 | } else { |
---|
| 491 | $responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; |
---|
[dd181cc] | 492 | jsonResponse(400, $responseError); |
---|
[bec1753] | 493 | } |
---|
[dd181cc] | 494 | } |
---|
[7100d82] | 495 | } catch (Exception $e) { |
---|
| 496 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[dd181cc] | 497 | jsonResponse(400, $responseError); |
---|
[7100d82] | 498 | } |
---|
[5727130] | 499 | } |
---|
[a8775ca] | 500 | ); |
---|
| 501 | |
---|
[dd181cc] | 502 | |
---|
[7100d82] | 503 | $app->post( |
---|
| 504 | '/dhcp/delete', |
---|
| 505 | function () use ($app) { |
---|
| 506 | try { |
---|
| 507 | $input = json_decode($app->request()->getBody()); |
---|
| 508 | $host = htmlspecialchars($input->host); |
---|
| 509 | } catch (Exception $e) { |
---|
| 510 | $response["message"] = $e->getMessage(); |
---|
| 511 | jsonResponse(400, $response); |
---|
| 512 | $app->stop(); |
---|
| 513 | } |
---|
| 514 | try { |
---|
| 515 | $response = executeCurlCommand('config-get'); |
---|
| 516 | $existe = False; |
---|
| 517 | |
---|
| 518 | if (isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 519 | foreach ($response[0]['arguments']['Dhcp4']['reservations'] as $key => $reservation) { |
---|
| 520 | if (isset($reservation['hostname']) && $reservation['hostname'] === $host) { |
---|
| 521 | unset($response[0]['arguments']['Dhcp4']['reservations'][$key]); |
---|
| 522 | $existe = True; |
---|
| 523 | $response[0]['arguments']['Dhcp4']['reservations'] = array_values($response[0]['arguments']['Dhcp4']['reservations']); |
---|
| 524 | break; |
---|
| 525 | } |
---|
| 526 | } |
---|
| 527 | if ($existe) { |
---|
[dd181cc] | 528 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 529 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 530 | $configuration = json_decode($configurationParsed); |
---|
[7100d82] | 531 | |
---|
| 532 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
| 533 | if ($response[0]["result"] == 0) { |
---|
| 534 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
| 535 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
[dd181cc] | 536 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 537 | jsonResponse(400, $responseError); |
---|
[7100d82] | 538 | } else { |
---|
[dd181cc] | 539 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 540 | jsonResponse(200, $responseSuccess); |
---|
| 541 | } |
---|
[7100d82] | 542 | } else { |
---|
[dd181cc] | 543 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 544 | jsonResponse(400, $responseError); |
---|
[bec1753] | 545 | } |
---|
[7100d82] | 546 | } else { |
---|
| 547 | $responseError = "Error: El host con el hostname '$host' no existe en las reservaciones."; |
---|
| 548 | jsonResponse(400, $responseError); |
---|
[dd181cc] | 549 | } |
---|
[7100d82] | 550 | } else { |
---|
| 551 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
[dd181cc] | 552 | jsonResponse(400, $responseError); |
---|
| 553 | } |
---|
[7100d82] | 554 | } catch (Exception $e) { |
---|
| 555 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[dd181cc] | 556 | jsonResponse(400, $responseError); |
---|
[7100d82] | 557 | } |
---|
| 558 | } |
---|
| 559 | ); |
---|
[eff870a] | 560 | |
---|
[7100d82] | 561 | $app->post( |
---|
| 562 | '/dhcp/update', |
---|
| 563 | function () use ($app) { |
---|
| 564 | try { |
---|
| 565 | $input = json_decode($app->request()->getBody()); |
---|
| 566 | $host = htmlspecialchars($input->host); |
---|
| 567 | $oldMacAddress = htmlspecialchars($input->oldMacAddress); |
---|
| 568 | $oldAddress = htmlspecialchars($input->oldAddress); |
---|
| 569 | $macAddress = htmlspecialchars($input->macAddress); |
---|
| 570 | $address = htmlspecialchars($input->address); |
---|
| 571 | $nextServer = htmlspecialchars($input->nextServer); |
---|
| 572 | } catch (Exception $e) { |
---|
| 573 | $response["message"] = $e->getMessage(); |
---|
| 574 | jsonResponse(400, $response); |
---|
| 575 | $app->stop(); |
---|
| 576 | } |
---|
| 577 | try { |
---|
| 578 | $response = executeCurlCommand('config-get'); |
---|
| 579 | $existe = False; |
---|
| 580 | if (isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 581 | foreach ($response[0]['arguments']['Dhcp4']['reservations'] as &$reservation) { |
---|
| 582 | if ($reservation['hw-address'] == $oldMacAddress && $reservation['ip-address'] == $oldAddress) { |
---|
| 583 | $existe = True; |
---|
| 584 | $reservation['hw-address'] = $macAddress; |
---|
| 585 | $reservation['ip-address'] = $address; |
---|
| 586 | $reservation['hostname'] = $host; |
---|
| 587 | $reservation['next-server'] = $nextServer; |
---|
| 588 | |
---|
| 589 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 590 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 591 | $configuration = json_decode($configurationParsed); |
---|
| 592 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
| 593 | |
---|
| 594 | if ($responseTest[0]["result"] == 0) { |
---|
| 595 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
| 596 | if ($responseSet == false && $responseSet[0]["result"] != 0) { |
---|
| 597 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 598 | jsonResponse(400, $responseError); |
---|
| 599 | } else { |
---|
| 600 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 601 | jsonResponse(200, $responseSuccess); |
---|
| 602 | } |
---|
| 603 | } else { |
---|
| 604 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 605 | jsonResponse(400, $responseError); |
---|
| 606 | } |
---|
| 607 | } |
---|
| 608 | } |
---|
| 609 | if (!$existe) { |
---|
| 610 | $responseError = "Error: La IP " . $oldAddress . " y la MAC " . $oldMacAddress . " no existe en las reservaciones."; |
---|
[eff870a] | 611 | |
---|
[7100d82] | 612 | jsonResponse(400, $responseError); |
---|
| 613 | } |
---|
| 614 | } else { |
---|
| 615 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
| 616 | jsonResponse(400, $responseError); |
---|
| 617 | } |
---|
| 618 | } catch (Exception $e) { |
---|
| 619 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
| 620 | jsonResponse(400, $responseError); |
---|
| 621 | } |
---|
| 622 | } |
---|
| 623 | ); |
---|
[f78659d] | 624 | |
---|
[7100d82] | 625 | $app->post( |
---|
| 626 | '/dhcp/apply', |
---|
| 627 | function () use ($app) { |
---|
[eff870a] | 628 | try { |
---|
[7100d82] | 629 | $response = executeCurlCommand('config-write'); |
---|
| 630 | if ($response[0]["result"] == 0) { |
---|
| 631 | jsonResponse(200, $response); |
---|
| 632 | } else { |
---|
[eff870a] | 633 | $responseError = "Error al escribir la configuración en Kea DHCP: " . $response[0]["text"]; |
---|
| 634 | jsonResponse(400, $responseError); |
---|
[7100d82] | 635 | } |
---|
[eff870a] | 636 | } catch (Exception $e) { |
---|
| 637 | $responseError = "Error al escribir la configuración en Kea DHCP: " . $e->getMessage(); |
---|
| 638 | jsonResponse(400, $responseError); |
---|
| 639 | } |
---|
[7100d82] | 640 | } |
---|
[eff870a] | 641 | ); |
---|
| 642 | |
---|
| 643 | |
---|
| 644 | |
---|
| 645 | /** |
---|
| 646 | * @brief Restore kea configuration. |
---|
| 647 | * @note Route: /dhcp/backup, Method: POST |
---|
| 648 | * @return string Result of operation. |
---|
| 649 | * @note All modifications in kea configuration is stored"/opt/opengnsys/etc/kea/backup" directory. |
---|
| 650 | */ |
---|
| 651 | |
---|
[7100d82] | 652 | $app->post('/dhcp/backup', function () use ($app) { |
---|
[eff870a] | 653 | $backup_dir = '/opt/opengnsys/etc/kea/backup'; |
---|
[7100d82] | 654 | try { |
---|
[dd181cc] | 655 | $backup_files = glob($backup_dir . '/*.conf'); |
---|
| 656 | if (empty($backup_files)) { |
---|
| 657 | $response = "No se encontraron archivos de backup"; |
---|
| 658 | jsonResponse(400, $response); |
---|
[7100d82] | 659 | } else { |
---|
| 660 | usort($backup_files, function ($a, $b) { |
---|
[dd181cc] | 661 | return filemtime($b) - filemtime($a); |
---|
| 662 | }); |
---|
| 663 | $backup_file = reset($backup_files); |
---|
| 664 | $config = file_get_contents($backup_file); |
---|
| 665 | $configuration = json_decode($config); |
---|
| 666 | |
---|
| 667 | $test_command = 'config-test'; |
---|
| 668 | $test_output = executeCurlCommand($test_command, $configuration); |
---|
| 669 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
| 670 | $responseError = "Error al comprobar la configuración de Kea: " . $test_output[0]["text"]; |
---|
| 671 | jsonResponse(400, $responseError); |
---|
[7100d82] | 672 | } else { |
---|
[dd181cc] | 673 | $set_command = 'config-set'; |
---|
| 674 | $set_output = executeCurlCommand($set_command, $configuration, false); |
---|
| 675 | if ($set_output == false || $set_output[0]["result"] != 0) { |
---|
| 676 | $responseError = "Error al guardar la última configuración de Kea: " . $set_output[0]["text"]; |
---|
| 677 | jsonResponse(400, $responseError); |
---|
[7100d82] | 678 | } else { |
---|
[dd181cc] | 679 | unlink($backup_file); |
---|
| 680 | $responseSuccess = "última configuración cargada correctamente"; |
---|
| 681 | jsonResponse(200, $responseSuccess); |
---|
| 682 | } |
---|
| 683 | } |
---|
| 684 | } |
---|
[7100d82] | 685 | } catch (Exception $e) { |
---|
| 686 | $responseError = "Error al restaurar la configuración: " . $e->getMessage(); |
---|
[dd181cc] | 687 | jsonResponse(400, $responseError); |
---|
[7100d82] | 688 | } |
---|
[eff870a] | 689 | }); |
---|
| 690 | |
---|
| 691 | |
---|
| 692 | |
---|
| 693 | /** |
---|
| 694 | * @brief Upload kea configuration file. |
---|
| 695 | * @note Route: /dhcp/upload, Method: POST |
---|
| 696 | * @param File file. |
---|
| 697 | * @return string Route of stored file. |
---|
| 698 | */ |
---|
| 699 | |
---|
[7100d82] | 700 | $app->post('/dhcp/upload', function () use ($app) { |
---|
[eff870a] | 701 | if (!isset($_FILES['file_input_name'])) { |
---|
[7100d82] | 702 | $responseError = "No se ha subido ningún archivo"; |
---|
| 703 | jsonResponse(400, $responseError); |
---|
[eff870a] | 704 | return; |
---|
| 705 | } |
---|
| 706 | |
---|
| 707 | $file_path = $_FILES['file_input_name']['tmp_name']; |
---|
| 708 | $json_data = file_get_contents($file_path); |
---|
| 709 | $config_data = json_decode($json_data, true); |
---|
| 710 | if (json_last_error() !== JSON_ERROR_NONE) { |
---|
[7100d82] | 711 | $responseError = "El archivo JSON subido no está correctamente escrito"; |
---|
| 712 | jsonResponse(400, $responseError); |
---|
[eff870a] | 713 | } |
---|
[7100d82] | 714 | try { |
---|
| 715 | $test_command = 'config-test'; |
---|
| 716 | $test_output = executeCurlCommand($test_command, $config_data); |
---|
[dd181cc] | 717 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
[7100d82] | 718 | $responseError = "La configuración no es válida"; |
---|
[eff870a] | 719 | jsonResponse(400, $responseError); |
---|
[7100d82] | 720 | } else { |
---|
| 721 | $set_command = 'config-set'; |
---|
| 722 | $set_output = executeCurlCommand($set_command, $config_data); |
---|
| 723 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
| 724 | $responseError = "Error al guardar la configuración en Kea DHCP"; |
---|
| 725 | jsonResponse(400, $responseError); |
---|
| 726 | http_response_code(400); |
---|
| 727 | } else { |
---|
| 728 | $responseSuccess = "Configuración cargada correctamente en el fichero: " . $file_path;; |
---|
| 729 | jsonResponse(200, $responseSuccess); |
---|
| 730 | http_response_code(200); |
---|
| 731 | } |
---|
[eff870a] | 732 | } |
---|
[7100d82] | 733 | } catch (Exception $e) { |
---|
| 734 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 735 | jsonResponse(400, $responseError); |
---|
| 736 | } |
---|
[eff870a] | 737 | }); |
---|
[f78659d] | 738 | |
---|
| 739 | |
---|
| 740 | |
---|
| 741 | |
---|
[3551804] | 742 | /** |
---|
| 743 | * @brief Get the server status |
---|
| 744 | * @note Route: /status, Method: GET |
---|
[195753c] | 745 | * @return string JSON object with all data collected from server status (RAM, %CPU, etc.). |
---|
[3551804] | 746 | */ |
---|
[7100d82] | 747 | $app->get( |
---|
| 748 | '/status', |
---|
| 749 | function () { |
---|
| 750 | $response = []; |
---|
| 751 | // Getting memory and CPU information. |
---|
| 752 | exec("awk '$1~/Mem/ {print $2}' /proc/meminfo", $memInfo); |
---|
| 753 | $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]); |
---|
| 754 | $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat"); |
---|
| 755 | $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo"); |
---|
| 756 | $response["memInfo"] = $memInfo; |
---|
| 757 | $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo); |
---|
| 758 | jsonResponse(200, $response); |
---|
| 759 | } |
---|
[3551804] | 760 | ); |
---|