diff --git a/src/DhcpBundle/Controller/DhcpController.php b/src/DhcpBundle/Controller/DhcpController.php index 959ece7..320c824 100644 --- a/src/DhcpBundle/Controller/DhcpController.php +++ b/src/DhcpBundle/Controller/DhcpController.php @@ -363,8 +363,10 @@ public function getSubnets(): JsonResponse $subnetId = (int) htmlspecialchars($input->subnetId); $mask = htmlspecialchars($input->mask); $address = htmlspecialchars($input->address); - $nextServer = htmlspecialchars($input->nextServer); - $bootFileName = htmlspecialchars($input->bootFileName); + + // Verificar si next-server y boot-file-name están presentes + $nextServer = isset($input->nextServer) ? htmlspecialchars($input->nextServer) : null; + $bootFileName = isset($input->bootFileName) ? htmlspecialchars($input->bootFileName) : null; } catch (Exception $e) { $response["message"] = $e->getMessage(); if (strpos($e->getMessage(), 'Undefined property') !== false) { @@ -381,11 +383,10 @@ public function getSubnets(): JsonResponse // Crear el campo option-data para la puerta de enlace (gateway) $gatewayIP = substr($address, 0, strrpos($address, '.')) . '.1'; + // Crear el array newSubnet con los valores obligatorios $newSubnet = [ "id" => $subnetId, "subnet" => $subnetName, - "next-server" => $nextServer, - "boot-file-name" => $bootFileName, "reservations" => [], "option-data" => [ [ @@ -396,6 +397,16 @@ public function getSubnets(): JsonResponse ] ]; + // Añadir next-server si está presente + if ($nextServer) { + $newSubnet["next-server"] = $nextServer; + } + + // Añadir boot-file-name si está presente + if ($bootFileName) { + $newSubnet["boot-file-name"] = $bootFileName; + } + if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { $response[0]['arguments']['Dhcp4']['subnet4'] = []; } @@ -465,6 +476,7 @@ public function getSubnets(): JsonResponse } } + /** * @OA\Delete( @@ -602,202 +614,163 @@ public function getSubnets(): JsonResponse } } + /** + * @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"PUT"}) + * @OA\Put( + * path="/ogdhcp/v1/subnets/{subnetId}", + * summary="Modify a DHCP subnet", + * @OA\Parameter( + * name="subnetId", + * in="path", + * description="ID of the subnet to modify", + * required=true, + * @OA\Schema(type="integer") + * ), + * @OA\RequestBody( + * description="Data to modify the subnet", + * required=true, + * @OA\JsonContent( + * type="object", + * @OA\Property(property="mask", type="string"), + * @OA\Property(property="address", type="string"), + * @OA\Property(property="nextServer", type="string"), + * @OA\Property(property="bootFileName", type="string") + * ) + * ), + * @OA\Response( + * response=200, + * description="Subnet modified successfully", + * @OA\JsonContent( + * type="object", + * @OA\Property(property="success", type="string") + * ) + * ), + * @OA\Response( + * response=400, + * description="Error occurred while deleting the subnet", + * @OA\JsonContent( + * oneOf={ + * @OA\Schema(@OA\Property(property="error", type="string", example="Falta un parámetro requerido: $paramFaltante")), + * @OA\Schema(@OA\Property(property="error", type="string", example="No hay subredes definidas")), + * @OA\Schema(@OA\Property(property="error", type="string", example="Error configuracion de kea invalido")), + * @OA\Schema(@OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP")), + * @OA\Schema(@OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP")) + * } + * ) + * ), + * @OA\Response( + * response=404, + * description="Subnet not found", + * @OA\JsonContent(type="object", @OA\Property(property="error", type="string", example="La subred con el id '2' no existe")) + * ), + * @OA\Response( + * response=500, + * description="Error saving configuration in Kea DHCP", + * @OA\JsonContent(type="object", @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP")) + * ) + * ) + */ +public function modifyDhcpSubnet(Request $request): JsonResponse +{ + $subnetId = (int) $request->get('subnetId'); - /** - * @Route("/ogdhcp/v1/subnets/{subnetId}", methods={"PUT"}) - * @OA\Put( - * path="/ogdhcp/v1/subnets/{subnetId}", - * summary="Modify a DHCP subnet", - * @OA\Parameter( - * name="subnetId", - * in="path", - * description="ID of the subnet to modify", - * required=true, - * @OA\Schema( - * type="integer" - * ) - * ), - * @OA\RequestBody( - * description="Data to modify the subnet", - * required=true, - * @OA\JsonContent( - * type="object", - * @OA\Property(property="mask", type="string"), - * @OA\Property(property="address", type="string"), - * @OA\Property(property="nextServer", type="string"), - * @OA\Property(property="bootFileName", type="string") - * ) - * ), - * @OA\Response( - * response=200, - * description="Subnet modified successfully", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="success", type="string") - * ) - * ), - * @OA\Response( - * response=400, - * description="Error occurred while deleting the subnet", - * @OA\JsonContent( - * oneOf={ - * @OA\Schema( - * @OA\Property(property="error", type="string", example="Falta un parámetro requerido: $paramFaltante") - * ), - * @OA\Schema( - * @OA\Property(property="error", type="string", example="No hay subredes definidas") - * ), - * @OA\Schema( - * @OA\Property(property="error", type="string", example="Error configuracion de kea invalido") - * ), - * @OA\Schema( - * @OA\Property(property="error", type="string", example="Error al guardar la configuración en Kea DHCP") - * ), - * @OA\Schema( - * @OA\Property(property="error", type="string", example="Error al escribir en la configuración en Kea DHCP") - * ) - * } - * ), - * @OA\Examples( - * example="parameterMissing", - * summary="Missing required parameter", - * value={"error": "Falta un parámetro requerido: $paramFaltante"} - * ), - * @OA\Examples( - * example="noSubnets", - * summary="No subnets initialized", - * value={"error": "No hay subredes definidas"} - * ), - * @OA\Examples( - * example="invalidKea", - * summary="Error in config-test in kea", - * value={"error": "Error configuracion de kea invalido"} - * ), - * @OA\Examples( - * example="saveKea", - * summary="Error in config-set in kea", - * value={"error": "Error al guardar la configuración en Kea DHCP"} - * ), - * @OA\Examples( - * example="writeKea", - * summary="Error in config-write in kea", - * value={"error": "Error al escribir en la configuración en Kea DHCP"} - * ) - * ), - * @OA\Response( - * response=404, - * description="Subnet not found", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="La subred con el id '2' no existe") - * ) - * ), - * @OA\Response( - * response=500, - * description="Error saving configuration in Kea DHCP", - * @OA\JsonContent( - * type="object", - * @OA\Property(property="error", type="string", example="Error al obtener la configuración de Kea DHCP") - * ) - * ) - * ) - */ - public function modifyDhcpSubnet(Request $request): JsonResponse - { - $subnetId = (int) $request->get('subnetId'); - - try { - $input = json_decode($request->getContent()); - $mask = htmlspecialchars($input->mask); - $address = htmlspecialchars($input->address); - $nextServer = htmlspecialchars($input->nextServer); - $bootFileName = htmlspecialchars($input->bootFileName); - } catch (Exception $e) { - $response["message"] = $e->getMessage(); - if (strpos($e->getMessage(), 'Undefined property') !== false) { - preg_match('/Undefined property: stdClass::\$(\w+)/', $e->getMessage(), $matches); - $paramFaltante = $matches[1] ?? 'desconocido'; - return new JsonResponse(['error' => "Falta un parámetro requerido: $paramFaltante"], 400); - } - } - - try { - $response = $this->curlKeaService->executeCurlCommand('config-get'); - $subnetName = $address . '/' . $this->curlKeaService->convertMaskToCIDR($mask); - - if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { - $responseError = "Error: No hay subredes definidas"; - return new JsonResponse(['error' => $responseError], 400); - } - - $subnetIndex = array_search($subnetId, array_column($response[0]['arguments']['Dhcp4']['subnet4'], 'id')); - - if ($subnetIndex === false) { - $responseError = "La subred con el id '$subnetId' no existe"; - return new JsonResponse(['error' => $responseError], 400); - } else { - // Calcular el gateway añadiendo .1 al final de la subred - $gateway = preg_replace('/\d+$/', '1', $address); - - // Modificar la subred existente - $response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = [ - "id" => $subnetId, - "subnet" => $subnetName, - "next-server" => $nextServer, - "boot-file-name" => $bootFileName, - "reservations" => [], - "option-data" => [ - [ - "name" => "routers", - "code" => 3, - "data" => $gateway - ] - ] - ]; - - // Eliminar el campo 'hash' si existe - if (isset($response[0]['arguments']['hash'])) { - unset($response[0]['arguments']['hash']); - } - - $array_encoded = json_encode($response[0]['arguments']); - $configurationParsed = str_replace('\\', '', $array_encoded); - $configuration = json_decode($configurationParsed); - - $responseTest = $this->curlKeaService->executeCurlCommand('config-test', $configuration); - - if ($responseTest[0]["result"] == 0) { - $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); - if ($responseSet == false || $responseSet[0]["result"] != 0) { - $responseError = "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } else { - $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); - if ($responseWrite == false || $responseWrite[0]["result"] != 0) { - $responseError = "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } else { - // Volvemos a consultar la configuración para devolver la subred modificada - $updatedResponse = $this->curlKeaService->executeCurlCommand('config-get'); - $updatedSubnet = array_filter($updatedResponse[0]['arguments']['Dhcp4']['subnet4'], function ($subnet) use ($subnetId) { - return $subnet['id'] == $subnetId; - }); - - $responseSuccess = "Subred modificada correctamente"; - return new JsonResponse(['success' => $responseSuccess,'message' => reset($updatedSubnet)], 200); - } - } - } else { - $responseError = "Error configuracion de kea invalido: " . $responseTest[0]["text"]; - return new JsonResponse(['error' => $responseError], 400); - } - } - } catch (Exception $e) { - $responseError = "Error al obtener la configuración de Kea DHCP: " . $e->getMessage(); - return new JsonResponse(['error' => $responseError], 500); + try { + $input = json_decode($request->getContent()); + $mask = htmlspecialchars($input->mask); + $address = htmlspecialchars($input->address); + + // Verificar si next-server y boot-file-name están presentes + $nextServer = isset($input->nextServer) ? htmlspecialchars($input->nextServer) : null; + $bootFileName = isset($input->bootFileName) ? htmlspecialchars($input->bootFileName) : null; + } catch (Exception $e) { + if (strpos($e->getMessage(), 'Undefined property') !== false) { + preg_match('/Undefined property: stdClass::\$(\w+)/', $e->getMessage(), $matches); + $paramFaltante = $matches[1] ?? 'desconocido'; + return new JsonResponse(['error' => "Falta un parámetro requerido: $paramFaltante"], 400); } + return new JsonResponse(['error' => $e->getMessage()], 400); } - + + try { + $response = $this->curlKeaService->executeCurlCommand('config-get'); + $subnetName = $address . '/' . $this->curlKeaService->convertMaskToCIDR($mask); + + if (!isset($response[0]['arguments']['Dhcp4']['subnet4'])) { + return new JsonResponse(['error' => "No hay subredes definidas"], 400); + } + + $subnetIndex = array_search($subnetId, array_column($response[0]['arguments']['Dhcp4']['subnet4'], 'id')); + + if ($subnetIndex === false) { + return new JsonResponse(['error' => "La subred con el id '$subnetId' no existe"], 400); + } else { + // Calcular el gateway añadiendo .1 al final de la subred + $gateway = preg_replace('/\d+$/', '1', $address); + + // Modificar la subred existente + $newSubnet = [ + "id" => $subnetId, + "subnet" => $subnetName, + "reservations" => [], + "option-data" => [ + [ + "name" => "routers", + "code" => 3, + "data" => $gateway + ] + ] + ]; + + // Añadir next-server si está presente + if ($nextServer) { + $newSubnet["next-server"] = $nextServer; + } + + // Añadir boot-file-name si está presente + if ($bootFileName) { + $newSubnet["boot-file-name"] = $bootFileName; + } + + $response[0]['arguments']['Dhcp4']['subnet4'][$subnetIndex] = $newSubnet; + + // Eliminar el campo 'hash' si existe + if (isset($response[0]['arguments']['hash'])) { + unset($response[0]['arguments']['hash']); + } + + $array_encoded = json_encode($response[0]['arguments']); + $configurationParsed = str_replace('\\', '', $array_encoded); + $configuration = json_decode($configurationParsed); + + $responseTest = $this->curlKeaService->executeCurlCommand('config-test', $configuration); + + if ($responseTest[0]["result"] == 0) { + $responseSet = $this->curlKeaService->executeCurlCommand('config-set', $configuration); + if ($responseSet == false || $responseSet[0]["result"] != 0) { + return new JsonResponse(['error' => "Error al guardar la configuración en Kea DHCP: " . $responseSet[0]["text"]], 400); + } else { + $responseWrite = $this->curlKeaService->executeCurlCommand('config-write', $configuration); + if ($responseWrite == false || $responseWrite[0]["result"] != 0) { + return new JsonResponse(['error' => "Error al escribir en la configuración en Kea DHCP: " . $responseWrite[0]["text"]], 400); + } else { + // Volvemos a consultar la configuración para devolver la subred modificada + $updatedResponse = $this->curlKeaService->executeCurlCommand('config-get'); + $updatedSubnet = array_filter($updatedResponse[0]['arguments']['Dhcp4']['subnet4'], function ($subnet) use ($subnetId) { + return $subnet['id'] == $subnetId; + }); + + return new JsonResponse(['success' => "Subred modificada correctamente", 'message' => reset($updatedSubnet)], 200); + } + } + } else { + return new JsonResponse(['error' => "Error configuracion de kea invalido: " . $responseTest[0]["text"]], 400); + } + } + } catch (Exception $e) { + return new JsonResponse(['error' => "Error al obtener la configuración de Kea DHCP: " . $e->getMessage()], 500); + } +} + /** * @OA\Get( * path="/ogdhcp/v1/subnets/{subnetId}/hosts", @@ -1566,3 +1539,4 @@ public function restoreDhcpConfiguration(): JsonResponse } +