source: admin/WebConsole/rest/common.php @ 72345b5

configure-oglivelgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 72345b5 was 7100d82, checked in by lgromero <lgromero@…>, 17 months ago

Index document

  • Property mode set to 100644
File size: 28.8 KB
Line 
1<?php
2
3/**
4 * @file    index.php
5 * @brief   OpenGnsys REST API: common functions and routes
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
15// Common constants.
16define('REST_LOGFILE', '/opt/opengnsys/log/rest.log');
17define('VERSION_FILE', '/opt/opengnsys/doc/VERSION.json');
18
19// Set time zone.
20if (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}
25
26// Common functions.
27
28/**
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 */
33function 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    }
49}
50
51/**
52 * @brief   Compose JSON response.
53 * @param   int status      Status code for HTTP response.
54 * @param   array response  Response data.
55 * @param   int opts        Options to encode JSON data.
56 * @return  string          JSON response.
57 */
58function 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);
67}
68
69/**
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 */
76function 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();
90}
91
92/**
93 * @brief    Validate API key included in "Authorization" HTTP header.
94 * @return   string  JSON response on error.
95 */
96function 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
107                                 FROM usuarios
108                                WHERE apikey='$apikey' LIMIT 1";
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    }
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 */
141function 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    }
152}
153
154/**
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 */
159function 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;
168}
169
170/**
171 * @brief   Show custom message for "not found" error (404).
172 */
173$app->notFound(
174    function () {
175        $response['message'] = 'REST route not found';
176        jsonResponse(404, $response);
177    }
178);
179
180/**
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.
184 */
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    }
202);
203
204
205// Common routes.
206
207/**
208 * @brief    Get general server information
209 * @note     Route: /info, Method: GET
210 * @return   string  JSON object with basic server information (version, services, etc.)
211 */
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    }
242);
243
244
245function backupConfig()
246{
247    $get_command = 'config-get';
248    $get_output = executeCurlCommand($get_command);
249    if ($get_output == false || $get_output[0]["result"] != 0) {
250        throw new Exception('Error al obtener la configuración actual de Kea DHCP');
251    }
252    $config_text = json_encode($get_output[0]['arguments']);
253    $configurationParsed = str_replace('\\', '', $config_text);
254
255    $backup_dir = '/opt/opengnsys/etc/kea/backup';
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    }
262    $backup_files = glob($backup_dir . '/*.conf');
263    if (count($backup_files) >= 10) {
264        usort($backup_files, function ($a, $b) {
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
275function executeCurlCommand($command, $arguments = null, $create_backup = true)
276{
277    $apiUrl = getenv('DHCP_IP');
278    if (!$apiUrl) {
279        $apiUrl = 'http://localhost:8000/';
280    }
281
282    if ($command == 'config-get' || $command == 'config-write') {
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    }
296    if (($command == 'config-set' || $command == 'config-write') && $create_backup) {
297        backupConfig();
298    }
299    $jsonData = json_encode($requestData);
300    try {
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);
306        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:'));
307        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
308        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
309        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
310        curl_setopt($ch, CURLOPT_POST, true);
311        $response = curl_exec($ch);
312        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
313        $output = json_decode($response, true);
314
315        if ($httpCode >= 200 && $httpCode < 300) {
316
317            return $output;
318        } else {
319            $error = curl_error($ch);
320            throw new Exception($error);
321            //return false;
322        }
323    } catch (Exception $e) {
324        throw new Exception($e->getMessage());
325    }
326}
327
328
329/**
330 * @brief    Get configuration of kea dhcp server
331 * @note     Route: /dhcp, Method: GET
332 * @return   string  JSON object with all kea configuration
333 */
334$app->get('/dhcp', function () {
335    try {
336        $response = executeCurlCommand('config-get');
337
338        if (!$response) {
339            $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf';
340            jsonResponse(400, $responseError);
341        } else {
342            $result_code = $response[0]["result"];
343            if ($result_code == 0) {
344                $arrayDhcp4 = $response[0]['arguments'];
345                jsonResponse(200, $arrayDhcp4, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
346            } else {
347                $responseError =  "Error kea configuration invalid: " . $response[0]["text"];
348                jsonResponse(400, $responseError);
349            }
350        }
351    } catch (Exception $e) {
352        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
353        jsonResponse(400, $responseError);
354    }
355});
356
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
363$app->get('/dhcp/hosts', function () {
364    try {
365        $response = executeCurlCommand('config-get');
366
367        if (!$response) {
368            $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf';
369            jsonResponse(400, $response);
370        } else {
371            $result_code = $response[0]["result"];
372            if ($result_code == 0) {
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                }
380            } else {
381                $responseError =  "Error kea configuration invalid: " . $response[0]["text"];
382                jsonResponse(400, $responseError);
383            }
384        }
385    } catch (Exception $e) {
386        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
387        jsonResponse(400, $responseError);
388    }
389});
390
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
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);
409    $configurationParsed = str_replace("\n", '', $configurationParsed);
410    $configurationParsed = str_replace('&quot;', '"', $configurationParsed);
411    $configuration = json_decode($configurationParsed);
412
413    if ($configuration === null || json_last_error() !== JSON_ERROR_NONE) {
414        $responseError = "Error: El texto proporcionado no es un JSON válido.";
415        jsonResponse(400, $responseError);
416    } else {
417        try {
418            $responseTest = executeCurlCommand('config-test', $configuration);
419            if ($responseTest[0]["result"] == 0) {
420                $responseSet = executeCurlCommand('config-set', $configuration);
421                if ($responseSet == false || $responseSet[0]["result"] != 0) {
422                    $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"];
423                    jsonResponse(400, $responseError);
424                } else {
425                    $responseSuccess =  "Configuración cargada correctamente";
426                    jsonResponse(200, $responseSuccess);
427                }
428            } else {
429                $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"];
430                jsonResponse(400, $responseError);
431            }
432        } catch (Exception $e) {
433            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
434            jsonResponse(400, $responseError);
435        }
436    }
437});
438
439
440$app->post(
441    '/dhcp/add',
442    function () use ($app) {
443        try {
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);
449        } catch (Exception $e) {
450            $response["message"] = $e->getMessage();
451            jsonResponse(400, $response);
452            $app->stop();
453        }
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'] = [];
465            }
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;
476                $array_encoded = json_encode($response[0]['arguments']);
477                $configurationParsed = str_replace('\\', '', $array_encoded);
478                $configuration = json_decode($configurationParsed);
479                $responseTest = executeCurlCommand('config-test', $configuration);
480
481                if ($responseTest[0]["result"] == 0) {
482                    $responseSet = executeCurlCommand('config-set', $configuration);
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);
486                    } else {
487                        $responseSuccess =  "Configuración cargada correctamente";
488                        jsonResponse(200, $responseSuccess);
489                    }
490                } else {
491                    $responseError =  "Error kea configuration invalid: " . $responseTest[0]["text"];
492                    jsonResponse(400, $responseError);
493                }
494            }
495        } catch (Exception $e) {
496            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
497            jsonResponse(400, $responseError);
498        }
499    }
500);
501
502
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) {
528                    $array_encoded = json_encode($response[0]['arguments']);
529                    $configurationParsed = str_replace('\\', '', $array_encoded);
530                    $configuration = json_decode($configurationParsed);
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) {
536                            $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"];
537                            jsonResponse(400, $responseError);
538                        } else {
539                            $responseSuccess =  "Configuración cargada correctamente";
540                            jsonResponse(200, $responseSuccess);
541                        }
542                    } else {
543                        $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"];
544                        jsonResponse(400, $responseError);
545                    }
546                } else {
547                    $responseError =  "Error: El host con el hostname '$host' no existe en las reservaciones.";
548                    jsonResponse(400, $responseError);
549                }
550            } else {
551                $responseError =  'El campo \'reservations\' no está inicializado';
552                jsonResponse(400, $responseError);
553            }
554        } catch (Exception $e) {
555            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
556            jsonResponse(400, $responseError);
557        }
558    }
559);
560
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.";
611
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);
624
625$app->post(
626    '/dhcp/apply',
627    function () use ($app) {
628        try {
629            $response = executeCurlCommand('config-write');
630            if ($response[0]["result"] == 0) {
631                jsonResponse(200, $response);
632            } else {
633                $responseError =  "Error al escribir la configuración en Kea DHCP: " . $response[0]["text"];
634                jsonResponse(400, $responseError);
635            }
636        } catch (Exception $e) {
637            $responseError =  "Error al escribir la configuración en Kea DHCP: " . $e->getMessage();
638            jsonResponse(400, $responseError);
639        }
640    }
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
652$app->post('/dhcp/backup', function () use ($app) {
653    $backup_dir = '/opt/opengnsys/etc/kea/backup';
654    try {
655        $backup_files = glob($backup_dir . '/*.conf');
656        if (empty($backup_files)) {
657            $response =  "No se encontraron archivos de backup";
658            jsonResponse(400, $response);
659        } else {
660            usort($backup_files, function ($a, $b) {
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);
672            } else {
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);
678                } else {
679                    unlink($backup_file);
680                    $responseSuccess =  "última configuración cargada correctamente";
681                    jsonResponse(200, $responseSuccess);
682                }
683            }
684        }
685    } catch (Exception $e) {
686        $responseError =  "Error al restaurar la configuración: " . $e->getMessage();
687        jsonResponse(400, $responseError);
688    }
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
700$app->post('/dhcp/upload', function () use ($app) {
701    if (!isset($_FILES['file_input_name'])) {
702        $responseError =  "No se ha subido ningún archivo";
703        jsonResponse(400, $responseError);
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) {
711        $responseError =  "El archivo JSON subido no está correctamente escrito";
712        jsonResponse(400, $responseError);
713    }
714    try {
715        $test_command = 'config-test';
716        $test_output = executeCurlCommand($test_command, $config_data);
717        if ($test_output == false || $test_output[0]["result"] != 0) {
718            $responseError =  "La configuración no es válida";
719            jsonResponse(400, $responseError);
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            }
732        }
733    } catch (Exception $e) {
734        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
735        jsonResponse(400, $responseError);
736    }
737});
738
739
740
741
742/**
743 * @brief    Get the server status
744 * @note     Route: /status, Method: GET
745 * @return   string  JSON object with all data collected from server status (RAM, %CPU, etc.).
746 */
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    }
760);
Note: See TracBrowser for help on using the repository browser.