diff --git a/etc/nginxServer.conf.tmpl b/etc/nginxServer.conf.tmpl new file mode 100644 index 0000000..b67abda --- /dev/null +++ b/etc/nginxServer.conf.tmpl @@ -0,0 +1,42 @@ +server { + listen 80; + server_name __SERVERIP__ localhost; # IP del servidor + + # Raíz del documento para el proyecto Symfony + root /opt/ogdhcp/public; + + # Bloque para manejar las solicitudes a /ogdhcp + location /ogdhcp { + try_files $uri $uri/ /index.php?$query_string; + # Aumentar el tiempo de espera por el install ogdhcp (si es necesario) + proxy_read_timeout 600; + proxy_connect_timeout 600; + proxy_send_timeout 600; + send_timeout 600; + } + + # Bloque para manejar las solicitudes a index.php + location ~ ^/index.php(/|$) { + include fastcgi_params; + fastcgi_pass unix:/run/php/php__PHPVERSION__-fpm-ogdhcp.sock; # Asegúrate de que esto sea correcto + fastcgi_split_path_info ^(.+\.php)(/.*)$; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param DOCUMENT_ROOT $document_root; + internal; + } + + # Bloque para devolver 404 en cualquier solicitud a archivos PHP que no sean index.php + location ~ \.php$ { + return 404; + } + + # Logs de error y acceso para el proyecto Symfony + error_log /var/log/nginx/ogdhcp_error.log; + access_log /var/log/nginx/ogdhcp_access.log; + + # Manejo de la ruta para la documentación de la API (Swagger) + location /ogdhcp/api/doc { + try_files $uri /index.php?$query_string; + } +} diff --git a/installer/ogdhcp_installer.sh b/installer/ogdhcp_installer.sh index 7a5f58f..7d71df0 100755 --- a/installer/ogdhcp_installer.sh +++ b/installer/ogdhcp_installer.sh @@ -41,18 +41,14 @@ function globalSetup() { ENABLESERVICE="eval update-rc.d \$service defaults" DISABLESERVICE="eval update-rc.d \$service disable" - APACHESERV=apache2 - APACHECFGDIR=/etc/apache2 - APACHESITESDIR=sites-available - APACHEOGSITE=ogdhcp - APACHEUSER="www-data" - APACHEGROUP="www-data" - APACHEENABLEMODS="a2enmod headers ssl rewrite proxy_fcgi fastcgi actions alias" - APACHEENABLESSL="a2ensite default-ssl" - APACHEENABLEOG="a2ensite $APACHEENABLEOG" - APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite" - - PHPFPMSERV=php7.2-fpm + # Variables globales + DEFAULTDEV="" + NGINX_TEMPLATE="$INSTALL_TARGET/etc/nginxServer.conf.tmpl" + NGINX_OUTPUT="/etc/nginx/sites-available/ogdhcp.conf" + NGINX_CONF_PATH="/etc/nginx/nginx.conf" + PHP_FPM_CONF_PATH="/etc/php/__PHPVERSION__/fpm/pool.d/www.conf" + NEW_FPM_CONF_PATH="/etc/php/__PHPVERSION__/fpm/pool.d/ogdhcp.conf" + SOCKET_PATH="/run/php/php__PHPVERSION__-fpm-ogdhcp.sock" # Registro de incidencias. OGLOGFILE="$INSTALL_TARGET/var/log/${PROGRAMNAME%.sh}.log" @@ -87,6 +83,7 @@ function checkDependencies() { kea-ctrl-agent jq net-tools + composer ) @@ -103,24 +100,6 @@ function checkDependencies() { echoAndLog "Dependencies checked." } -# Función para instalar los paquetes necesarios para KEA-DHCP -install_kea() { - sudo apt-get install -y isc-kea-common isc-kea-ctrl-agent isc-kea-dhcp4-server isc-kea-dhcp6-server isc-kea-admin -} - -# Función para instalar Composer -install_composer() { - curl -sS https://getcomposer.org/installer | php - sudo mv composer.phar /usr/local/bin/composer -} - -# Función para instalar Swagger UI -install_swagger() { - sudo apt-get install -y unzip - wget https://github.com/swagger-api/swagger-ui/archive/master.zip - unzip master.zip -d /var/www/html/ - sudo mv /var/www/html/swagger-ui-master /var/www/html/swagger-ui -} # Obtiene el código fuente del proyecto desde el repositorio de GitHub. function downloadCode() { @@ -333,85 +312,146 @@ function runComposer() { return 0 } -function install_swagger_ui { - # Define la URL del archivo de Swagger UI que quieres descargar - swagger_ui_url="https://github.com/swagger-api/swagger-ui/archive/refs/heads/master.zip" - # Define la ruta donde quieres descomprimir Swagger UI - swagger_ui_path="/tmp/swagger-ui" +get_first_network_interface_with_traffic() { + while read -r line; do + if [[ "$line" == *:* ]]; then + interface=$(echo "$line" | cut -d ':' -f 1 | xargs) + if [[ "$interface" != "lo" ]]; then + received_bytes=$(echo "$line" | awk '{print $2}') + transmitted_bytes=$(echo "$line" | awk '{print $10}') + if (( received_bytes > 0 || transmitted_bytes > 0 )); then + DEFAULTDEV="$interface" + break + fi + fi + fi + done < /proc/net/dev +} +comment_auth_kea() { + KEA_CTRL_AGENT_CONF="/etc/kea/kea-ctrl-agent.conf" + if grep -q '^[^#]*"authentication": {' "$KEA_CTRL_AGENT_CONF"; then + echo "Comentando el bloque de autenticación en $KEA_CTRL_AGENT_CONF..." + sed -i '/"authentication": {/,/]/ { + s/^ *//; # Elimina espacios en blanco al principio de la línea + s/^\([^#]\)/#\1/ # Comenta solo las líneas no comentadas + }' "$KEA_CTRL_AGENT_CONF" - # Define la ruta de destino para los archivos de Swagger UI - destination_path="/opt/ogdhcp/public" + echo "Bloque de autenticación comentado correctamente." + else + echo "El bloque de autenticación ya está comentado." + fi - # Crea los directorios si no existen - mkdir -p "$swagger_ui_path" - mkdir -p "$destination_path" + # Verificar si las líneas fueron comentadas usando una expresión regular mejorada + # que permite cualquier cantidad de espacios entre # y "authentication" + if grep -q '^#\s*"authentication": {' "$KEA_CTRL_AGENT_CONF"; then + echo "Confirmación: Bloque de autenticación comentado correctamente." + # Reiniciar el servicio de Kea Control Agent para aplicar los cambios + echo "Reiniciando el agente de Kea Control Agent..." + sudo systemctl restart kea-ctrl-agent.service - # Descarga el archivo de Swagger UI - wget "$swagger_ui_url" -O /tmp/swagger-ui.zip - - # Descomprime el archivo de Swagger UI en la ruta especificada - unzip /tmp/swagger-ui.zip -d "$swagger_ui_path" - - # Copia los archivos de Swagger UI al directorio de destino - cp -r "$swagger_ui_path"/swagger-ui-master/dist/* "$destination_path" - - # Elimina el archivo descargado y el directorio temporal - rm /tmp/swagger-ui.zip - rm -r "$swagger_ui_path" - /opt/ogdhcp/vendor/bin/openapi /opt/ogdhcp/src/DhcpBundle/Controller/ -o "$destination_path/swagger.json" - echo "Swagger UI instalado en $destination_path." + if systemctl is-active --quiet kea-ctrl-agent.service; then + echo "El agente de Kea Control Agent se ha reiniciado correctamente." + else + echo "Error: No se pudo reiniciar el agente de Kea Control Agent." + fi + else + echo "Error: No se pudo comentar correctamente el bloque de autenticación." + fi +} +# Función para obtener la dirección IP de una interfaz +get_ip_address() { + local interface="$1" + ip -4 addr show "$interface" | grep -oP "(?<=inet\s)\d+(\.\d+){3}" } -function installWebConsoleApacheConf() { - if [ $# -ne 2 ]; then - errorAndLog "${FUNCNAME}(): invalid number of parameters" +# Función para obtener la versión de PHP instalada +get_php_fpm_version() { + php -v | grep -oP "PHP \K\d+\.\d+" +} + +# Función para configurar Nginx +setup_nginx() { + get_first_network_interface_with_traffic + + if [[ -z "$DEFAULTDEV" ]]; then + echo "Error: No se encontró una interfaz de red activa." exit 1 fi - local path_opengnsys_base="$1" - local path_apache2_confd="$2" - local OGHDPCDIR="${path_opengnsys_base}/public" - local sockfile + ip_address_server=$(get_ip_address "$DEFAULTDEV") + php_version=$(get_php_fpm_version) - if [ ! -d "$path_apache2_confd" ]; then - errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation" - return 1 + if [[ -z "$php_version" ]]; then + echo "Error: No se pudo obtener la versión de PHP." + exit 1 fi - mkdir -p "$path_apache2_confd/{sites-available,sites-enabled}" - - echoAndLog "${FUNCNAME}(): creating apache2 config file.." - - # Activar PHP-FPM. - echoAndLog "${FUNCNAME}(): configuring PHP-FPM" - service="$PHPFPMSERV" - $ENABLESERVICE; $STARTSERVICE - sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1) - - # Activar módulos de Apache. - $APACHEENABLEMODS - - # Generar configuración de consola web a partir del archivo de plantilla. - if [ -n "$sockfile" ]; then - sed -e "s,OGHDPCDIR,$OGHDPCDIR,g" \ - -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \ - "$WORKDIR/ogdhcp/etc/apache.conf.tmpl" > "$path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf" - else - sed -e "s,OGHDPCDIR,$OGHDPCDIR,g" \ - "$WORKDIR/ogdhcp/server/etc/apache.conf.tmpl" > "$path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf" + # Leer y modificar la plantilla de configuración de nginx + if [[ ! -f "$NGINX_TEMPLATE" ]]; then + echo "Error: La plantilla de Nginx no se encontró." + exit 1 fi - $APACHEENABLEOG - if [ $? -ne 0 ]; then - errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation" - return 1 - fi - echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon" - service="$APACHESERV" - $ENABLESERVICE; $STARTSERVICE - return 0 + + nginx_content=$(<"$NGINX_TEMPLATE") + nginx_content="${nginx_content//__SERVERIP__/$ip_address_server}" + nginx_content="${nginx_content//__PHPVERSION__/$php_version}" + + # Crear el archivo de configuración de Nginx + echo "$nginx_content" > "$NGINX_OUTPUT" + echo "Archivo de configuración de Nginx creado en $NGINX_OUTPUT." + + # Crear el enlace simbólico + ln -sf "$NGINX_OUTPUT" /etc/nginx/sites-enabled/ogdhcp.conf + echo "Enlace simbólico creado en /etc/nginx/sites-enabled/ogdhcp.conf." + + # Modificar nginx.conf para ejecutar como ogdhcp + sed -i 's/user www-data;/user ogdhcp;/g' "$NGINX_CONF_PATH" + echo "Nginx configurado para ejecutarse como ogdhcp." + + # Reiniciar Nginx + systemctl restart nginx.service + echo "Servicio Nginx reiniciado." } +# Función para modificar el archivo de configuración PHP-FPM +modify_php_fpm_config() { + php_version=$(get_php_fpm_version) + + if [[ -z "$php_version" ]]; then + echo "Error: No se pudo obtener la versión de PHP." + exit 1 + fi + + php_fpm_conf_path="/etc/php/$php_version/fpm/pool.d/www.conf" + new_fpm_conf_path="/etc/php/$php_version/fpm/pool.d/ogdhcp.conf" + socket_path="/run/php/php$php_version-fpm-ogdhcp.sock" + + # Copiar el archivo www.conf a ogdhcp.conf + cp "$php_fpm_conf_path" "$new_fpm_conf_path" + + # Modificar el archivo ogdhcp.conf + sed -i 's/\[www\]/[ogdhcp]/g' "$new_fpm_conf_path" + sed -i 's/user = www-data/user = ogdhcp/g' "$new_fpm_conf_path" + sed -i 's/group = www-data/group = ogdhcp/g' "$new_fpm_conf_path" + sed -i "s|listen =.*|listen = $socket_path|g" "$new_fpm_conf_path" + sed -i 's/listen.owner = www-data/listen.owner = ogdhcp/g' "$new_fpm_conf_path" + sed -i 's/listen.group = www-data/listen.group = ogdhcp/g' "$new_fpm_conf_path" + + # Reiniciar PHP-FPM + systemctl restart php"$php_version"-fpm.service + echo "PHP-FPM reiniciado." + + # Verificar la creación del socket + if [[ -S "$socket_path" ]]; then + echo "Socket PHP-FPM $socket_path creado correctamente." + else + echo "Error: El socket PHP-FPM $socket_path no se ha creado." + exit 1 + fi +} + + ##################################################################### ####### Algunas funciones útiles de propósito general: ##################################################################### @@ -459,7 +499,6 @@ mkdir -p $WORKDIR pushd $WORKDIR checkDependencies -install_kea # Si es necesario, descarga el repositorio de código en directorio temporal if [ $REMOTE -eq 1 ]; then downloadCode $GIT_REPO @@ -492,10 +531,16 @@ if [ $? -ne 0 ]; then exit 1 fi + +comment_auth_kea +if [ $? -ne 0 ]; then + errorAndLog "Error while commenting auth block!" + exit 1 +fi + downloadComposer runComposer -install_swagger_ui # Creando configuración de Apache. installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR if [ $? -ne 0 ]; then