source: admin/WebConsole/rest/common.php

lgromero-new-oglive
Last change on this file was a5d23af, checked in by Natalia Serrano <natalia.serrano@…>, 14 months ago

refs #232 fix log truncation, improve WOL logging

  • Property mode set to 100644
File size: 29.0 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        $max_body_len_to_log = 150;
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        }
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        }
207    }
208);
209
210
211// Common routes.
212
213/**
214 * @brief    Get general server information
215 * @note     Route: /info, Method: GET
216 * @return   string  JSON object with basic server information (version, services, etc.)
217 */
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    }
248);
249
250
251function backupConfig()
252{
253    $get_command = 'config-get';
254    $get_output = executeCurlCommand($get_command);
255    if ($get_output == false || $get_output[0]["result"] != 0) {
256        throw new Exception('Error al obtener la configuración actual de Kea DHCP');
257    }
258    $config_text = json_encode($get_output[0]['arguments']);
259    $configurationParsed = str_replace('\\', '', $config_text);
260
261    $backup_dir = '/opt/opengnsys/etc/kea/backup';
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    }
268    $backup_files = glob($backup_dir . '/*.conf');
269    if (count($backup_files) >= 10) {
270        usort($backup_files, function ($a, $b) {
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
281function executeCurlCommand($command, $arguments = null, $create_backup = true)
282{
283    $apiUrl = getenv('DHCP_IP');
284    if (!$apiUrl) {
285        $apiUrl = 'http://localhost:8000/';
286    }
287
288    if ($command == 'config-get' || $command == 'config-write') {
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    }
302    if (($command == 'config-set' || $command == 'config-write') && $create_backup) {
303        backupConfig();
304    }
305    $jsonData = json_encode($requestData);
306    try {
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);
312        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Expect:'));
313        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
314        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
315        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
316        curl_setopt($ch, CURLOPT_POST, true);
317        $response = curl_exec($ch);
318        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
319        $output = json_decode($response, true);
320
321        if ($httpCode >= 200 && $httpCode < 300) {
322
323            return $output;
324        } else {
325            $error = curl_error($ch);
326            throw new Exception($error);
327            //return false;
328        }
329    } catch (Exception $e) {
330        throw new Exception($e->getMessage());
331    }
332}
333
334
335/**
336 * @brief    Get configuration of kea dhcp server
337 * @note     Route: /dhcp, Method: GET
338 * @return   string  JSON object with all kea configuration
339 */
340$app->get('/dhcp', function () {
341    try {
342        $response = executeCurlCommand('config-get');
343
344        if (!$response) {
345            $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf';
346            jsonResponse(400, $responseError);
347        } else {
348            $result_code = $response[0]["result"];
349            if ($result_code == 0) {
350                $arrayDhcp4 = $response[0]['arguments'];
351                jsonResponse(200, $arrayDhcp4, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
352            } else {
353                $responseError =  "Error kea configuration invalid: " . $response[0]["text"];
354                jsonResponse(400, $responseError);
355            }
356        }
357    } catch (Exception $e) {
358        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
359        jsonResponse(400, $responseError);
360    }
361});
362
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
369$app->get('/dhcp/hosts', function () {
370    try {
371        $response = executeCurlCommand('config-get');
372
373        if (!$response) {
374            $responseError = 'Error: No se pudo acceder al archivo dhcpd.conf';
375            jsonResponse(400, $response);
376        } else {
377            $result_code = $response[0]["result"];
378            if ($result_code == 0) {
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                }
386            } else {
387                $responseError =  "Error kea configuration invalid: " . $response[0]["text"];
388                jsonResponse(400, $responseError);
389            }
390        }
391    } catch (Exception $e) {
392        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
393        jsonResponse(400, $responseError);
394    }
395});
396
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
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);
415    $configurationParsed = str_replace("\n", '', $configurationParsed);
416    $configurationParsed = str_replace('&quot;', '"', $configurationParsed);
417    $configuration = json_decode($configurationParsed);
418
419    if ($configuration === null || json_last_error() !== JSON_ERROR_NONE) {
420        $responseError = "Error: El texto proporcionado no es un JSON válido.";
421        jsonResponse(400, $responseError);
422    } else {
423        try {
424            $responseTest = executeCurlCommand('config-test', $configuration);
425            if ($responseTest[0]["result"] == 0) {
426                $responseSet = executeCurlCommand('config-set', $configuration);
427                if ($responseSet == false || $responseSet[0]["result"] != 0) {
428                    $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"];
429                    jsonResponse(400, $responseError);
430                } else {
431                    $responseSuccess =  "Configuración cargada correctamente";
432                    jsonResponse(200, $responseSuccess);
433                }
434            } else {
435                $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"];
436                jsonResponse(400, $responseError);
437            }
438        } catch (Exception $e) {
439            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
440            jsonResponse(400, $responseError);
441        }
442    }
443});
444
445
446$app->post(
447    '/dhcp/add',
448    function () use ($app) {
449        try {
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);
455        } catch (Exception $e) {
456            $response["message"] = $e->getMessage();
457            jsonResponse(400, $response);
458            $app->stop();
459        }
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'] = [];
471            }
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;
482                $array_encoded = json_encode($response[0]['arguments']);
483                $configurationParsed = str_replace('\\', '', $array_encoded);
484                $configuration = json_decode($configurationParsed);
485                $responseTest = executeCurlCommand('config-test', $configuration);
486
487                if ($responseTest[0]["result"] == 0) {
488                    $responseSet = executeCurlCommand('config-set', $configuration);
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);
492                    } else {
493                        $responseSuccess =  "Configuración cargada correctamente";
494                        jsonResponse(200, $responseSuccess);
495                    }
496                } else {
497                    $responseError =  "Error kea configuration invalid: " . $responseTest[0]["text"];
498                    jsonResponse(400, $responseError);
499                }
500            }
501        } catch (Exception $e) {
502            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
503            jsonResponse(400, $responseError);
504        }
505    }
506);
507
508
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) {
534                    $array_encoded = json_encode($response[0]['arguments']);
535                    $configurationParsed = str_replace('\\', '', $array_encoded);
536                    $configuration = json_decode($configurationParsed);
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) {
542                            $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"];
543                            jsonResponse(400, $responseError);
544                        } else {
545                            $responseSuccess =  "Configuración cargada correctamente";
546                            jsonResponse(200, $responseSuccess);
547                        }
548                    } else {
549                        $responseError =  "Error al guardar la configuración en Kea DHCP: " . $responseTest[0]["text"];
550                        jsonResponse(400, $responseError);
551                    }
552                } else {
553                    $responseError =  "Error: El host con el hostname '$host' no existe en las reservaciones.";
554                    jsonResponse(400, $responseError);
555                }
556            } else {
557                $responseError =  'El campo \'reservations\' no está inicializado';
558                jsonResponse(400, $responseError);
559            }
560        } catch (Exception $e) {
561            $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
562            jsonResponse(400, $responseError);
563        }
564    }
565);
566
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.";
617
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);
630
631$app->post(
632    '/dhcp/apply',
633    function () use ($app) {
634        try {
635            $response = executeCurlCommand('config-write');
636            if ($response[0]["result"] == 0) {
637                jsonResponse(200, $response);
638            } else {
639                $responseError =  "Error al escribir la configuración en Kea DHCP: " . $response[0]["text"];
640                jsonResponse(400, $responseError);
641            }
642        } catch (Exception $e) {
643            $responseError =  "Error al escribir la configuración en Kea DHCP: " . $e->getMessage();
644            jsonResponse(400, $responseError);
645        }
646    }
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
658$app->post('/dhcp/backup', function () use ($app) {
659    $backup_dir = '/opt/opengnsys/etc/kea/backup';
660    try {
661        $backup_files = glob($backup_dir . '/*.conf');
662        if (empty($backup_files)) {
663            $response =  "No se encontraron archivos de backup";
664            jsonResponse(400, $response);
665        } else {
666            usort($backup_files, function ($a, $b) {
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);
678            } else {
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);
684                } else {
685                    unlink($backup_file);
686                    $responseSuccess =  "última configuración cargada correctamente";
687                    jsonResponse(200, $responseSuccess);
688                }
689            }
690        }
691    } catch (Exception $e) {
692        $responseError =  "Error al restaurar la configuración: " . $e->getMessage();
693        jsonResponse(400, $responseError);
694    }
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
706$app->post('/dhcp/upload', function () use ($app) {
707    if (!isset($_FILES['file_input_name'])) {
708        $responseError =  "No se ha subido ningún archivo";
709        jsonResponse(400, $responseError);
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) {
717        $responseError =  "El archivo JSON subido no está correctamente escrito";
718        jsonResponse(400, $responseError);
719    }
720    try {
721        $test_command = 'config-test';
722        $test_output = executeCurlCommand($test_command, $config_data);
723        if ($test_output == false || $test_output[0]["result"] != 0) {
724            $responseError =  "La configuración no es válida";
725            jsonResponse(400, $responseError);
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            }
738        }
739    } catch (Exception $e) {
740        $responseError =  "Error al obtener la configuración de Kea DHCP: " . $e->getMessage();
741        jsonResponse(400, $responseError);
742    }
743});
744
745
746
747
748/**
749 * @brief    Get the server status
750 * @note     Route: /status, Method: GET
751 * @return   string  JSON object with all data collected from server status (RAM, %CPU, etc.).
752 */
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    }
766);
Note: See TracBrowser for help on using the repository browser.