[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) { |
---|
[a5d23af] | 188 | $max_body_len_to_log = 150; |
---|
[7100d82] | 189 | if ($app->response->getStatus() != 200) { |
---|
| 190 | // Compose error message (truncating long lines). |
---|
| 191 | $app->log->error(date(DATE_ISO8601) . ': ' . |
---|
| 192 | $app->getName() . ': ' . |
---|
| 193 | $_SERVER['REMOTE_ADDR'] . ": " . |
---|
| 194 | (isset($userid) ? $userid : "-") . ": " . |
---|
| 195 | $app->response->getStatus() . ': ' . |
---|
| 196 | $app->request->getMethod() . ' ' . |
---|
| 197 | $app->request->getPathInfo() . ': ' . |
---|
| 198 | substr($app->response->getBody(), 0, 100)); |
---|
| 199 | } |
---|
[a5d23af] | 200 | if ($app->settings['debug']) { |
---|
| 201 | $body = $app->response->getBody(); |
---|
| 202 | if (strlen($body) > $max_body_len_to_log) { |
---|
| 203 | $body = substr($body, 0, $max_body_len_to_log) . '... (output has been truncated)'; |
---|
| 204 | } |
---|
| 205 | writeRestLog($body); |
---|
| 206 | } |
---|
[7100d82] | 207 | } |
---|
[1ab1b31d] | 208 | ); |
---|
| 209 | |
---|
| 210 | |
---|
[3551804] | 211 | // Common routes. |
---|
| 212 | |
---|
| 213 | /** |
---|
| 214 | * @brief Get general server information |
---|
| 215 | * @note Route: /info, Method: GET |
---|
[195753c] | 216 | * @return string JSON object with basic server information (version, services, etc.) |
---|
[3551804] | 217 | */ |
---|
[7100d82] | 218 | $app->get( |
---|
| 219 | '/info', |
---|
| 220 | function () { |
---|
| 221 | $hasOglive = false; |
---|
| 222 | $response = new \stdClass; |
---|
| 223 | // Reading version file. |
---|
| 224 | $data = json_decode(@file_get_contents(VERSION_FILE)); |
---|
| 225 | if (isset($data->project)) { |
---|
| 226 | $response = $data; |
---|
| 227 | } else { |
---|
| 228 | $response->project = 'OpenGnsys'; |
---|
| 229 | } |
---|
| 230 | // Getting actived services. |
---|
| 231 | @$services = parse_ini_file('/etc/default/opengnsys'); |
---|
| 232 | $response->services = []; |
---|
| 233 | if (@$services["RUN_OGADMSERVER"] === "yes") { |
---|
| 234 | array_push($response->services, "server"); |
---|
| 235 | $hasOglive = true; |
---|
| 236 | } |
---|
| 237 | if (@$services["RUN_OGADMREPO"] === "yes") array_push($response->services, "repository"); |
---|
| 238 | if (@$services["RUN_BTTRACKER"] === "yes") array_push($response->services, "tracker"); |
---|
| 239 | // Reading installed ogLive information file. |
---|
| 240 | if ($hasOglive === true) { |
---|
| 241 | $data = json_decode(@file_get_contents('/opt/opengnsys/etc/ogliveinfo.json')); |
---|
| 242 | if (isset($data->oglive)) { |
---|
| 243 | $response->oglive = $data->oglive; |
---|
| 244 | } |
---|
| 245 | } |
---|
| 246 | jsonResponse(200, $response); |
---|
| 247 | } |
---|
[3551804] | 248 | ); |
---|
| 249 | |
---|
[c069a28] | 250 | |
---|
[7100d82] | 251 | function backupConfig() |
---|
| 252 | { |
---|
[c069a28] | 253 | $get_command = 'config-get'; |
---|
| 254 | $get_output = executeCurlCommand($get_command); |
---|
[dd181cc] | 255 | if ($get_output == false || $get_output[0]["result"] != 0) { |
---|
[c069a28] | 256 | throw new Exception('Error al obtener la configuración actual de Kea DHCP'); |
---|
| 257 | } |
---|
[7100d82] | 258 | $config_text = json_encode($get_output[0]['arguments']); |
---|
| 259 | $configurationParsed = str_replace('\\', '', $config_text); |
---|
[c069a28] | 260 | |
---|
| 261 | $backup_dir = '/opt/opengnsys/etc/kea/backup'; |
---|
[5727130] | 262 | if (!is_dir($backup_dir)) { |
---|
| 263 | throw new Exception('El directorio de backup no existe'); |
---|
| 264 | } |
---|
| 265 | if (!is_writable($backup_dir)) { |
---|
| 266 | throw new Exception('El directorio de backup no tiene permisos de escritura'); |
---|
| 267 | } |
---|
[c069a28] | 268 | $backup_files = glob($backup_dir . '/*.conf'); |
---|
| 269 | if (count($backup_files) >= 10) { |
---|
[7100d82] | 270 | usort($backup_files, function ($a, $b) { |
---|
[c069a28] | 271 | return filemtime($a) - filemtime($b); |
---|
| 272 | }); |
---|
| 273 | unlink($backup_files[0]); |
---|
| 274 | } |
---|
| 275 | $backup_file = $backup_dir . '/' . date('Y-m-d_H-i-s') . '.conf'; |
---|
| 276 | if (!file_put_contents($backup_file, $configurationParsed)) { |
---|
| 277 | throw new Exception('Error al guardar la configuración de backup'); |
---|
| 278 | } |
---|
| 279 | } |
---|
| 280 | |
---|
[7100d82] | 281 | function executeCurlCommand($command, $arguments = null, $create_backup = true) |
---|
| 282 | { |
---|
[dd181cc] | 283 | $apiUrl = getenv('DHCP_IP'); |
---|
| 284 | if (!$apiUrl) { |
---|
| 285 | $apiUrl = 'http://localhost:8000/'; |
---|
[d7c02f4] | 286 | } |
---|
| 287 | |
---|
[99cefa0] | 288 | if ($command == 'config-get' || $command == 'config-write') { |
---|
[b61fee8] | 289 | $requestData = array( |
---|
| 290 | 'command' => $command, |
---|
| 291 | 'service' => array('dhcp4'), |
---|
| 292 | ); |
---|
| 293 | } elseif ($command == 'config-set' || $command == 'config-test') { |
---|
| 294 | $requestData = array( |
---|
| 295 | 'command' => $command, |
---|
| 296 | 'service' => array('dhcp4'), |
---|
| 297 | 'arguments' => $arguments, |
---|
| 298 | ); |
---|
| 299 | } else { |
---|
| 300 | return "Error: Comando no válido"; |
---|
| 301 | } |
---|
[7100d82] | 302 | if (($command == 'config-set' || $command == 'config-write') && $create_backup) { |
---|
| 303 | backupConfig(); |
---|
| 304 | } |
---|
[b61fee8] | 305 | $jsonData = json_encode($requestData); |
---|
[7100d82] | 306 | try { |
---|
[0eb2e98] | 307 | $ch = curl_init(); |
---|
| 308 | curl_setopt($ch, CURLOPT_URL, $apiUrl); |
---|
| 309 | curl_setopt($ch, CURLOPT_POST, 1); |
---|
| 310 | curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); |
---|
| 311 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
---|
[a4f75938] | 312 | curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:')); |
---|
[0eb2e98] | 313 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); |
---|
| 314 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
---|
[7d49912] | 315 | curl_setopt($ch, CURLOPT_TIMEOUT, 10); |
---|
[7100d82] | 316 | curl_setopt($ch, CURLOPT_POST, true); |
---|
[0eb2e98] | 317 | $response = curl_exec($ch); |
---|
| 318 | $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
---|
| 319 | $output = json_decode($response, true); |
---|
[b61fee8] | 320 | |
---|
[0eb2e98] | 321 | if ($httpCode >= 200 && $httpCode < 300) { |
---|
[d7c02f4] | 322 | |
---|
[7100d82] | 323 | return $output; |
---|
[0eb2e98] | 324 | } else { |
---|
[7d49912] | 325 | $error = curl_error($ch); |
---|
| 326 | throw new Exception($error); |
---|
| 327 | //return false; |
---|
[0eb2e98] | 328 | } |
---|
| 329 | } catch (Exception $e) { |
---|
[7d49912] | 330 | throw new Exception($e->getMessage()); |
---|
[a8775ca] | 331 | } |
---|
| 332 | } |
---|
| 333 | |
---|
[f78659d] | 334 | |
---|
| 335 | /** |
---|
[bec1753] | 336 | * @brief Get configuration of kea dhcp server |
---|
| 337 | * @note Route: /dhcp, Method: GET |
---|
| 338 | * @return string JSON object with all kea configuration |
---|
[f78659d] | 339 | */ |
---|
[7100d82] | 340 | $app->get('/dhcp', function () { |
---|
| 341 | try { |
---|
[5727130] | 342 | $response = executeCurlCommand('config-get'); |
---|
[f78659d] | 343 | |
---|
[7100d82] | 344 | if (!$response) { |
---|
[5727130] | 345 | $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf'; |
---|
[bec1753] | 346 | jsonResponse(400, $responseError); |
---|
[7100d82] | 347 | } else { |
---|
[5727130] | 348 | $result_code = $response[0]["result"]; |
---|
[7100d82] | 349 | if ($result_code == 0) { |
---|
[5727130] | 350 | $arrayDhcp4 = $response[0]['arguments']; |
---|
[7100d82] | 351 | jsonResponse(200, $arrayDhcp4, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
---|
| 352 | } else { |
---|
| 353 | $responseError = "Error kea configuration invalid: " . $response[0]["text"]; |
---|
[5727130] | 354 | jsonResponse(400, $responseError); |
---|
| 355 | } |
---|
[a8775ca] | 356 | } |
---|
[7100d82] | 357 | } catch (Exception $e) { |
---|
| 358 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 359 | jsonResponse(400, $responseError); |
---|
[7100d82] | 360 | } |
---|
[a8775ca] | 361 | }); |
---|
[8a00e28] | 362 | |
---|
[bec1753] | 363 | /** |
---|
| 364 | * @brief Get hosts from kea configuration |
---|
| 365 | * @note Route: /dhcp/hosts, Method: GET |
---|
| 366 | * @return string JSON object with all hosts in kea configuration |
---|
| 367 | */ |
---|
| 368 | |
---|
[7100d82] | 369 | $app->get('/dhcp/hosts', function () { |
---|
| 370 | try { |
---|
| 371 | $response = executeCurlCommand('config-get'); |
---|
[8a00e28] | 372 | |
---|
[7100d82] | 373 | if (!$response) { |
---|
[5727130] | 374 | $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf'; |
---|
| 375 | jsonResponse(400, $response); |
---|
[7100d82] | 376 | } else { |
---|
[5727130] | 377 | $result_code = $response[0]["result"]; |
---|
[7100d82] | 378 | if ($result_code == 0) { |
---|
[dd181cc] | 379 | if (!isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 380 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
| 381 | jsonResponse(400, $responseError); |
---|
| 382 | } else { |
---|
| 383 | $arrayReservations = $response[0]['arguments']['Dhcp4']['reservations']; |
---|
| 384 | jsonResponse(200, $arrayReservations, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
---|
| 385 | } |
---|
[7100d82] | 386 | } else { |
---|
| 387 | $responseError = "Error kea configuration invalid: " . $response[0]["text"]; |
---|
[5727130] | 388 | jsonResponse(400, $responseError); |
---|
| 389 | } |
---|
[7100d82] | 390 | } |
---|
| 391 | } catch (Exception $e) { |
---|
| 392 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 393 | jsonResponse(400, $responseError); |
---|
| 394 | } |
---|
[a8775ca] | 395 | }); |
---|
[8a00e28] | 396 | |
---|
[bec1753] | 397 | /** |
---|
| 398 | * @brief Update kea configuration |
---|
| 399 | * @note Route: /dhcp/save, Method: POST |
---|
| 400 | * @param string configurationText |
---|
| 401 | * @return string JSON object with all hosts in kea configuration |
---|
| 402 | */ |
---|
| 403 | |
---|
[7100d82] | 404 | $app->post('/dhcp/save', function () use ($app) { |
---|
| 405 | try { |
---|
| 406 | $input = json_decode($app->request()->getBody()); |
---|
| 407 | $configurationText = htmlspecialchars($input->configurationText); |
---|
| 408 | } catch (Exception $e) { |
---|
| 409 | $response["message"] = $e->getMessage(); |
---|
| 410 | jsonResponse(400, $response); |
---|
| 411 | $app->stop(); |
---|
| 412 | } |
---|
| 413 | |
---|
| 414 | $configurationParsed = str_replace(' ', '', $configurationText); |
---|
[deffac7] | 415 | $configurationParsed = str_replace("\n", '', $configurationParsed); |
---|
[7100d82] | 416 | $configurationParsed = str_replace('"', '"', $configurationParsed); |
---|
[deffac7] | 417 | $configuration = json_decode($configurationParsed); |
---|
| 418 | |
---|
[dd181cc] | 419 | if ($configuration === null || json_last_error() !== JSON_ERROR_NONE) { |
---|
[bec1753] | 420 | $responseError = "Error: El texto proporcionado no es un JSON válido."; |
---|
[7100d82] | 421 | jsonResponse(400, $responseError); |
---|
| 422 | } else { |
---|
| 423 | try { |
---|
[5727130] | 424 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
[7100d82] | 425 | if ($responseTest[0]["result"] == 0) { |
---|
| 426 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
[dd181cc] | 427 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
[5727130] | 428 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 429 | jsonResponse(400, $responseError); |
---|
[7100d82] | 430 | } else { |
---|
[5727130] | 431 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 432 | jsonResponse(200, $responseSuccess); |
---|
| 433 | } |
---|
[7100d82] | 434 | } else { |
---|
[5727130] | 435 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 436 | jsonResponse(400, $responseError); |
---|
[bec1753] | 437 | } |
---|
[7100d82] | 438 | } catch (Exception $e) { |
---|
| 439 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[bec1753] | 440 | jsonResponse(400, $responseError); |
---|
| 441 | } |
---|
[deffac7] | 442 | } |
---|
[b61fee8] | 443 | }); |
---|
[a8775ca] | 444 | |
---|
| 445 | |
---|
[7100d82] | 446 | $app->post( |
---|
| 447 | '/dhcp/add', |
---|
| 448 | function () use ($app) { |
---|
[a8775ca] | 449 | try { |
---|
[7100d82] | 450 | $input = json_decode($app->request()->getBody()); |
---|
| 451 | $host = htmlspecialchars($input->host); |
---|
| 452 | $macAddress = htmlspecialchars($input->macAddress); |
---|
| 453 | $address = htmlspecialchars($input->address); |
---|
| 454 | $nextServer = htmlspecialchars($input->nextServer); |
---|
[a8775ca] | 455 | } catch (Exception $e) { |
---|
[7100d82] | 456 | $response["message"] = $e->getMessage(); |
---|
| 457 | jsonResponse(400, $response); |
---|
| 458 | $app->stop(); |
---|
[a8775ca] | 459 | } |
---|
[7100d82] | 460 | try { |
---|
| 461 | $response = executeCurlCommand('config-get'); |
---|
| 462 | $nuevoHost = [ |
---|
| 463 | "hostname" => $host, |
---|
| 464 | "hw-address" => $macAddress, |
---|
| 465 | "ip-address" => $address, |
---|
| 466 | "next-server" => $nextServer |
---|
| 467 | ]; |
---|
| 468 | //En caso de que no esté declarado el array de reservations, lo inicializamos |
---|
| 469 | if (!isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 470 | $response[0]['arguments']['Dhcp4']['reservations'] = []; |
---|
[dd181cc] | 471 | } |
---|
[7100d82] | 472 | $existe = False; |
---|
| 473 | $existe = array_reduce($response[0]['arguments']['Dhcp4']['reservations'], function ($existe, $reserva) use ($host) { |
---|
| 474 | return $existe || ($reserva['hostname'] === $host); |
---|
| 475 | }); |
---|
| 476 | |
---|
| 477 | if ($existe) { |
---|
| 478 | $response = "Error: El host con el hostname '$host' ya existe en las reservaciones."; |
---|
| 479 | jsonResponse(400, $response); |
---|
| 480 | } else { |
---|
| 481 | $response[0]['arguments']['Dhcp4']['reservations'][] = $nuevoHost; |
---|
[dd181cc] | 482 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 483 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 484 | $configuration = json_decode($configurationParsed); |
---|
[7100d82] | 485 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
[deffac7] | 486 | |
---|
[7100d82] | 487 | if ($responseTest[0]["result"] == 0) { |
---|
| 488 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
[dd181cc] | 489 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
| 490 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 491 | jsonResponse(400, $responseError); |
---|
[7100d82] | 492 | } else { |
---|
[dd181cc] | 493 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 494 | jsonResponse(200, $responseSuccess); |
---|
| 495 | } |
---|
[7100d82] | 496 | } else { |
---|
| 497 | $responseError = "Error kea configuration invalid: " . $responseTest[0]["text"]; |
---|
[dd181cc] | 498 | jsonResponse(400, $responseError); |
---|
[bec1753] | 499 | } |
---|
[dd181cc] | 500 | } |
---|
[7100d82] | 501 | } catch (Exception $e) { |
---|
| 502 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[dd181cc] | 503 | jsonResponse(400, $responseError); |
---|
[7100d82] | 504 | } |
---|
[5727130] | 505 | } |
---|
[a8775ca] | 506 | ); |
---|
| 507 | |
---|
[dd181cc] | 508 | |
---|
[7100d82] | 509 | $app->post( |
---|
| 510 | '/dhcp/delete', |
---|
| 511 | function () use ($app) { |
---|
| 512 | try { |
---|
| 513 | $input = json_decode($app->request()->getBody()); |
---|
| 514 | $host = htmlspecialchars($input->host); |
---|
| 515 | } catch (Exception $e) { |
---|
| 516 | $response["message"] = $e->getMessage(); |
---|
| 517 | jsonResponse(400, $response); |
---|
| 518 | $app->stop(); |
---|
| 519 | } |
---|
| 520 | try { |
---|
| 521 | $response = executeCurlCommand('config-get'); |
---|
| 522 | $existe = False; |
---|
| 523 | |
---|
| 524 | if (isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 525 | foreach ($response[0]['arguments']['Dhcp4']['reservations'] as $key => $reservation) { |
---|
| 526 | if (isset($reservation['hostname']) && $reservation['hostname'] === $host) { |
---|
| 527 | unset($response[0]['arguments']['Dhcp4']['reservations'][$key]); |
---|
| 528 | $existe = True; |
---|
| 529 | $response[0]['arguments']['Dhcp4']['reservations'] = array_values($response[0]['arguments']['Dhcp4']['reservations']); |
---|
| 530 | break; |
---|
| 531 | } |
---|
| 532 | } |
---|
| 533 | if ($existe) { |
---|
[dd181cc] | 534 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 535 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 536 | $configuration = json_decode($configurationParsed); |
---|
[7100d82] | 537 | |
---|
| 538 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
| 539 | if ($response[0]["result"] == 0) { |
---|
| 540 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
| 541 | if ($responseSet == false || $responseSet[0]["result"] != 0) { |
---|
[dd181cc] | 542 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 543 | jsonResponse(400, $responseError); |
---|
[7100d82] | 544 | } else { |
---|
[dd181cc] | 545 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 546 | jsonResponse(200, $responseSuccess); |
---|
| 547 | } |
---|
[7100d82] | 548 | } else { |
---|
[dd181cc] | 549 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 550 | jsonResponse(400, $responseError); |
---|
[bec1753] | 551 | } |
---|
[7100d82] | 552 | } else { |
---|
| 553 | $responseError = "Error: El host con el hostname '$host' no existe en las reservaciones."; |
---|
| 554 | jsonResponse(400, $responseError); |
---|
[dd181cc] | 555 | } |
---|
[7100d82] | 556 | } else { |
---|
| 557 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
[dd181cc] | 558 | jsonResponse(400, $responseError); |
---|
| 559 | } |
---|
[7100d82] | 560 | } catch (Exception $e) { |
---|
| 561 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[dd181cc] | 562 | jsonResponse(400, $responseError); |
---|
[7100d82] | 563 | } |
---|
| 564 | } |
---|
| 565 | ); |
---|
[eff870a] | 566 | |
---|
[7100d82] | 567 | $app->post( |
---|
| 568 | '/dhcp/update', |
---|
| 569 | function () use ($app) { |
---|
| 570 | try { |
---|
| 571 | $input = json_decode($app->request()->getBody()); |
---|
| 572 | $host = htmlspecialchars($input->host); |
---|
| 573 | $oldMacAddress = htmlspecialchars($input->oldMacAddress); |
---|
| 574 | $oldAddress = htmlspecialchars($input->oldAddress); |
---|
| 575 | $macAddress = htmlspecialchars($input->macAddress); |
---|
| 576 | $address = htmlspecialchars($input->address); |
---|
| 577 | $nextServer = htmlspecialchars($input->nextServer); |
---|
| 578 | } catch (Exception $e) { |
---|
| 579 | $response["message"] = $e->getMessage(); |
---|
| 580 | jsonResponse(400, $response); |
---|
| 581 | $app->stop(); |
---|
| 582 | } |
---|
| 583 | try { |
---|
| 584 | $response = executeCurlCommand('config-get'); |
---|
| 585 | $existe = False; |
---|
| 586 | if (isset($response[0]['arguments']['Dhcp4']['reservations'])) { |
---|
| 587 | foreach ($response[0]['arguments']['Dhcp4']['reservations'] as &$reservation) { |
---|
| 588 | if ($reservation['hw-address'] == $oldMacAddress && $reservation['ip-address'] == $oldAddress) { |
---|
| 589 | $existe = True; |
---|
| 590 | $reservation['hw-address'] = $macAddress; |
---|
| 591 | $reservation['ip-address'] = $address; |
---|
| 592 | $reservation['hostname'] = $host; |
---|
| 593 | $reservation['next-server'] = $nextServer; |
---|
| 594 | |
---|
| 595 | $array_encoded = json_encode($response[0]['arguments']); |
---|
| 596 | $configurationParsed = str_replace('\\', '', $array_encoded); |
---|
| 597 | $configuration = json_decode($configurationParsed); |
---|
| 598 | $responseTest = executeCurlCommand('config-test', $configuration); |
---|
| 599 | |
---|
| 600 | if ($responseTest[0]["result"] == 0) { |
---|
| 601 | $responseSet = executeCurlCommand('config-set', $configuration); |
---|
| 602 | if ($responseSet == false && $responseSet[0]["result"] != 0) { |
---|
| 603 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; |
---|
| 604 | jsonResponse(400, $responseError); |
---|
| 605 | } else { |
---|
| 606 | $responseSuccess = "Configuración cargada correctamente"; |
---|
| 607 | jsonResponse(200, $responseSuccess); |
---|
| 608 | } |
---|
| 609 | } else { |
---|
| 610 | $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"]; |
---|
| 611 | jsonResponse(400, $responseError); |
---|
| 612 | } |
---|
| 613 | } |
---|
| 614 | } |
---|
| 615 | if (!$existe) { |
---|
| 616 | $responseError = "Error: La IP " . $oldAddress . " y la MAC " . $oldMacAddress . " no existe en las reservaciones."; |
---|
[eff870a] | 617 | |
---|
[7100d82] | 618 | jsonResponse(400, $responseError); |
---|
| 619 | } |
---|
| 620 | } else { |
---|
| 621 | $responseError = 'El campo \'reservations\' no está inicializado'; |
---|
| 622 | jsonResponse(400, $responseError); |
---|
| 623 | } |
---|
| 624 | } catch (Exception $e) { |
---|
| 625 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
| 626 | jsonResponse(400, $responseError); |
---|
| 627 | } |
---|
| 628 | } |
---|
| 629 | ); |
---|
[f78659d] | 630 | |
---|
[7100d82] | 631 | $app->post( |
---|
| 632 | '/dhcp/apply', |
---|
| 633 | function () use ($app) { |
---|
[eff870a] | 634 | try { |
---|
[7100d82] | 635 | $response = executeCurlCommand('config-write'); |
---|
| 636 | if ($response[0]["result"] == 0) { |
---|
| 637 | jsonResponse(200, $response); |
---|
| 638 | } else { |
---|
[eff870a] | 639 | $responseError = "Error al escribir la configuración en Kea DHCP: " . $response[0]["text"]; |
---|
| 640 | jsonResponse(400, $responseError); |
---|
[7100d82] | 641 | } |
---|
[eff870a] | 642 | } catch (Exception $e) { |
---|
| 643 | $responseError = "Error al escribir la configuración en Kea DHCP: " . $e->getMessage(); |
---|
| 644 | jsonResponse(400, $responseError); |
---|
| 645 | } |
---|
[7100d82] | 646 | } |
---|
[eff870a] | 647 | ); |
---|
| 648 | |
---|
| 649 | |
---|
| 650 | |
---|
| 651 | /** |
---|
| 652 | * @brief Restore kea configuration. |
---|
| 653 | * @note Route: /dhcp/backup, Method: POST |
---|
| 654 | * @return string Result of operation. |
---|
| 655 | * @note All modifications in kea configuration is stored"/opt/opengnsys/etc/kea/backup" directory. |
---|
| 656 | */ |
---|
| 657 | |
---|
[7100d82] | 658 | $app->post('/dhcp/backup', function () use ($app) { |
---|
[eff870a] | 659 | $backup_dir = '/opt/opengnsys/etc/kea/backup'; |
---|
[7100d82] | 660 | try { |
---|
[dd181cc] | 661 | $backup_files = glob($backup_dir . '/*.conf'); |
---|
| 662 | if (empty($backup_files)) { |
---|
| 663 | $response = "No se encontraron archivos de backup"; |
---|
| 664 | jsonResponse(400, $response); |
---|
[7100d82] | 665 | } else { |
---|
| 666 | usort($backup_files, function ($a, $b) { |
---|
[dd181cc] | 667 | return filemtime($b) - filemtime($a); |
---|
| 668 | }); |
---|
| 669 | $backup_file = reset($backup_files); |
---|
| 670 | $config = file_get_contents($backup_file); |
---|
| 671 | $configuration = json_decode($config); |
---|
| 672 | |
---|
| 673 | $test_command = 'config-test'; |
---|
| 674 | $test_output = executeCurlCommand($test_command, $configuration); |
---|
| 675 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
| 676 | $responseError = "Error al comprobar la configuración de Kea: " . $test_output[0]["text"]; |
---|
| 677 | jsonResponse(400, $responseError); |
---|
[7100d82] | 678 | } else { |
---|
[dd181cc] | 679 | $set_command = 'config-set'; |
---|
| 680 | $set_output = executeCurlCommand($set_command, $configuration, false); |
---|
| 681 | if ($set_output == false || $set_output[0]["result"] != 0) { |
---|
| 682 | $responseError = "Error al guardar la última configuración de Kea: " . $set_output[0]["text"]; |
---|
| 683 | jsonResponse(400, $responseError); |
---|
[7100d82] | 684 | } else { |
---|
[dd181cc] | 685 | unlink($backup_file); |
---|
| 686 | $responseSuccess = "última configuración cargada correctamente"; |
---|
| 687 | jsonResponse(200, $responseSuccess); |
---|
| 688 | } |
---|
| 689 | } |
---|
| 690 | } |
---|
[7100d82] | 691 | } catch (Exception $e) { |
---|
| 692 | $responseError = "Error al restaurar la configuración: " . $e->getMessage(); |
---|
[dd181cc] | 693 | jsonResponse(400, $responseError); |
---|
[7100d82] | 694 | } |
---|
[eff870a] | 695 | }); |
---|
| 696 | |
---|
| 697 | |
---|
| 698 | |
---|
| 699 | /** |
---|
| 700 | * @brief Upload kea configuration file. |
---|
| 701 | * @note Route: /dhcp/upload, Method: POST |
---|
| 702 | * @param File file. |
---|
| 703 | * @return string Route of stored file. |
---|
| 704 | */ |
---|
| 705 | |
---|
[7100d82] | 706 | $app->post('/dhcp/upload', function () use ($app) { |
---|
[eff870a] | 707 | if (!isset($_FILES['file_input_name'])) { |
---|
[7100d82] | 708 | $responseError = "No se ha subido ningún archivo"; |
---|
| 709 | jsonResponse(400, $responseError); |
---|
[eff870a] | 710 | return; |
---|
| 711 | } |
---|
| 712 | |
---|
| 713 | $file_path = $_FILES['file_input_name']['tmp_name']; |
---|
| 714 | $json_data = file_get_contents($file_path); |
---|
| 715 | $config_data = json_decode($json_data, true); |
---|
| 716 | if (json_last_error() !== JSON_ERROR_NONE) { |
---|
[7100d82] | 717 | $responseError = "El archivo JSON subido no está correctamente escrito"; |
---|
| 718 | jsonResponse(400, $responseError); |
---|
[eff870a] | 719 | } |
---|
[7100d82] | 720 | try { |
---|
| 721 | $test_command = 'config-test'; |
---|
| 722 | $test_output = executeCurlCommand($test_command, $config_data); |
---|
[dd181cc] | 723 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
[7100d82] | 724 | $responseError = "La configuración no es válida"; |
---|
[eff870a] | 725 | jsonResponse(400, $responseError); |
---|
[7100d82] | 726 | } else { |
---|
| 727 | $set_command = 'config-set'; |
---|
| 728 | $set_output = executeCurlCommand($set_command, $config_data); |
---|
| 729 | if ($test_output == false || $test_output[0]["result"] != 0) { |
---|
| 730 | $responseError = "Error al guardar la configuración en Kea DHCP"; |
---|
| 731 | jsonResponse(400, $responseError); |
---|
| 732 | http_response_code(400); |
---|
| 733 | } else { |
---|
| 734 | $responseSuccess = "Configuración cargada correctamente en el fichero: " . $file_path;; |
---|
| 735 | jsonResponse(200, $responseSuccess); |
---|
| 736 | http_response_code(200); |
---|
| 737 | } |
---|
[eff870a] | 738 | } |
---|
[7100d82] | 739 | } catch (Exception $e) { |
---|
| 740 | $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); |
---|
[5727130] | 741 | jsonResponse(400, $responseError); |
---|
| 742 | } |
---|
[eff870a] | 743 | }); |
---|
[f78659d] | 744 | |
---|
| 745 | |
---|
| 746 | |
---|
| 747 | |
---|
[3551804] | 748 | /** |
---|
| 749 | * @brief Get the server status |
---|
| 750 | * @note Route: /status, Method: GET |
---|
[195753c] | 751 | * @return string JSON object with all data collected from server status (RAM, %CPU, etc.). |
---|
[3551804] | 752 | */ |
---|
[7100d82] | 753 | $app->get( |
---|
| 754 | '/status', |
---|
| 755 | function () { |
---|
| 756 | $response = []; |
---|
| 757 | // Getting memory and CPU information. |
---|
| 758 | exec("awk '$1~/Mem/ {print $2}' /proc/meminfo", $memInfo); |
---|
| 759 | $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]); |
---|
| 760 | $cpuInfo = exec("awk '$1==\"cpu\" {printf \"%.2f\",($2+$4)*100/($2+$4+$5)}' /proc/stat"); |
---|
| 761 | $cpuModel = exec("awk -F: '$1~/model name/ {print $2}' /proc/cpuinfo"); |
---|
| 762 | $response["memInfo"] = $memInfo; |
---|
| 763 | $response["cpu"] = array("model" => trim($cpuModel), "usage" => $cpuInfo); |
---|
| 764 | jsonResponse(200, $response); |
---|
| 765 | } |
---|
[3551804] | 766 | ); |
---|