diff options
188 files changed, 4013 insertions, 3078 deletions
diff --git a/admin/Database/ogAdmBD-1.1.0a-1.1.1.sql b/admin/Database/ogAdmBD-1.1.0a-1.1.1.sql index d0b3e0a7..e5a6bd4e 100644 --- a/admin/Database/ogAdmBD-1.1.0a-1.1.1.sql +++ b/admin/Database/ogAdmBD-1.1.0a-1.1.1.sql @@ -1,13 +1,43 @@ ### Fichero de actualización de la base de datos. -# OpenGnsys 1.1.0, 1.1.0a - OpenGnsys 1.1.1 +# OpenGnsys 1.1.0, 1.1.0a, 1.1.1pre - OpenGnsys 1.1.1 #use ogAdmBD -# Añadir campo para incluir PC de profesor de aula (ticket #816). -ALTER TABLE aulas - ADD idordprofesor INT(11) DEFAULT 0 AFTER puestos; +# Eliminar procedimiento y disparador para evitar errores de ejecución. +DROP PROCEDURE IF EXISTS addcols; +# Procedimiento para actualización condicional de tablas. +DELIMITER '//' +CREATE PROCEDURE addcols() BEGIN + # Añadir campo para incluir PC de profesor de aula (ticket #816). + IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='idordprofesor' AND TABLE_NAME='aulas' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE aulas + ADD idordprofesor INT(11) DEFAULT 0 AFTER puestos; + END IF; + # Borrar campos sin uso del antiguo servicio ogAdmRepo (ticket #875). + IF EXISTS (SELECT * FROM information_schema.COLUMNS + WHERE COLUMN_NAME='puertorepo' AND TABLE_NAME='repositorios' AND TABLE_SCHEMA=DATABASE()) + THEN + ALTER TABLE repositorios + DROP passguor, + DROP puertorepo; + END IF; +END// +# Ejecutar actualización condicional. +DELIMITER ';' +CALL addcols(); +DROP PROCEDURE addcols; -# Borrar campos sin uso del antiguo servicio ogAdmRepo (ticket #875). -ALTER TABLE repositorios - DROP passguor, - DROP puertorepo; +# Cambio del nombre de las plantillas PXE para compatibilidad con UEFI. +UPDATE ordenadores SET arranque='10' WHERE arranque='01'; +# Nuevos tipos de particiones. +INSERT INTO tipospar (codpar, tipopar, clonable) VALUES + (CONV('27',16,10), 'HNTFS-WINRE', 1) + ON DUPLICATE KEY UPDATE + codpar=VALUES(codpar), tipopar=VALUES(tipopar), clonable=VALUES(clonable); + +# Actualizar gestores de los asistentes (ticket #915). +UPDATE asistentes + SET gestor = REPLACE(gestor, '/asistentes/', '/comandos/') + WHERE gestor LIKE '../asistentes/%'; diff --git a/admin/Database/ogAdmBD.sql b/admin/Database/ogAdmBD.sql index 372398e4..8c742e48 100644 --- a/admin/Database/ogAdmBD.sql +++ b/admin/Database/ogAdmBD.sql @@ -164,11 +164,11 @@ CREATE TABLE `asistentes` ( INSERT INTO `asistentes` (`idcomando`, `descripcion`, `pagina`, `gestor`, `funcion`, `urlimg`, `aplicambito`, `visuparametros`, `parametros`, `comentarios`, `activo`) VALUES -('8', 'Asistente Clonacion Particiones Remotas', '../asistentes/AsistenteCloneRemotePartition.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'), -('8', 'Asistente Deploy de Imagenes', '../asistentes/AsistenteDeployImage.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'), -('8', 'Asistente UpdateCache con Imagenes', '../asistentes/AsistenteUpdateCache.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '0'), -('8', 'Asistente Restauracion de Imagenes', '../asistentes/AsistenteRestoreImage.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '0'), -('8', 'Asistente Particionado', '../asistentes/AsistenteParticionado.php', '../asistentes/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'); +('8', 'Asistente Clonacion Particiones Remotas', '../asistentes/AsistenteCloneRemotePartition.php', '../comandos/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'), +('8', 'Asistente Deploy de Imagenes', '../asistentes/AsistenteDeployImage.php', '../comandos/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'), +('8', 'Asistente UpdateCache con Imagenes', '../asistentes/AsistenteUpdateCache.php', '../comandos/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '0'), +('8', 'Asistente Restauracion de Imagenes', '../asistentes/AsistenteRestoreImage.php', '../comandos/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '0'), +('8', 'Asistente Particionado', '../asistentes/AsistenteParticionado.php', '../comandos/gestores/gestor_Comandos.php', 'EjecutarScript', ' ', '31', 'iph;tis;dcr;dsp', 'nfn;iph;tis;dcr;scp', ' ', '1'); -- -------------------------------------------------------- diff --git a/admin/INSTALL b/admin/INSTALL deleted file mode 100644 index e69de29b..00000000 --- a/admin/INSTALL +++ /dev/null diff --git a/admin/README.es.txt b/admin/README.es.txt new file mode 100644 index 00000000..bf3f1a47 --- /dev/null +++ b/admin/README.es.txt @@ -0,0 +1,10 @@ +OpenGnsys Administrator README +================================ + + +Este directorio contiene la estructura de datos de los servicios principales de OpenGnsys. + +- Database ficheros SQL para crear/actualizar la base de datos +- Interface scripts de interfaz entre la web y el servicio OpenGnsys Server +- Sources código fuente de servicio y clientes +- WebConsole web de administración de OpenGnsys diff --git a/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.c b/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.c index 9035e81a..6f87cc45 100644 --- a/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.c +++ b/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.c @@ -2132,6 +2132,12 @@ BOOLEAN ejecutaArchivo(char* filecmd,TRAMA *ptrTrama) liberaMemoria(buffer);
return(TRUE);
}
+
+BOOLEAN EjecutaComandosPendientes(TRAMA* ptrTrama)
+{
+ return(TRUE);
+}
+
//______________________________________________________________________________________________________
// Funcin: enviaMensajeServidor
//
@@ -2262,6 +2268,9 @@ int main(int argc, char *argv[]) strcpy(tbfuncionesClient[cf].nf, "InventarioSoftware");
tbfuncionesClient[cf++].fptr = &InventarioSoftware;
+ strcpy(tbfuncionesClient[cf].nf, "EjecutaComandosPendientes");
+ tbfuncionesClient[cf++].fptr = &EjecutaComandosPendientes;
+
/*--------------------------------------------------------------------------------------------------------
Toma direccin IP del cliente
---------------------------------------------------------------------------------------------------------*/
diff --git a/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.h b/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.h index 9539afbf..da0a5c34 100644 --- a/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.h +++ b/admin/Sources/Clients/ogAdmClient/sources/ogAdmClient.h @@ -87,7 +87,7 @@ char* tbErroresScripts[]={"Se han generado errores desconocidos. No se puede con "030-Error al restaurar imagen - Imagen mas grande que particion",\ "031-Error al realizar el comando updateCache",\ "032-Error al formatear",\ - "033-Error no definido",\ + "033-Archivo de imagen corrupto o de otra versión de partclone",\ "034-Error no definido",\ "035-Error no definido",\ "036-Error no definido",\ diff --git a/admin/Sources/Clients/ogagent/linux/Makefile b/admin/Sources/Clients/ogagent/linux/Makefile index 6ada91f5..889f07de 100644 --- a/admin/Sources/Clients/ogagent/linux/Makefile +++ b/admin/Sources/Clients/ogagent/linux/Makefile @@ -17,6 +17,7 @@ CACHES := $(shell find $(SOURCEDIR) -name '__pycache__') clean: rm -rf $(PYC) $(CACHES) $(DESTDIR) + install-ogagent: rm -rf $(DESTDIR) mkdir -p $(LIBDIR) @@ -26,12 +27,11 @@ install-ogagent: mkdir -p $(CFGDIR) mkdir -p $(XDGAUTOSTARTDIR) mkdir -p $(KDEAUTOSTARTDIR) - - mkdir $(LIBDIR)/img - + mkdir -p $(LIBDIR)/img + # Cleans up .pyc and cache folders rm -f $(PYC) $(CACHES) - + cp -r $(SOURCEDIR)/opengnsys $(LIBDIR)/opengnsys cp -r $(SOURCEDIR)/cfg $(LIBDIR)/cfg cp $(SOURCEDIR)/img/oga.png $(LIBDIR)/img @@ -40,22 +40,24 @@ install-ogagent: # QT Dialogs & resources cp $(SOURCEDIR)/*_ui.py $(LIBDIR) cp $(SOURCEDIR)/OGAgent_rc.py $(LIBDIR) - + # Version file + cp $(SOURCEDIR)/VERSION $(LIBDIR) + # Autostart elements for gnome/kde cp desktop/OGAgentTool.desktop $(XDGAUTOSTARTDIR) cp desktop/OGAgentTool.desktop $(KDEAUTOSTARTDIR) - + # scripts cp scripts/ogagent $(BINDIR) cp scripts/OGAgentTool-startup $(BINDIR) cp scripts/OGAgentTool $(BINDIR) - + # Fix permissions chmod 755 $(BINDIR)/ogagent chmod 755 $(BINDIR)/OGAgentTool-startup chmod 755 $(LIBDIR)/OGAgentUser.py chmod 600 $(LIBDIR)/cfg/ogagent.cfg - + # If for red hat based, copy init.d ifeq ($(DISTRO),rh) mkdir -p $(INITDIR) @@ -64,8 +66,7 @@ ifeq ($(DISTRO),rh) ln -fs /usr/share/OGAgent/cfg/ogagent.cfg $(CFGDIR) ln -fs /usr/share/OGAgent/cfg/ogclient.cfg $(CFGDIR) endif - - # chmod 0755 $(BINDIR)/ogagent + uninstall: rm -rf $(LIBDIR) # rm -f $(BINDIR)/ogagent diff --git a/admin/Sources/Clients/ogagent/linux/debian/control b/admin/Sources/Clients/ogagent/linux/debian/control index 34d25de7..c627c31b 100644 --- a/admin/Sources/Clients/ogagent/linux/debian/control +++ b/admin/Sources/Clients/ogagent/linux/debian/control @@ -4,12 +4,13 @@ Priority: optional Maintainer: Ramón M. Gómez <ramongomez@us.es> Build-Depends: debhelper (>= 7), po-debconf Standards-Version: 3.9.2 -Homepage: https://opengnsys.es +Homepage: https://opengnsys.es/ Package: ogagent Section: admin Priority: optional Architecture: all -Depends: policykit-1(>=0.100), python-requests (>=0.8.2), python-qt4 (>=4.9), python-six(>=1.1), python-prctl(>=1.1.1), python (>=2.7), libxss1, ${misc:Depends} +Depends: policykit-1(>=0.100), python-requests (>=0.8.2), python-qt4 (>=4.9), python-six(>=1.1), python-prctl(>=1.1.1), python-distro, python (>=2.7), libxss1, ${misc:Depends} +Recommends: gnome-shell-extension-top-icons-plus Description: OpenGnsys Agent for Operating Systems This package provides the required components to allow this machine to work on an environment managed by OpenGnsys. diff --git a/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop b/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop index fd3867d3..fd3867d3 100644..100755 --- a/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop +++ b/admin/Sources/Clients/ogagent/linux/desktop/OGAgentTool.desktop diff --git a/admin/Sources/Clients/ogagent/linux/ogagent-template.spec b/admin/Sources/Clients/ogagent/linux/ogagent-template.spec index 1368cccb..b3c7362f 100644 --- a/admin/Sources/Clients/ogagent/linux/ogagent-template.spec +++ b/admin/Sources/Clients/ogagent/linux/ogagent-template.spec @@ -8,12 +8,12 @@ BuildRoot: %{buildroot} Name: %{name} Version: %{version} Release: %{release} -Summary: OpenGnsys Agent & tools +Summary: OpenGnsys Agent for Operating Systems License: BSD3 Group: Admin -Requires: python-six python-requests PyQt4 libXScrnSaver +Requires: chkconfig initscripts python-six python-requests python-distro PyQt4 libXScrnSaver Vendor: OpenGnsys Project -URL: https://opengnsys.es +URL: https://opengnsys.es/ Provides: ogagent %define _rpmdir ../ diff --git a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool index 5b300523..5b300523 100644..100755 --- a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool +++ b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool diff --git a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup index bb3a848e..bb3a848e 100644..100755 --- a/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup +++ b/admin/Sources/Clients/ogagent/linux/scripts/OGAgentTool-startup diff --git a/admin/Sources/Clients/ogagent/linux/scripts/ogagent b/admin/Sources/Clients/ogagent/linux/scripts/ogagent index 1bcc29b0..1bcc29b0 100644..100755 --- a/admin/Sources/Clients/ogagent/linux/scripts/ogagent +++ b/admin/Sources/Clients/ogagent/linux/scripts/ogagent diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py index 0c08f95f..f3236e26 100644 --- a/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py +++ b/admin/Sources/Clients/ogagent/src/opengnsys/linux/operations.py @@ -42,6 +42,7 @@ import subprocess import struct import array import six +import distro from opengnsys import utils from .renamer import rename @@ -139,8 +140,10 @@ def getDomainName(): def getLinuxVersion(): - lv = platform.linux_distribution() - return lv[0] + ', ' + lv[1] + """ + Returns the version of the Linux distribution + """ + return distro.os_release_attr('pretty_name') def reboot(flags=0): diff --git a/admin/Sources/Clients/ogagent/src/opengnsys/operations.py b/admin/Sources/Clients/ogagent/src/opengnsys/operations.py index 1a274b20..be777dd5 100644 --- a/admin/Sources/Clients/ogagent/src/opengnsys/operations.py +++ b/admin/Sources/Clients/ogagent/src/opengnsys/operations.py @@ -47,4 +47,4 @@ else: else: from .linux.operations import * # @UnusedWildImport os_type = 'Linux' - os_version = getLinuxVersion().replace(',', '') + os_version = getLinuxVersion() diff --git a/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh b/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh index 17fbbbc7..407dd155 100755 --- a/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh +++ b/admin/Sources/Clients/ogagent/windows/py2exe-wine-linux.sh @@ -14,7 +14,6 @@ download() { wget -nd https://www.python.org/ftp/python/2.7.14/python-2.7.14.msi -O python-2.7.msi wget -nd http://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi wget -nd https://bootstrap.pypa.io/get-pip.py - wget -nd http://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/pywin32-221.win32-py2.7.exe/download -O pywin32-install.exe wget -nd http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/py2exe-0.6.9.win32-py2.7.exe/download -O py2exe-install.exe wget -nd http://prdownloads.sourceforge.net/nsis/nsis-3.0rc1-setup.exe?download -O nsis-install.exe wget -nd http://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe/download -O pyqt-install.exe @@ -27,32 +26,32 @@ install_python() { echo "Setting up wine prefix (using winetricks)" winetricks fi - + cd downloads echo "Installing python" $WINE msiexec /qn /i python-2.7.msi echo "Installing vc for python" $WINE msiexec /qn /i VCForPython27.msi - - echo "Installing pywin32 (needs X)" - $WINE pywin32-install.exe + echo "Installing py2exe (needs X)" $WINE py2exe-install.exe - echo "Installing pyqt" + echo "Installing pyqt (needs X)" $WINE pyqt-install.exe echo "Installing nsis (needs X?)" $WINE nsis-install.exe - + cd .. } setup_pip() { echo "Seting up pip..." $WINE C:\\Python27\\python -m pip install --upgrade pip -} +} install_packages() { - echo "Installing required packages" + echo "Installing pywin32" + $WINE C:\\Python27\\python -m pip install pywin32 + echo "Installing required packages" $WINE C:\\Python27\\python -m pip install requests $WINE C:\\Python27\\python -m pip install six # Using easy_install instead of pip to install pycrypto @@ -68,4 +67,3 @@ install_python setup_pip install_packages - diff --git a/admin/Sources/Includes/registrow.c b/admin/Sources/Includes/registrow.c deleted file mode 100644 index ae16eef6..00000000 --- a/admin/Sources/Includes/registrow.c +++ /dev/null @@ -1,199 +0,0 @@ -// ********************************************************************************************************************************************************
-// Aplicacin HIDRA
-// Copyright 2003-2005 Jos Manuel Alonso. Todos los derechos reservados.
-// Fichero: registro.c
-// Descripcin:
-// Este proyecto implementa el servicio hidra en un ordenador con plataforma windows NT. Este fichero aporta las funciones de
-// manipulacin del registro de Windows
-// *********************************************************************************************************************************************************
-#include "registrow.h"
-//____________________________________________________________________________________________________________________________
-//
-BOOLEAN WriteRegistryString(HKEY hive,char *key,char *subkey,char *value)
-{
- HKEY hk;
- DWORD dp,ret;
- int sz;
-
- sz=strlen(value)+1;
- if (RegCreateKeyEx(
- hive,
- key,
- 0,
- "REG_SZ",
- REG_OPTION_NON_VOLATILE,
- KEY_WRITE,
- NULL,
- &hk,
- &dp)!=ERROR_SUCCESS)
- return FALSE;
- if ((ret=RegSetValueEx(hk,subkey,0,REG_SZ,(unsigned char *)value,sz))!=ERROR_SUCCESS)
- {
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN WriteRegistryBytes(HKEY hive,char *key,char *subkey,void *value,int sz)
-{
- HKEY hk;
- DWORD dp,ret;
-
- if (RegCreateKeyEx(
- hive,
- key,
- 0,
- "REG_BINARY",
- REG_OPTION_NON_VOLATILE,
- KEY_WRITE,
- NULL,
- &hk,
- &dp)!=ERROR_SUCCESS)
- return FALSE;
- if ((ret=RegSetValueEx(hk,subkey,0,REG_BINARY,(BYTE*)value,sz))!=ERROR_SUCCESS)
- {
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN WriteRegistryInteger(HKEY hive,char *key,char *subkey,DWORD value)
-{
- HKEY hk;
- DWORD dp,ret;
- int sz;
-
- sz=sizeof(DWORD);
- if (RegCreateKeyEx(
- hive,
- key,
- 0,
- "REG_DWORD",
- REG_OPTION_NON_VOLATILE,
- KEY_WRITE,
- NULL,
- &hk,
- &dp)!=ERROR_SUCCESS)
- return FALSE;
- if ((ret=RegSetValueEx(hk,subkey,0,REG_DWORD,(BYTE*)&value,sz))!=ERROR_SUCCESS)
- {
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN ReadRegistryString(HKEY hive,char *key,char *subkey,char *value,int sz)
-{
- HKEY hk;
- DWORD type,ret;
-
- if (RegOpenKeyEx(
- hive,
- key,
- 0,
- KEY_QUERY_VALUE,
- &hk)!=ERROR_SUCCESS)
- {
- return FALSE;
- }
- if ((ret=RegQueryValueEx(hk,subkey,0,&type,(unsigned char *)value,(DWORD*)&sz))!=ERROR_SUCCESS)
- {
- RegCloseKey(hk);
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN ReadRegistryInteger(HKEY hive,char *key,char *subkey,DWORD *value)
-{
- HKEY hk;
- DWORD sz=sizeof(DWORD),type,ret;
-
- if (RegOpenKeyEx(
- hive,
- key,
- 0,
- KEY_QUERY_VALUE,
- &hk)!=ERROR_SUCCESS)
- {
- return FALSE;
- }
- if ((ret=RegQueryValueEx(hk,subkey,0,&type,(LPBYTE)value,&sz))!=ERROR_SUCCESS)
- {
- RegCloseKey(hk);
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN ReadRegistryShort(HKEY hive,char *key,char *subkey,short *value)
-{
- HKEY hk;
- DWORD sz=sizeof(DWORD),type,tmpvalue,ret;
-
- if (RegOpenKeyEx(
- hive,
- key,
- 0,
- KEY_QUERY_VALUE,
- &hk)!=ERROR_SUCCESS)
- {
- return FALSE;
- }
- if ((ret=RegQueryValueEx(hk,subkey,0,&type,(LPBYTE)&tmpvalue,&sz))!=ERROR_SUCCESS)
- {
- RegCloseKey(hk);
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- *value=(short)tmpvalue;
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN DeleteRegistryValue(HKEY hive,char *key,char *subkey)
-{
- HKEY hk;
- DWORD ret;
-
- if (RegOpenKeyEx(
- hive,
- key,
- 0,
- KEY_SET_VALUE,
- &hk)!=ERROR_SUCCESS)
- {
- return FALSE;
- }
- if ((ret=RegDeleteValue(hk,subkey))!=ERROR_SUCCESS)
- {
- RegCloseKey(hk);
- SetLastError(ret);
- return FALSE;
- }
- RegCloseKey(hk);
- return TRUE;
-}
-// _____________________________________________________________________________________________________________
-BOOLEAN DeleteRegistryKey(HKEY hive,char *key)
-{
- DWORD ret;
-
- if ((ret=RegDeleteKey(hive,key))!=ERROR_SUCCESS)
- {
- SetLastError(ret);
- return FALSE;
- }
- return TRUE;
-}
-
diff --git a/admin/Sources/Includes/registrow.h b/admin/Sources/Includes/registrow.h deleted file mode 100644 index 611d493c..00000000 --- a/admin/Sources/Includes/registrow.h +++ /dev/null @@ -1,20 +0,0 @@ -// ********************************************************************************************************************************************************
-// Aplicacin HIDRA
-// Copyright 2003-2005 Jos Manuel Alonso. Todos los derechos reservados.
-// Fichero: registro.h
-// Descripcin:
-// Este proyecto implementa el servicio hidra en un ordenador con plataforma windows NT. Este fichero aporta las funciones de
-// manipulacin del registro de Windows
-// *********************************************************************************************************************************************************
-#include <windows.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-BOOLEAN WriteRegistryString(HKEY hive,char *key,char *subkey,char *value);
-BOOLEAN WriteRegistryInteger(HKEY hive,char *key,char *subkey,DWORD value);
-BOOLEAN WriteRegistryBytes(HKEY hive,char *key,char *subkey,void *value,int sz);
-BOOLEAN ReadRegistryString(HKEY hive,char *key,char *subkey,char *value,int sz);
-BOOLEAN ReadRegistryInteger(HKEY hive,char *key,char *subkey,DWORD *value);
-BOOLEAN ReadRegistryShort(HKEY hive,char *key,char *subkey,short *value);
-BOOLEAN DeleteRegistryValue(HKEY hive,char *key,char *subkey);
-BOOLEAN DeleteRegistryKey(HKEY hive,char *key);
\ No newline at end of file diff --git a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp index 1b806a91..9c6fc419 100644 --- a/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp +++ b/admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp @@ -602,7 +602,7 @@ bool actualizaConfiguracion(Database db, Table tbl, char *cfg, int ido) lon += sprintf(tbPar + lon, "(%s, %s),", disk, par); - sprintf(sqlstr, "SELECT numdisk, numpar, codpar, tamano, uso, idsistemafichero, idnombreso" + sprintf(sqlstr, "SELECT numdisk, numpar, tamano, uso, idsistemafichero, idnombreso" " FROM ordenadores_particiones" " WHERE idordenador=%d AND numdisk=%s AND numpar=%s", ido, disk, par); @@ -627,32 +627,25 @@ bool actualizaConfiguracion(Database db, Table tbl, char *cfg, int ido) } } else { // Existe el registro swu = true; // Se supone que algún dato ha cambiado - if (!tbl.Get("codpar", dato)) { // Toma dato + if (!tbl.Get("tamano", dato)) { // Toma dato tbl.GetErrorErrStr(msglog); // Error al acceder al registro og_info(msglog); return false; } - if (strtol(cpt, NULL, 16) == dato) {// Parámetro tipo de partición (hexadecimal) igual al almacenado (decimal) - if (!tbl.Get("tamano", dato)) { // Toma dato + if (atoi(tam) == dato) { // Parámetro tamaño igual al almacenado + if (!tbl.Get("idsistemafichero", dato)) { // Toma dato tbl.GetErrorErrStr(msglog); // Error al acceder al registro og_info(msglog); return false; } - if (atoi(tam) == dato) {// Parámetro tamaño igual al almacenado - if (!tbl.Get("idsistemafichero", dato)) { // Toma dato + if (idsfi == dato) { // Parámetro sistema de fichero igual al almacenado + if (!tbl.Get("idnombreso", dato)) { // Toma dato tbl.GetErrorErrStr(msglog); // Error al acceder al registro og_info(msglog); return false; } - if (idsfi == dato) {// Parámetro sistema de fichero igual al almacenado - if (!tbl.Get("idnombreso", dato)) { // Toma dato - tbl.GetErrorErrStr(msglog); // Error al acceder al registro - og_info(msglog); - return false; - } - if (idsoi == dato) {// Parámetro sistema de fichero distinto al almacenado - swu = false; // Todos los parámetros de la partición son iguales, no se actualiza - } + if (idsoi == dato) { // Parámetro sistema operativo distinto al almacenado + swu = false; // Todos los parámetros de la partición son iguales, no se actualiza } } } @@ -670,9 +663,10 @@ bool actualizaConfiguracion(Database db, Table tbl, char *cfg, int ido) cpt, tam, uso, idsfi, idsoi, ido, disk, par); } else { // Actualizar porcentaje de uso. sprintf(sqlstr, "UPDATE ordenadores_particiones SET " + " codpar=0x%s," " uso=%s" " WHERE idordenador=%d AND numdisk=%s AND numpar=%s", - uso, ido, disk, par); + cpt, uso, ido, disk, par); } if (!db.Execute(sqlstr, tbl)) { db.GetErrorErrStr(msglog); @@ -1068,13 +1062,25 @@ static bool respuestaEstandar(TRAMA *ptrTrama, char *iph, char *ido, Database db struct tm* st; int idaccion; - ids = copiaParametro("ids",ptrTrama); // Toma identificador de la sesión + ids = copiaParametro("ids",ptrTrama); + res = copiaParametro("res",ptrTrama); - if (ids == NULL) // No existe seguimiento de la acción + if (ids == NULL) { + if (atoi(res) == ACCION_FALLIDA) { + liberaMemoria(res); + return false; + } + liberaMemoria(res); return true; + } - if (atoi(ids) == 0){ // No existe seguimiento de la acción + if (atoi(ids) == 0) { liberaMemoria(ids); + if (atoi(res) == ACCION_FALLIDA) { + liberaMemoria(res); + return false; + } + liberaMemoria(res); return true; } @@ -1103,7 +1109,6 @@ static bool respuestaEstandar(TRAMA *ptrTrama, char *iph, char *ido, Database db sprintf(fechafin, "%d/%d/%d %d:%d:%d", st->tm_year + 1900, st->tm_mon + 1, st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec); - res = copiaParametro("res",ptrTrama); // Toma resultado der = copiaParametro("der",ptrTrama); // Toma descripción del error (si hubiera habido) sprintf(sqlstr, @@ -1121,10 +1126,10 @@ static bool respuestaEstandar(TRAMA *ptrTrama, char *iph, char *ido, Database db } liberaMemoria(der); - + if (atoi(res) == ACCION_FALLIDA) { liberaMemoria(res); - return false; // Error en la ejecución del comando + return false; } liberaMemoria(res); @@ -1439,27 +1444,6 @@ static bool RESPUESTA_Arrancar(TRAMA* ptrTrama, struct og_client *cli) return true; } // ________________________________________________________________________________________________________ -// Función: Apagar -// -// Descripción: -// Procesa el comando Apagar -// Parámetros: -// - socket_c: Socket de la consola al envió el mensaje -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// true: Si el proceso es correcto -// false: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -static bool Apagar(TRAMA* ptrTrama, struct og_client *cli) -{ - if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) { - respuestaConsola(og_client_socket(cli), ptrTrama, false); - return false; - } - respuestaConsola(og_client_socket(cli), ptrTrama, true); - return true; -} -// ________________________________________________________________________________________________________ // Función: RESPUESTA_Apagar // // Descripción: @@ -1598,27 +1582,6 @@ static bool RESPUESTA_IniciarSesion(TRAMA* ptrTrama, struct og_client *cli) return true; } // ________________________________________________________________________________________________________ -// Función: CrearImagen -// -// Descripción: -// Crea una imagen de una partición de un disco y la guarda o bien en un repositorio -// Parámetros: -// - socket_c: Socket de la consola al envió el mensaje -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// true: Si el proceso es correcto -// false: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -static bool CrearImagen(TRAMA* ptrTrama, struct og_client *cli) -{ - if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) { - respuestaConsola(og_client_socket(cli), ptrTrama, false); - return false; - } - respuestaConsola(og_client_socket(cli), ptrTrama, true); - return true; -} -// ________________________________________________________________________________________________________ // Función: RESPUESTA_CrearImagen // // Descripción: @@ -1902,27 +1865,6 @@ static bool RESPUESTA_CrearSoftIncremental(TRAMA* ptrTrama, struct og_client *cl return true; } // ________________________________________________________________________________________________________ -// Función: RestaurarImagen -// -// Descripción: -// Restaura una imagen en una partición -// Parámetros: -// - socket_c: Socket de la consola al envió el mensaje -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// true: Si el proceso es correcto -// false: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -static bool RestaurarImagen(TRAMA* ptrTrama, struct og_client *cli) -{ - if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) { - respuestaConsola(og_client_socket(cli), ptrTrama, false); - return false; - } - respuestaConsola(og_client_socket(cli), ptrTrama, true); - return true; -} -// ________________________________________________________________________________________________________ // Función: RestaurarImagenBasica // // Descripción: @@ -2246,27 +2188,6 @@ static bool RESPUESTA_EjecutarScript(TRAMA* ptrTrama, struct og_client *cli) return true; } // ________________________________________________________________________________________________________ -// Función: InventarioHardware -// -// Descripción: -// Solicita al cliente un inventario de su hardware -// Parámetros: -// - socket_c: Socket de la consola al envió el mensaje -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// true: Si el proceso es correcto -// false: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -static bool InventarioHardware(TRAMA* ptrTrama, struct og_client *cli) -{ - if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) { - respuestaConsola(og_client_socket(cli), ptrTrama, false); - return false; - } - respuestaConsola(og_client_socket(cli), ptrTrama, true); - return true; -} -// ________________________________________________________________________________________________________ // Función: RESPUESTA_InventarioHardware // // Descripción: @@ -2618,27 +2539,6 @@ bool cuestionPerfilHardware(Database db, Table tbl, char *idc, char *ido, return true; } // ________________________________________________________________________________________________________ -// Función: InventarioSoftware -// -// Descripción: -// Solicita al cliente un inventario de su software -// Parámetros: -// - socket_c: Socket de la consola al envió el mensaje -// - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros -// Devuelve: -// true: Si el proceso es correcto -// false: En caso de ocurrir algún error -// ________________________________________________________________________________________________________ -static bool InventarioSoftware(TRAMA* ptrTrama, struct og_client *cli) -{ - if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) { - respuestaConsola(og_client_socket(cli), ptrTrama, false); - return false; - } - respuestaConsola(og_client_socket(cli), ptrTrama, true); - return true; -} -// ________________________________________________________________________________________________________ // Función: RESPUESTA_InventarioSoftware // // Descripción: @@ -3162,17 +3062,14 @@ static struct { { "ComandosPendientes", ComandosPendientes, }, { "DisponibilidadComandos", DisponibilidadComandos, }, { "RESPUESTA_Arrancar", RESPUESTA_Arrancar, }, - { "Apagar", Apagar, }, { "RESPUESTA_Apagar", RESPUESTA_Apagar, }, { "RESPUESTA_Reiniciar", RESPUESTA_Reiniciar, }, { "RESPUESTA_IniciarSesion", RESPUESTA_IniciarSesion, }, - { "CrearImagen", CrearImagen, }, { "RESPUESTA_CrearImagen", RESPUESTA_CrearImagen, }, { "CrearImagenBasica", CrearImagenBasica, }, { "RESPUESTA_CrearImagenBasica", RESPUESTA_CrearImagenBasica, }, { "CrearSoftIncremental", CrearSoftIncremental, }, { "RESPUESTA_CrearSoftIncremental", RESPUESTA_CrearSoftIncremental, }, - { "RestaurarImagen", RestaurarImagen, }, { "RESPUESTA_RestaurarImagen", RESPUESTA_RestaurarImagen }, { "RestaurarImagenBasica", RestaurarImagenBasica, }, { "RESPUESTA_RestaurarImagenBasica", RESPUESTA_RestaurarImagenBasica, }, @@ -3182,9 +3079,7 @@ static struct { { "RESPUESTA_Configurar", RESPUESTA_Configurar, }, { "EjecutarScript", EjecutarScript, }, { "RESPUESTA_EjecutarScript", RESPUESTA_EjecutarScript, }, - { "InventarioHardware", InventarioHardware, }, { "RESPUESTA_InventarioHardware", RESPUESTA_InventarioHardware, }, - { "InventarioSoftware", InventarioSoftware }, { "RESPUESTA_InventarioSoftware", RESPUESTA_InventarioSoftware, }, { "enviaArchivo", enviaArchivo, }, { "recibeArchivo", recibeArchivo, }, @@ -3350,6 +3245,30 @@ static int og_client_state_process_payload(struct og_client *cli) } #define OG_CLIENTS_MAX 4096 +#define OG_PARTITION_MAX 4 + +struct og_partition { + const char *number; + const char *code; + const char *size; + const char *filesystem; + const char *format; +}; + +struct og_sync_params { + const char *sync; + const char *diff; + const char *remove; + const char *compress; + const char *cleanup; + const char *cache; + const char *cleanup_cache; + const char *remove_dst; + const char *diff_id; + const char *diff_name; + const char *path; + const char *method; +}; struct og_msg_params { const char *ips_array[OG_CLIENTS_MAX]; @@ -3359,8 +3278,58 @@ struct og_msg_params { char run_cmd[4096]; const char *disk; const char *partition; + const char *repository; + const char *name; + const char *id; + const char *code; + const char *type; + const char *profile; + const char *cache; + const char *cache_size; + bool echo; + struct og_partition partition_setup[OG_PARTITION_MAX]; + struct og_sync_params sync_setup; + uint64_t flags; }; +#define OG_REST_PARAM_ADDR (1UL << 0) +#define OG_REST_PARAM_MAC (1UL << 1) +#define OG_REST_PARAM_WOL_TYPE (1UL << 2) +#define OG_REST_PARAM_RUN_CMD (1UL << 3) +#define OG_REST_PARAM_DISK (1UL << 4) +#define OG_REST_PARAM_PARTITION (1UL << 5) +#define OG_REST_PARAM_REPO (1UL << 6) +#define OG_REST_PARAM_NAME (1UL << 7) +#define OG_REST_PARAM_ID (1UL << 8) +#define OG_REST_PARAM_CODE (1UL << 9) +#define OG_REST_PARAM_TYPE (1UL << 10) +#define OG_REST_PARAM_PROFILE (1UL << 11) +#define OG_REST_PARAM_CACHE (1UL << 12) +#define OG_REST_PARAM_CACHE_SIZE (1UL << 13) +#define OG_REST_PARAM_PART_0 (1UL << 14) +#define OG_REST_PARAM_PART_1 (1UL << 15) +#define OG_REST_PARAM_PART_2 (1UL << 16) +#define OG_REST_PARAM_PART_3 (1UL << 17) +#define OG_REST_PARAM_SYNC_SYNC (1UL << 18) +#define OG_REST_PARAM_SYNC_DIFF (1UL << 19) +#define OG_REST_PARAM_SYNC_REMOVE (1UL << 20) +#define OG_REST_PARAM_SYNC_COMPRESS (1UL << 21) +#define OG_REST_PARAM_SYNC_CLEANUP (1UL << 22) +#define OG_REST_PARAM_SYNC_CACHE (1UL << 23) +#define OG_REST_PARAM_SYNC_CLEANUP_CACHE (1UL << 24) +#define OG_REST_PARAM_SYNC_REMOVE_DST (1UL << 25) +#define OG_REST_PARAM_SYNC_DIFF_ID (1UL << 26) +#define OG_REST_PARAM_SYNC_DIFF_NAME (1UL << 27) +#define OG_REST_PARAM_SYNC_PATH (1UL << 28) +#define OG_REST_PARAM_SYNC_METHOD (1UL << 29) +#define OG_REST_PARAM_ECHO (1UL << 30) + +static bool og_msg_params_validate(const struct og_msg_params *params, + const uint64_t flags) +{ + return (params->flags & flags) == flags; +} + static int og_json_parse_clients(json_t *element, struct og_msg_params *params) { unsigned int i; @@ -3376,6 +3345,153 @@ static int og_json_parse_clients(json_t *element, struct og_msg_params *params) params->ips_array[params->ips_array_len++] = json_string_value(k); + + params->flags |= OG_REST_PARAM_ADDR; + } + + return 0; +} + +static int og_json_parse_string(json_t *element, const char **str) +{ + if (json_typeof(element) != JSON_STRING) + return -1; + + *str = json_string_value(element); + return 0; +} + +static int og_json_parse_bool(json_t *element, bool *value) +{ + if (json_typeof(element) == JSON_TRUE) + *value = true; + else if (json_typeof(element) == JSON_FALSE) + *value = false; + else + return -1; + + return 0; +} + +static int og_json_parse_sync_params(json_t *element, + struct og_msg_params *params) +{ + const char *key; + json_t *value; + int err = 0; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "sync")) { + err = og_json_parse_string(value, ¶ms->sync_setup.sync); + params->flags |= OG_REST_PARAM_SYNC_SYNC; + } else if (!strcmp(key, "diff")) { + err = og_json_parse_string(value, ¶ms->sync_setup.diff); + params->flags |= OG_REST_PARAM_SYNC_DIFF; + } else if (!strcmp(key, "remove")) { + err = og_json_parse_string(value, ¶ms->sync_setup.remove); + params->flags |= OG_REST_PARAM_SYNC_REMOVE; + } else if (!strcmp(key, "compress")) { + err = og_json_parse_string(value, ¶ms->sync_setup.compress); + params->flags |= OG_REST_PARAM_SYNC_COMPRESS; + } else if (!strcmp(key, "cleanup")) { + err = og_json_parse_string(value, ¶ms->sync_setup.cleanup); + params->flags |= OG_REST_PARAM_SYNC_CLEANUP; + } else if (!strcmp(key, "cache")) { + err = og_json_parse_string(value, ¶ms->sync_setup.cache); + params->flags |= OG_REST_PARAM_SYNC_CACHE; + } else if (!strcmp(key, "cleanup_cache")) { + err = og_json_parse_string(value, ¶ms->sync_setup.cleanup_cache); + params->flags |= OG_REST_PARAM_SYNC_CLEANUP_CACHE; + } else if (!strcmp(key, "remove_dst")) { + err = og_json_parse_string(value, ¶ms->sync_setup.remove_dst); + params->flags |= OG_REST_PARAM_SYNC_REMOVE_DST; + } else if (!strcmp(key, "diff_id")) { + err = og_json_parse_string(value, ¶ms->sync_setup.diff_id); + params->flags |= OG_REST_PARAM_SYNC_DIFF_ID; + } else if (!strcmp(key, "diff_name")) { + err = og_json_parse_string(value, ¶ms->sync_setup.diff_name); + params->flags |= OG_REST_PARAM_SYNC_DIFF_NAME; + } else if (!strcmp(key, "path")) { + err = og_json_parse_string(value, ¶ms->sync_setup.path); + params->flags |= OG_REST_PARAM_SYNC_PATH; + } else if (!strcmp(key, "method")) { + err = og_json_parse_string(value, ¶ms->sync_setup.method); + params->flags |= OG_REST_PARAM_SYNC_METHOD; + } + + if (err != 0) + return err; + } + return err; +} + +#define OG_PARAM_PART_NUMBER (1UL << 0) +#define OG_PARAM_PART_CODE (1UL << 1) +#define OG_PARAM_PART_FILESYSTEM (1UL << 2) +#define OG_PARAM_PART_SIZE (1UL << 3) +#define OG_PARAM_PART_FORMAT (1UL << 4) + +static int og_json_parse_partition(json_t *element, + struct og_msg_params *params, + unsigned int i) +{ + struct og_partition *part = ¶ms->partition_setup[i]; + uint64_t flags = 0UL; + const char *key; + json_t *value; + int err = 0; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, &part->number); + flags |= OG_PARAM_PART_NUMBER; + } else if (!strcmp(key, "code")) { + err = og_json_parse_string(value, &part->code); + flags |= OG_PARAM_PART_CODE; + } else if (!strcmp(key, "filesystem")) { + err = og_json_parse_string(value, &part->filesystem); + flags |= OG_PARAM_PART_FILESYSTEM; + } else if (!strcmp(key, "size")) { + err = og_json_parse_string(value, &part->size); + flags |= OG_PARAM_PART_SIZE; + } else if (!strcmp(key, "format")) { + err = og_json_parse_string(value, &part->format); + flags |= OG_PARAM_PART_FORMAT; + } + + if (err < 0) + return err; + } + + if (flags != (OG_PARAM_PART_NUMBER | + OG_PARAM_PART_CODE | + OG_PARAM_PART_FILESYSTEM | + OG_PARAM_PART_SIZE | + OG_PARAM_PART_FORMAT)) + return -1; + + params->flags |= (OG_REST_PARAM_PART_0 << i); + + return err; +} + +static int og_json_parse_partition_setup(json_t *element, + struct og_msg_params *params) +{ + unsigned int i; + json_t *k; + + if (json_typeof(element) != JSON_ARRAY) + return -1; + + for (i = 0; i < json_array_size(element) && i < OG_PARTITION_MAX; ++i) { + k = json_array_get(element, i); + + if (json_typeof(k) != JSON_OBJECT) + return -1; + + if (og_json_parse_partition(k, params, i) != 0) + return -1; } return 0; } @@ -3419,6 +3535,9 @@ static int og_cmd_post_clients(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "Sondeo", CLIENTE_APAGADO); } @@ -3505,12 +3624,16 @@ static int og_json_parse_target(json_t *element, struct og_msg_params *params) params->ips_array[params->ips_array_len] = json_string_value(value); + + params->flags |= OG_REST_PARAM_ADDR; } else if (!strcmp(key, "mac")) { if (json_typeof(value) != JSON_STRING) return -1; params->mac_array[params->ips_array_len] = json_string_value(value); + + params->flags |= OG_REST_PARAM_MAC; } } @@ -3556,6 +3679,8 @@ static int og_json_parse_type(json_t *element, struct og_msg_params *params) else if (!strcmp(type, "broadcast")) params->wol_type = "1"; + params->flags |= OG_REST_PARAM_WOL_TYPE; + return 0; } @@ -3579,6 +3704,11 @@ static int og_cmd_wol(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_MAC | + OG_REST_PARAM_WOL_TYPE)) + return -1; + if (!Levanta((char **)params->ips_array, (char **)params->mac_array, params->ips_array_len, (char *)params->wol_type)) return -1; @@ -3594,6 +3724,8 @@ static int og_json_parse_run(json_t *element, struct og_msg_params *params) snprintf(params->run_cmd, sizeof(params->run_cmd), "%s", json_string_value(element)); + params->flags |= OG_REST_PARAM_RUN_CMD; + return 0; } @@ -3612,19 +3744,36 @@ static int og_cmd_run_post(json_t *element, struct og_msg_params *params) json_object_foreach(element, key, value) { if (!strcmp(key, "clients")) err = og_json_parse_clients(value, params); - if (!strcmp(key, "run")) + else if (!strcmp(key, "run")) err = og_json_parse_run(value, params); + else if (!strcmp(key, "echo")) { + err = og_json_parse_bool(value, ¶ms->echo); + params->flags |= OG_REST_PARAM_ECHO; + } if (err < 0) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_RUN_CMD | + OG_REST_PARAM_ECHO)) + return -1; + for (i = 0; i < params->ips_array_len; i++) { len = snprintf(iph + strlen(iph), sizeof(iph), "%s;", params->ips_array[i]); } - len = snprintf(buf, sizeof(buf), "nfn=ConsolaRemota\riph=%s\rscp=%s\r", - iph, params->run_cmd); + + if (params->echo) { + len = snprintf(buf, sizeof(buf), + "nfn=ConsolaRemota\riph=%s\rscp=%s\r", + iph, params->run_cmd); + } else { + len = snprintf(buf, sizeof(buf), + "nfn=EjecutarScript\riph=%s\rscp=%s\r", + iph, params->run_cmd); + } msg = og_msg_alloc(buf, len); if (!msg) @@ -3673,6 +3822,9 @@ static int og_cmd_run_get(json_t *element, struct og_msg_params *params, return err; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + array = json_array(); if (!array) return -1; @@ -3731,27 +3883,6 @@ static int og_cmd_run_get(json_t *element, struct og_msg_params *params, return 0; } -static int og_json_parse_disk(json_t *element, struct og_msg_params *params) -{ - if (json_typeof(element) != JSON_STRING) - return -1; - - params->disk = json_string_value(element); - - return 0; -} - -static int og_json_parse_partition(json_t *element, - struct og_msg_params *params) -{ - if (json_typeof(element) != JSON_STRING) - return -1; - - params->partition = json_string_value(element); - - return 0; -} - static int og_cmd_session(json_t *element, struct og_msg_params *params) { char buf[4096], iph[4096]; @@ -3768,15 +3899,22 @@ static int og_cmd_session(json_t *element, struct og_msg_params *params) if (!strcmp(key, "clients")) { err = og_json_parse_clients(value, params); } else if (!strcmp(key, "disk")) { - err = og_json_parse_disk(value, params); + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; } else if (!strcmp(key, "partition")) { - err = og_json_parse_partition(value, params); + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; } if (err < 0) return err; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION)) + return -1; + for (i = 0; i < params->ips_array_len; i++) { snprintf(iph + strlen(iph), sizeof(iph), "%s;", params->ips_array[i]); @@ -3815,6 +3953,9 @@ static int og_cmd_poweroff(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "Apagar", CLIENTE_OCUPADO); } @@ -3835,6 +3976,9 @@ static int og_cmd_refresh(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "Actualizar", CLIENTE_APAGADO); } @@ -3855,6 +3999,9 @@ static int og_cmd_reboot(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "Reiniciar", CLIENTE_OCUPADO); } @@ -3875,6 +4022,9 @@ static int og_cmd_stop(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "Purgar", CLIENTE_APAGADO); } @@ -3895,29 +4045,618 @@ static int og_cmd_hardware(json_t *element, struct og_msg_params *params) break; } + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + return og_cmd_legacy_send(params, "InventarioHardware", CLIENTE_OCUPADO); } static int og_cmd_software(json_t *element, struct og_msg_params *params) { + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) + err = og_json_parse_clients(value, params); + else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } + else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=InventarioSoftware\rdsk=%s\rpar=%s\r", + params->disk, params->partition); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_create_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } else if (!strcmp(key, "code")) { + err = og_json_parse_string(value, ¶ms->code); + params->flags |= OG_REST_PARAM_CODE; + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_CODE | + OG_REST_PARAM_ID | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=CrearImagen\rdsk=%s\rpar=%s\rcpt=%s\ridi=%s\rnci=%s\ripr=%s\r", + params->disk, params->partition, params->code, + params->id, params->name, params->repository); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_restore_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "type")) { + err = og_json_parse_string(value, ¶ms->type); + params->flags |= OG_REST_PARAM_TYPE; + } else if (!strcmp(key, "profile")) { + err = og_json_parse_string(value, ¶ms->profile); + params->flags |= OG_REST_PARAM_PROFILE; + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO | + OG_REST_PARAM_TYPE | + OG_REST_PARAM_PROFILE | + OG_REST_PARAM_ID)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=RestaurarImagen\ridi=%s\rdsk=%s\rpar=%s\rifs=%s\r" + "nci=%s\ripr=%s\rptc=%s\r", + params->id, params->disk, params->partition, + params->profile, params->name, + params->repository, params->type); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_setup(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "cache")) { + err = og_json_parse_string(value, ¶ms->cache); + params->flags |= OG_REST_PARAM_CACHE; + } else if (!strcmp(key, "cache_size")) { + err = og_json_parse_string(value, ¶ms->cache_size); + params->flags |= OG_REST_PARAM_CACHE_SIZE; + } else if (!strcmp(key, "partition_setup")) { + err = og_json_parse_partition_setup(value, params); + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_CACHE | + OG_REST_PARAM_CACHE_SIZE | + OG_REST_PARAM_PART_0 | + OG_REST_PARAM_PART_1 | + OG_REST_PARAM_PART_2 | + OG_REST_PARAM_PART_3)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=Configurar\rdsk=%s\rcfg=dis=%s*che=%s*tch=%s!", + params->disk, params->disk, params->cache, params->cache_size); + + for (unsigned int i = 0; i < OG_PARTITION_MAX; ++i) { + const struct og_partition *part = ¶ms->partition_setup[i]; + + len += snprintf(buf + strlen(buf), sizeof(buf), + "par=%s*cpt=%s*sfi=%s*tam=%s*ope=%s%%", + part->number, part->code, part->filesystem, part->size, part->format); + } + + msg = og_msg_alloc(buf, len + 1); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_run_schedule(json_t *element, struct og_msg_params *params) +{ const char *key; json_t *value; int err = 0; + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) + err = og_json_parse_clients(value, params); + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR)) + return -1; + + og_cmd_legacy_send(params, "EjecutaComandosPendientes", CLIENTE_OCUPADO); + + return 0; +} + +static int og_cmd_create_basic_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "code")) { + err = og_json_parse_string(value, ¶ms->code); + params->flags |= OG_REST_PARAM_CODE; + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "sync_params")) { + err = og_json_parse_sync_params(value, params); + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_CODE | + OG_REST_PARAM_ID | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO | + OG_REST_PARAM_SYNC_SYNC | + OG_REST_PARAM_SYNC_DIFF | + OG_REST_PARAM_SYNC_REMOVE | + OG_REST_PARAM_SYNC_COMPRESS | + OG_REST_PARAM_SYNC_CLEANUP | + OG_REST_PARAM_SYNC_CACHE | + OG_REST_PARAM_SYNC_CLEANUP_CACHE | + OG_REST_PARAM_SYNC_REMOVE_DST)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=CrearImagenBasica\rdsk=%s\rpar=%s\rcpt=%s\ridi=%s\r" + "nci=%s\ripr=%s\rrti=\rmsy=%s\rwhl=%s\reli=%s\rcmp=%s\rbpi=%s\r" + "cpc=%s\rbpc=%s\rnba=%s\r", + params->disk, params->partition, params->code, params->id, + params->name, params->repository, params->sync_setup.sync, + params->sync_setup.diff, params->sync_setup.remove, + params->sync_setup.compress, params->sync_setup.cleanup, + params->sync_setup.cache, params->sync_setup.cleanup_cache, + params->sync_setup.remove_dst); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_create_incremental_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + if (json_typeof(element) != JSON_OBJECT) return -1; json_object_foreach(element, key, value) { if (!strcmp(key, "clients")) err = og_json_parse_clients(value, params); + else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "sync_params")) { + err = og_json_parse_sync_params(value, params); + } if (err < 0) break; } - return og_cmd_legacy_send(params, "InventarioSoftware", - CLIENTE_OCUPADO); + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_ID | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO | + OG_REST_PARAM_SYNC_SYNC | + OG_REST_PARAM_SYNC_PATH | + OG_REST_PARAM_SYNC_DIFF | + OG_REST_PARAM_SYNC_DIFF_ID | + OG_REST_PARAM_SYNC_DIFF_NAME | + OG_REST_PARAM_SYNC_REMOVE | + OG_REST_PARAM_SYNC_COMPRESS | + OG_REST_PARAM_SYNC_CLEANUP | + OG_REST_PARAM_SYNC_CACHE | + OG_REST_PARAM_SYNC_CLEANUP_CACHE | + OG_REST_PARAM_SYNC_REMOVE_DST)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=CrearSoftIncremental\rdsk=%s\rpar=%s\ridi=%s\rnci=%s\r" + "rti=%s\ripr=%s\ridf=%s\rncf=%s\rmsy=%s\rwhl=%s\reli=%s\rcmp=%s\r" + "bpi=%s\rcpc=%s\rbpc=%s\rnba=%s\r", + params->disk, params->partition, params->id, params->name, + params->sync_setup.path, params->repository, params->sync_setup.diff_id, + params->sync_setup.diff_name, params->sync_setup.sync, + params->sync_setup.diff, params->sync_setup.remove_dst, + params->sync_setup.compress, params->sync_setup.cleanup, + params->sync_setup.cache, params->sync_setup.cleanup_cache, + params->sync_setup.remove_dst); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_restore_basic_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "profile")) { + err = og_json_parse_string(value, ¶ms->profile); + params->flags |= OG_REST_PARAM_PROFILE; + } else if (!strcmp(key, "type")) { + err = og_json_parse_string(value, ¶ms->type); + params->flags |= OG_REST_PARAM_TYPE; + } else if (!strcmp(key, "sync_params")) { + err = og_json_parse_sync_params(value, params); + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_ID | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO | + OG_REST_PARAM_PROFILE | + OG_REST_PARAM_TYPE | + OG_REST_PARAM_SYNC_PATH | + OG_REST_PARAM_SYNC_METHOD | + OG_REST_PARAM_SYNC_SYNC | + OG_REST_PARAM_SYNC_DIFF | + OG_REST_PARAM_SYNC_REMOVE | + OG_REST_PARAM_SYNC_COMPRESS | + OG_REST_PARAM_SYNC_CLEANUP | + OG_REST_PARAM_SYNC_CACHE | + OG_REST_PARAM_SYNC_CLEANUP_CACHE | + OG_REST_PARAM_SYNC_REMOVE_DST)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=RestaurarImagenBasica\rdsk=%s\rpar=%s\ridi=%s\rnci=%s\r" + "ipr=%s\rifs=%s\rrti=%s\rmet=%s\rmsy=%s\rtpt=%s\rwhl=%s\r" + "eli=%s\rcmp=%s\rbpi=%s\rcpc=%s\rbpc=%s\rnba=%s\r", + params->disk, params->partition, params->id, params->name, + params->repository, params->profile, params->sync_setup.path, + params->sync_setup.method, params->sync_setup.sync, params->type, + params->sync_setup.diff, params->sync_setup.remove, + params->sync_setup.compress, params->sync_setup.cleanup, + params->sync_setup.cache, params->sync_setup.cleanup_cache, + params->sync_setup.remove_dst); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; +} + +static int og_cmd_restore_incremental_image(json_t *element, struct og_msg_params *params) +{ + char buf[4096] = {}; + int err = 0, len; + const char *key; + json_t *value; + TRAMA *msg; + + if (json_typeof(element) != JSON_OBJECT) + return -1; + + json_object_foreach(element, key, value) { + if (!strcmp(key, "clients")) { + err = og_json_parse_clients(value, params); + } else if (!strcmp(key, "disk")) { + err = og_json_parse_string(value, ¶ms->disk); + params->flags |= OG_REST_PARAM_DISK; + } else if (!strcmp(key, "partition")) { + err = og_json_parse_string(value, ¶ms->partition); + params->flags |= OG_REST_PARAM_PARTITION; + } else if (!strcmp(key, "id")) { + err = og_json_parse_string(value, ¶ms->id); + params->flags |= OG_REST_PARAM_ID; + } else if (!strcmp(key, "name")) { + err = og_json_parse_string(value, ¶ms->name); + params->flags |= OG_REST_PARAM_NAME; + } else if (!strcmp(key, "repository")) { + err = og_json_parse_string(value, ¶ms->repository); + params->flags |= OG_REST_PARAM_REPO; + } else if (!strcmp(key, "profile")) { + err = og_json_parse_string(value, ¶ms->profile); + params->flags |= OG_REST_PARAM_PROFILE; + } else if (!strcmp(key, "type")) { + err = og_json_parse_string(value, ¶ms->type); + params->flags |= OG_REST_PARAM_TYPE; + } else if (!strcmp(key, "sync_params")) { + err = og_json_parse_sync_params(value, params); + } + + if (err < 0) + break; + } + + if (!og_msg_params_validate(params, OG_REST_PARAM_ADDR | + OG_REST_PARAM_DISK | + OG_REST_PARAM_PARTITION | + OG_REST_PARAM_ID | + OG_REST_PARAM_NAME | + OG_REST_PARAM_REPO | + OG_REST_PARAM_PROFILE | + OG_REST_PARAM_TYPE | + OG_REST_PARAM_SYNC_DIFF_ID | + OG_REST_PARAM_SYNC_DIFF_NAME | + OG_REST_PARAM_SYNC_PATH | + OG_REST_PARAM_SYNC_METHOD | + OG_REST_PARAM_SYNC_SYNC | + OG_REST_PARAM_SYNC_DIFF | + OG_REST_PARAM_SYNC_REMOVE | + OG_REST_PARAM_SYNC_COMPRESS | + OG_REST_PARAM_SYNC_CLEANUP | + OG_REST_PARAM_SYNC_CACHE | + OG_REST_PARAM_SYNC_CLEANUP_CACHE | + OG_REST_PARAM_SYNC_REMOVE_DST)) + return -1; + + len = snprintf(buf, sizeof(buf), + "nfn=RestaurarSoftIncremental\rdsk=%s\rpar=%s\ridi=%s\rnci=%s\r" + "ipr=%s\rifs=%s\ridf=%s\rncf=%s\rrti=%s\rmet=%s\rmsy=%s\r" + "tpt=%s\rwhl=%s\reli=%s\rcmp=%s\rbpi=%s\rcpc=%s\rbpc=%s\r" + "nba=%s\r", + params->disk, params->partition, params->id, params->name, + params->repository, params->profile, params->sync_setup.diff_id, + params->sync_setup.diff_name, params->sync_setup.path, + params->sync_setup.method, params->sync_setup.sync, params->type, + params->sync_setup.diff, params->sync_setup.remove, + params->sync_setup.compress, params->sync_setup.cleanup, + params->sync_setup.cache, params->sync_setup.cleanup_cache, + params->sync_setup.remove_dst); + + msg = og_msg_alloc(buf, len); + if (!msg) + return -1; + + og_send_cmd((char **)params->ips_array, params->ips_array_len, + CLIENTE_OCUPADO, msg); + + og_msg_free(msg); + + return 0; } static int og_client_method_not_found(struct og_client *cli) @@ -4142,6 +4881,83 @@ static int og_client_state_process_payload_rest(struct og_client *cli) return og_client_bad_request(cli); } err = og_cmd_software(root, ¶ms); + } else if (!strncmp(cmd, "image/create/basic", + strlen("image/create/basic"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_create_basic_image(root, ¶ms); + } else if (!strncmp(cmd, "image/create/incremental", + strlen("image/create/incremental"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_create_incremental_image(root, ¶ms); + } else if (!strncmp(cmd, "image/create", strlen("image/create"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_create_image(root, ¶ms); + } else if (!strncmp(cmd, "image/restore/basic", + strlen("image/restore/basic"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_restore_basic_image(root, ¶ms); + } else if (!strncmp(cmd, "image/restore/incremental", + strlen("image/restore/incremental"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_restore_incremental_image(root, ¶ms); + } else if (!strncmp(cmd, "image/restore", strlen("image/restore"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_restore_image(root, ¶ms); + } else if (!strncmp(cmd, "setup", strlen("setup"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + err = og_cmd_setup(root, ¶ms); + } else if (!strncmp(cmd, "run/schedule", strlen("run/schedule"))) { + if (method != OG_METHOD_POST) + return og_client_method_not_found(cli); + + if (!root) { + syslog(LOG_ERR, "command create with no payload\n"); + return og_client_bad_request(cli); + } + + err = og_cmd_run_schedule(root, ¶ms); } else { syslog(LOG_ERR, "unknown command: %.32s ...\n", cmd); err = og_client_not_found(cli); @@ -4151,7 +4967,7 @@ static int og_client_state_process_payload_rest(struct og_client *cli) json_decref(root); if (err < 0) - return err; + return og_client_bad_request(cli); err = og_client_ok(cli, buf_reply); if (err < 0) { diff --git a/admin/Sources/Services/ogAdmServer/tests/create_basic_image.json b/admin/Sources/Services/ogAdmServer/tests/create_basic_image.json new file mode 100644 index 00000000..8000219a --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/create_basic_image.json @@ -0,0 +1 @@ +{"clients":["192.168.56.11"],"disk":"1","partition":"1","code":"131","id":"8","name":"debianbasica","repository":"192.168.56.10","sync_params":{"sync":"1","diff":"0","remove":"1","compress":"0","cleanup":"0","cache":"0","cleanup_cache":"0","remove_dst":"0"}} diff --git a/admin/Sources/Services/ogAdmServer/tests/create_image.json b/admin/Sources/Services/ogAdmServer/tests/create_image.json new file mode 100644 index 00000000..bd4ab215 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/create_image.json @@ -0,0 +1 @@ +{ "clients" : [ "192.168.2.1" ], "disk" : "1", "partition" : "1", "code" : "1", "id" : "1", "name" : "test", "repository" : "192.168.2.4" } diff --git a/admin/Sources/Services/ogAdmServer/tests/create_incremental_image.json b/admin/Sources/Services/ogAdmServer/tests/create_incremental_image.json new file mode 100644 index 00000000..94b3a4d0 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/create_incremental_image.json @@ -0,0 +1 @@ +{"clients":["192.168.56.11"], "disk":"1", "partition":"1", "id":"3", "name":"basica1", "repository":"192.168.56.10", "sync_params":{"sync":"1", "path":"", "diff":"0", "diff_id":"4", "diff_name":"p2", "remove":"1", "compress":"0", "cleanup":"0", "cache":"0", "cleanup_cache":"0", "remove_dst":"0"}} diff --git a/admin/Sources/Services/ogAdmServer/tests/restore_basic_image.json b/admin/Sources/Services/ogAdmServer/tests/restore_basic_image.json new file mode 100644 index 00000000..255507c0 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/restore_basic_image.json @@ -0,0 +1 @@ +{"clients":["192.168.56.11"],"disk":"1","partition":"1","id":"9","name":"test","repository":"192.168.56.10","profile":"17","type":"UNICAST","sync_params":{"path":"","method":"1","sync":"1","diff":"0","remove":"1","compress":"0","cleanup":"0","cache":"0","cleanup_cache":"0","remove_dst":"0"}} diff --git a/admin/Sources/Services/ogAdmServer/tests/restore_image.json b/admin/Sources/Services/ogAdmServer/tests/restore_image.json new file mode 100644 index 00000000..bf2982ab --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/restore_image.json @@ -0,0 +1 @@ +{ "clients" : [ "192.168.56.11" ], "disk" : "1", "partition" : "1", "name" : "test", "repository" : "192.168.56.10", "type" : "UNICAST", "profile": "1", "id": "1"} diff --git a/admin/Sources/Services/ogAdmServer/tests/restore_incremental_image.json b/admin/Sources/Services/ogAdmServer/tests/restore_incremental_image.json new file mode 100644 index 00000000..66dfd0a2 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/restore_incremental_image.json @@ -0,0 +1 @@ +{"clients":["192.168.56.11"],"disk":"1","partition":"1","id":"9","name":"test","repository":"192.168.56.10","profile":"17","type":"UNICAST","sync_params":{"diff_id":"1","diff_name":"test","path":"","method":"1","sync":"1","diff":"0","remove":"1","compress":"0","cleanup":"0","cache":"0","cleanup_cache":"0","remove_dst":"0"}} diff --git a/admin/Sources/Services/ogAdmServer/tests/run-tests.sh b/admin/Sources/Services/ogAdmServer/tests/run-tests.sh index f22df02a..893e0264 100755 --- a/admin/Sources/Services/ogAdmServer/tests/run-tests.sh +++ b/admin/Sources/Services/ogAdmServer/tests/run-tests.sh @@ -12,3 +12,11 @@ curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/stop -d @stop.js curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/refresh -d @refresh.json curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/hardware -d @post_clients.json curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/software -d @post_clients.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/create -d @create_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/restore -d @restore_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/setup -d @setup_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/create/basic -d @create_basic_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/create/incremental -d @create_incremental_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/restore/basic -d @restore_basic_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/image/restore/incremental -d @restore_incremental_image.json +curl -X POST -H "Authorization: $API_KEY" http://127.0.0.1:8888/run/schedule -d @run_schedule.json diff --git a/admin/Sources/Services/ogAdmServer/tests/run_schedule.json b/admin/Sources/Services/ogAdmServer/tests/run_schedule.json new file mode 100644 index 00000000..60a10349 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/run_schedule.json @@ -0,0 +1 @@ +{"clients":["192.168.56.11"]} diff --git a/admin/Sources/Services/ogAdmServer/tests/setup_image.json b/admin/Sources/Services/ogAdmServer/tests/setup_image.json new file mode 100644 index 00000000..0135e207 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/setup_image.json @@ -0,0 +1 @@ +{ "clients" : [ "192.168.56.11" ], "disk" : "1", "cache" : "1", "cache_size" : "0", "partition_setup": [{"partition": "1", "code": "LINUX", "filesystem": "EMPTY", "size": "498688", "format": "0"}, {"partition": "2", "code": "LINUX-SWAP", "filesystem": "EMPTY", "size": "199987", "format": "0"}, {"partition": "3", "code": "LINUX", "filesystem": "EMPTY", "size": "31053824", "format": "0"}, {"partition": "4", "code": "EMPTY", "filesystem": "EMPTY", "size": "0", "format": "0"}]} diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0002_post_clients.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0002_post_clients.py index 1aae349e..3e0d4e5d 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0002_post_clients.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0002_post_clients.py @@ -12,5 +12,13 @@ class TestPostClientsMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + if __name__ == '__main__': unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0003_post_wol.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0003_post_wol.py index e997aff6..5c8c012a 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0003_post_wol.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0003_post_wol.py @@ -13,6 +13,19 @@ class TestPostWolMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0004_post_shell_run.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0004_post_shell_run.py index 2a330be9..11779da4 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0004_post_shell_run.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0004_post_shell_run.py @@ -6,12 +6,27 @@ class TestPostShellRunMethods(unittest.TestCase): def setUp(self): self.url = 'http://localhost:8888/shell/run' self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} - self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], 'run' : 'ls' } + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'run' : 'ls', + 'echo': True} def test_post(self): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0005_post_shell_output.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0005_post_shell_output.py index 1c6f7a3a..dec9ccd0 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0005_post_shell_output.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0005_post_shell_output.py @@ -12,6 +12,14 @@ class TestPostShellOutputMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0006_post_session.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0006_post_session.py index 544ae2ab..ba6179f2 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0006_post_session.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0006_post_session.py @@ -13,6 +13,19 @@ class TestPostSessionMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0007_post_poweroff.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0007_post_poweroff.py index d2d5b15d..3c262656 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0007_post_poweroff.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0007_post_poweroff.py @@ -12,6 +12,14 @@ class TestPostPoweroffMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0008_post_reboot.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0008_post_reboot.py index 5ac4dc24..6705e87f 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0008_post_reboot.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0008_post_reboot.py @@ -12,6 +12,14 @@ class TestPostRebootMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0009_post_stop.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0009_post_stop.py index 7aa96ff8..68b1b7c6 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0009_post_stop.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0009_post_stop.py @@ -12,6 +12,14 @@ class TestPostStopMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0010_post_refresh.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0010_post_refresh.py index 745bdbe5..0df3c60f 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0010_post_refresh.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0010_post_refresh.py @@ -12,6 +12,14 @@ class TestPostRefreshMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0011_post_hardware.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0011_post_hardware.py index 6d9c16a9..1f3e1604 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0011_post_hardware.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0011_post_hardware.py @@ -12,6 +12,14 @@ class TestPostHardwareMethods(unittest.TestCase): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0012_post_software.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0012_post_software.py index 049a3ec8..3a00d467 100644 --- a/admin/Sources/Services/ogAdmServer/tests/units/test_0012_post_software.py +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0012_post_software.py @@ -6,12 +6,27 @@ class TestPostSoftwareMethods(unittest.TestCase): def setUp(self): self.url = 'http://localhost:8888/software' self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} - self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ] } + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk' : '0', + 'partition' : '1' } def test_post(self): returned = requests.post(self.url, headers=self.headers, json=self.json) self.assertEqual(returned.status_code, 200) + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + def test_get(self): returned = requests.get(self.url, headers=self.headers) self.assertEqual(returned.status_code, 405) diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0016_post_image_create.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0016_post_image_create.py new file mode 100644 index 00000000..fb6eb975 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0016_post_image_create.py @@ -0,0 +1,39 @@ +import requests +import unittest + +class TestPostCreateImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/create' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk' : '1', + 'partition' : '1', + 'code' : '1', + 'id' : '1', + 'name' : 'test', + 'repository' : '192.168.2.4' } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0017_post_image_restore.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0017_post_image_restore.py new file mode 100644 index 00000000..1bdeacb5 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0017_post_image_restore.py @@ -0,0 +1,40 @@ +import requests +import unittest + +class TestPostRestoreImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/restore' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk' : '1', + 'partition' : '1', + 'name' : 'test', + 'repository' : '192.168.56.10', + 'type' : 'UNICAST', + 'profile': '1', + 'id': '1' } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0018_post_setup.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0018_post_setup.py new file mode 100644 index 00000000..16fc1d4e --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0018_post_setup.py @@ -0,0 +1,56 @@ +import requests +import unittest + +class TestPostSetupMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/setup' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk' : '1', + 'cache' : '1', + 'cache_size' : '0', + 'partition_setup': [{'partition': '1', + 'code': 'LINUX', + 'filesystem': 'EMPTY', + 'size': '498688', + 'format': '0'}, + {'partition': '2', + 'code': 'LINUX-SWAP', + 'filesystem': 'EMPTY', + 'size': '199987', + 'format': '0'}, + {'partition': '3', + 'code': 'LINUX', + 'filesystem': 'EMPTY', + 'size': '31053824', + 'format': '0'}, + {'partition': '4', + 'code': 'EMPTY', + 'filesystem': 'EMPTY', + 'size': '0', + 'format': '0'}] } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0019_post_image_create_basic.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0019_post_image_create_basic.py new file mode 100644 index 00000000..9d05b99d --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0019_post_image_create_basic.py @@ -0,0 +1,47 @@ +import requests +import unittest + +class TestPostCreateBasicImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/create/basic' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk': '1', + 'partition': '1', + 'code': '131', + 'id': '8', + 'name': 'debianbasica', + 'repository': '192.168.56.10', + 'sync_params':{'sync': '1', + 'diff': '0', + 'remove': '1', + 'compress': '0', + 'cleanup': '0', + 'cache': '0', + 'cleanup_cache': '0', + 'remove_dst': '0'} } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0020_post_image_create_incremental.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0020_post_image_create_incremental.py new file mode 100644 index 00000000..c677e270 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0020_post_image_create_incremental.py @@ -0,0 +1,49 @@ +import requests +import unittest + +class TestPostCreateIncrementalImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/create/incremental' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk': '1', + 'partition': '1', + 'id': '3', + 'name': 'basica1', + 'repository': '192.168.56.10', + 'sync_params':{'sync': '1', + 'path': '', + 'diff': '0', + 'diff_id': '4', + 'diff_name': 'p2', + 'remove': '1', + 'compress': '0', + 'cleanup': '0', + 'cache': '0', + 'cleanup_cache': '0', + 'remove_dst': '0'} } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0021_post_image_restore_basic.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0021_post_image_restore_basic.py new file mode 100644 index 00000000..efe8a61c --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0021_post_image_restore_basic.py @@ -0,0 +1,50 @@ +import requests +import unittest + +class TestPostRestoreBasicImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/restore/basic' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk': '1', + 'partition': '1', + 'id': '9', + 'name': 'test', + 'repository': '192.168.56.10', + 'profile': '17', + 'type': 'UNICAST', + 'sync_params':{'path': '', + 'method': '1', + 'sync': '1', + 'diff': '0', + 'remove': '1', + 'compress': '0', + 'cleanup': '0', + 'cache': '0', + 'cleanup_cache': '0', + 'remove_dst': '0'} } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0022_post_image_restore_incremental.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0022_post_image_restore_incremental.py new file mode 100644 index 00000000..ad7727f1 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0022_post_image_restore_incremental.py @@ -0,0 +1,52 @@ +import requests +import unittest + +class TestPostRestoreIncrementalImageMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/image/restore/incremental' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ], + 'disk': '1', + 'partition': '1', + 'id': '9', + 'name': 'test', + 'repository': '192.168.56.10', + 'profile': '17', + 'type': 'UNICAST', + 'sync_params':{'diff_id': '1', + 'diff_name': 'test', + 'path': '', + 'method': '1', + 'sync': '1', + 'diff': '0', + 'remove': '1', + 'compress': '0', + 'cleanup': '0', + 'cache': '0', + 'cleanup_cache': '0', + 'remove_dst': '0'} } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + for parameter in self.json: + malformed_payload = self.json.copy() + malformed_payload.pop(parameter) + returned = requests.post(self.url, + headers=self.headers, + json=malformed_payload) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/Sources/Services/ogAdmServer/tests/units/test_0023_post_run_schedule.py b/admin/Sources/Services/ogAdmServer/tests/units/test_0023_post_run_schedule.py new file mode 100644 index 00000000..3b923049 --- /dev/null +++ b/admin/Sources/Services/ogAdmServer/tests/units/test_0023_post_run_schedule.py @@ -0,0 +1,28 @@ +import requests +import unittest + +class TestPostRunScheduleMethods(unittest.TestCase): + + def setUp(self): + self.url = 'http://localhost:8888/run/schedule' + self.headers = {'Authorization' : '07b3bfe728954619b58f0107ad73acc1'} + self.json = { 'clients' : [ '192.168.2.1', '192.168.2.2' ] } + + def test_post(self): + returned = requests.post(self.url, headers=self.headers, json=self.json) + self.assertEqual(returned.status_code, 200) + + def test_no_payload(self): + returned = requests.post(self.url, headers=self.headers, json=None) + self.assertEqual(returned.status_code, 400) + + def test_malformed_payload(self): + returned = requests.post(self.url, headers=self.headers, json={}) + self.assertEqual(returned.status_code, 400) + + def test_get(self): + returned = requests.get(self.url, headers=self.headers) + self.assertEqual(returned.status_code, 405) + +if __name__ == '__main__': + unittest.main() diff --git a/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php b/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php index cf6587cc..32e051ac 100644 --- a/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php +++ b/admin/WebConsole/asistentes/AsistenteCloneRemotePartition.php @@ -19,6 +19,13 @@ include_once("../includes/CreaComando.php"); include_once("../includes/HTMLSELECT.php"); include_once("../idiomas/php/".$idioma."/comandos/ejecutarscripts_".$idioma.".php"); include_once("../idiomas/php/".$idioma."/comandos/opcionesacciones_".$idioma.".php"); + +include_once("../includes/HTMLCTESELECT.php"); +include_once("../includes/TomaDato.php"); +include_once("../includes/ConfiguracionesParticiones.php"); +include_once("../includes/RecopilaIpesMacs.php"); +include_once("./includes/asistentes/AyudanteFormularios.php"); + //________________________________________________________________________________________________________ include_once("./includes/capturaacciones.php"); //________________________________________________________________________________________________________ @@ -74,6 +81,10 @@ switch($ambito){ echo '<p align=center><span class=cabeceras>'.$TbMsg["WCRP31"].' </span><br>'; echo '<IMG src="'.$urlimg.'"> <span align=center class=subcabeceras> <U>'.$TbMsg[6].': '.$textambito.','.$nombreambito.'</U></span> </span></p>'; + + $sws=$fk_sysFi | $fk_nombreSO | $fk_tamano | $fk_imagen | $fk_perfil | $fk_cache; + pintaConfiguraciones($cmd,$idambito,$ambito,9,$sws,false); + ?> diff --git a/admin/WebConsole/asistentes/AsistenteDeployImage.php b/admin/WebConsole/asistentes/AsistenteDeployImage.php index b7f3596d..ddf38e67 100644 --- a/admin/WebConsole/asistentes/AsistenteDeployImage.php +++ b/admin/WebConsole/asistentes/AsistenteDeployImage.php @@ -46,6 +46,7 @@ if (!$cmd) <SCRIPT language="javascript" src="./jscripts/asistentes.js"></SCRIPT> <?php echo '<SCRIPT language="javascript" src="../idiomas/javascripts/'.$idioma.'/comandos/ejecutarscripts_'.$idioma.'.js"></SCRIPT>'?> <?php echo '<SCRIPT language="javascript" src="../idiomas/javascripts/'.$idioma.'/comandos/comunescomandos_'.$idioma.'.js"></SCRIPT>'?> + <?php echo '<SCRIPT language="javascript" src="../idiomas/javascripts/'.$idioma.'/asistentes_'.$idioma.'.js"></SCRIPT>'?> </head> diff --git a/admin/WebConsole/asistentes/gestores/gestor_Comandos.php b/admin/WebConsole/asistentes/gestores/gestor_Comandos.php deleted file mode 100644 index f96ed350..00000000 --- a/admin/WebConsole/asistentes/gestores/gestor_Comandos.php +++ /dev/null @@ -1,285 +0,0 @@ -<?php -// ************************************************************************************************************************************************* -// Aplicación WEB: ogAdmWebCon -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Año 2009-2010 -// Fecha Última modificación: Agosto-2010 -// Nombre del fichero: gestor_Comandos.php -// Descripción : -// Gestor de todos los comandos -// ************************************************************************************************************************************************* -include_once("../../includes/ctrlacc.php"); -include_once("../../clases/AdoPhp.php"); -include_once("../../clases/SockHidra.php"); -include_once("../../includes/constantes.php"); -include_once("../../includes/comunes.php"); -include_once("../../includes/cuestionacciones.php"); -include_once("../../includes/CreaComando.php"); -include_once("../../includes/RecopilaIpesMacs.php"); -//________________________________________________________________________________________________________ -include_once("../includes/capturaacciones.php"); -//________________________________________________________________________________________________________ - - // Recoge parametros de seguimiento -$sw_ejya=""; -$sw_seguimiento=""; -$sw_ejprg=""; - -$sw_mkprocedimiento=""; -$nombreprocedimiento=""; -$idprocedimiento=""; -$ordprocedimiento=0; - -$sw_mktarea=""; -$nombretarea=""; -$idtarea=""; -$ordtarea=0; - -if (isset($_POST["sw_ejya"])) $sw_ejya=$_POST["sw_ejya"]; -if (isset($_POST["sw_seguimiento"])) $sw_seguimiento=$_POST["sw_seguimiento"]; - -if (isset($_POST["sw_ejprg"])) $sw_ejprg=$_POST["sw_ejprg"]; - -if (isset($_POST["sw_mkprocedimiento"])) $sw_mkprocedimiento=$_POST["sw_mkprocedimiento"]; -if (isset($_POST["nombreprocedimiento"])) $nombreprocedimiento=$_POST["nombreprocedimiento"]; -if (isset($_POST["idprocedimiento"])) $idprocedimiento=$_POST["idprocedimiento"]; -if (isset($_POST["ordprocedimiento"])) $ordprocedimiento=$_POST["ordprocedimiento"]; -if(empty($ordprocedimiento)) $ordprocedimiento=0; - -if (isset($_POST["sw_mktarea"])) $sw_mktarea=$_POST["sw_mktarea"]; -if (isset($_POST["nombretarea"])) $nombretarea=$_POST["nombretarea"]; -if (isset($_POST["idtarea"])) $idtarea=$_POST["idtarea"]; -if (isset($_POST["ordtarea"])) $ordtarea=$_POST["ordtarea"]; -if(empty($ordtarea)) $ordtarea=0; - -//__________________________________________________________________ -$cmd=CreaComando($cadenaconexion); -if (!$cmd) - Header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. -//__________________________________________________________________ -$funcion="nfn=".$funcion.chr(13); // Nombre de la función que procesa el comando y el script que lo implementa -$aplicacion=""; // Ámbito de aplicación (cadena de ipes separadas por ";" y de identificadores de ordenadores por "," -$acciones=""; // Cadena de identificadores de acciones separadas por ";" para seguimiento - -$atributos=str_replace('@',chr(13),$atributos); // Reemplaza caracters -$atributos=str_replace('#',chr(10),$atributos); -$atributos=str_replace('$',chr(9),$atributos); - -//__________________________________________________________________ -?> -<HTML> -<HEAD> - <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> -<BODY> - <SCRIPT language="javascript" src="../../comandos/jscripts/comunescomandos.js"></SCRIPT> - <?php echo '<SCRIPT language="javascript" src="../../idiomas/javascripts/'.$idioma.'/comandos/comunescomandos_'.$idioma.'.js"></SCRIPT>'?> -<?php - -/* Recopila identificadore ,ipes y macs para envío de comandos */ -$cadenaid=""; -$cadenaip=""; -$cadenamac=""; -RecopilaIpesMacs($cmd,$ambito,$idambito); - -/*-------------------------------------------------------------------------------------------------------------------- - Creación de parametros para sentencias SQL ---------------------------------------------------------------------------------------------------------------------*/ -$cmd->CreaParametro("@tipoaccion",0,1); -$cmd->CreaParametro("@idtipoaccion",0,1); -$cmd->CreaParametro("@descriaccion","",0); -$cmd->CreaParametro("@idordenador",0,1); -$cmd->CreaParametro("@ip","",0); -$cmd->CreaParametro("@sesion",0,1); -$cmd->CreaParametro("@parametros","",0); -$cmd->CreaParametro("@fechahorareg","",0); -$cmd->CreaParametro("@estado",0,1); -$cmd->CreaParametro("@resultado",0,1); -$cmd->CreaParametro("@idcentro",0,1); -$cmd->CreaParametro("@idprocedimiento",0,1); -$cmd->CreaParametro("@descripcion","",0); -$cmd->CreaParametro("@idcomando",0,1); -$cmd->CreaParametro("@idtarea",0,1); -$cmd->CreaParametro("@ambito",0,1); -$cmd->CreaParametro("@idambito",0,1); -$cmd->CreaParametro("@restrambito","",0); -$cmd->CreaParametro("@ordprocedimiento",0,1); -$cmd->CreaParametro("@ordtarea",0,1); - -if($ambito==0){ // Ambito restringido a un subconjuto de ordenadores con formato (idordenador1,idordenador2,etc) - $cmd->ParamSetValor("@restrambito",$idambito); - $idambito=0; -} -$resul=true; -/*-------------------------------------------------------------------------------------------------------------------- - Switch de ejecución inmediata y de seguimiento ---------------------------------------------------------------------------------------------------------------------*/ -if($sw_ejya=='on' || $sw_ejprg=="on" ){ - $parametros=$funcion.$atributos; - $aplicacion=chr(13)."ido=".$cadenaid.chr(13)."mac=".$cadenamac.chr(13)."iph=".$cadenaip.chr(13); - if($sw_seguimiento==1 || $sw_ejprg=="on"){ // Switch de ejecución con seguimiento o comando programado - $sesion=time(); - $cmd->ParamSetValor("@tipoaccion",$EJECUCION_COMANDO); - $cmd->ParamSetValor("@idtipoaccion",$idcomando); - $cmd->ParamSetValor("@descriaccion",$descricomando); - $cmd->ParamSetValor("@sesion",$sesion); - $cmd->ParamSetValor("@idcomando",$idcomando); - $cmd->ParamSetValor("@parametros",$parametros); - $cmd->ParamSetValor("@fechahorareg",date("y/m/d H:i:s")); - if($sw_ejprg=="on") // Switch de ejecución con programación (se para el comando tarea para lanzarlo posteriormente) - $cmd->ParamSetValor("@estado",$ACCION_DETENIDA); - else - $cmd->ParamSetValor("@estado",$ACCION_INICIADA); - $cmd->ParamSetValor("@resultado",$ACCION_SINRESULTADO); - $cmd->ParamSetValor("@ambito",$ambito); - $cmd->ParamSetValor("@idambito",$idambito); - $cmd->ParamSetValor("@idcentro",$idcentro); - $auxID=explode(",",$cadenaid); - $auxIP=explode(";",$cadenaip); - for ($i=0;$i<sizeof($auxID);$i++){ - $cmd->ParamSetValor("@idordenador",$auxID[$i]); - $cmd->ParamSetValor("@ip",$auxIP[$i]); - $cmd->texto="INSERT INTO acciones (idordenador,tipoaccion,idtipoaccion,descriaccion,ip, - sesion,idcomando,parametros,fechahorareg,estado,resultado,ambito,idambito,restrambito,idcentro) - VALUES (@idordenador,@tipoaccion,@idtipoaccion,@descriaccion,@ip, - @sesion,@idcomando,@parametros,@fechahorareg,@estado,@resultado,@ambito,@idambito,@restrambito,@idcentro)"; - $resul=$cmd->Ejecutar(); - //echo "<br>".$cmd->texto; - } - $acciones=chr(13)."ids=".$sesion.chr(13); // Para seguimiento - } - if (!$resul){ - echo '<SCRIPT language="javascript">'; - echo 'resultado_comando(7);'.chr(13); - echo '</SCRIPT>'; - } - else{ - if($sw_ejya=='on'){ - // Envio al servidor - $shidra=new SockHidra($servidorhidra,$hidraport); - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $parametros.=$aplicacion; - $parametros.=$acciones; - //echo $parametros; - $resul=$shidra->envia_comando($parametros); - if($resul) - $trama=$shidra->recibe_respuesta(); - if($resul){ - $hlonprm=hexdec(substr($trama,$LONCABECERA,$LONHEXPRM)); - $parametros=substr($trama,$LONCABECERA+$LONHEXPRM,$hlonprm); - $ValorParametros=extrae_parametros($parametros,chr(13),'='); - $resul=$ValorParametros["res"]; - } - $shidra->desconectar(); - } - if (!$resul){ - echo '<SCRIPT language="javascript">'; - echo 'resultado_comando(1);'.chr(13); - echo '</SCRIPT>'; - } - else{ - echo '<SCRIPT language="javascript">'.chr(13); - echo 'resultado_comando(2);'.chr(13); - echo '</SCRIPT>'.chr(13); - } - } - } -} -/*-------------------------------------------------------------------------------------------------------------------- - Switch de creación o inclusión en procedimiento ---------------------------------------------------------------------------------------------------------------------*/ -if($sw_mkprocedimiento=='on' || $sw_mktarea=='on'){ - $resul=false; - if($idprocedimiento==0 || $sw_mktarea=='on'){ // Nuevo procedimiento o Tarea - if($sw_mktarea=='on' && empty($nombreprocedimiento)){ // Si tarea con inclusión de procedimiento... - if(!empty($nombretarea)) - $nombreprocedimiento="Proc($nombretarea)"; // .. tarea nueva - else - $nombreprocedimiento="Proc($idtarea)"; // .. inclusión en tarea - } - $cmd->ParamSetValor("@descripcion",$nombreprocedimiento); - $cmd->ParamSetValor("@idcentro",$idcentro); - $cmd->texto="INSERT INTO procedimientos(descripcion,idcentro) VALUES (@descripcion,@idcentro)"; - $resul=$cmd->Ejecutar(); - if($resul){ - if($idprocedimiento==0) // Cambia el identificador sólo si es nuevo procedimiento - $idprocedimiento=$cmd->Autonumerico(); - if($sw_mktarea=='on') - $idprocedimientotarea=$cmd->Autonumerico(); // Identificador para la tarea; - } - } - if( $idprocedimiento>0 || $sw_mktarea=='on'){ // inclusión en procedimiento existente - $cmd->ParamSetValor("@idprocedimiento",$idprocedimiento); - $cmd->ParamSetValor("@idcomando",$idcomando); - $cmd->ParamSetValor("@ordprocedimiento",$ordprocedimiento); - $parametros=$funcion.$atributos; - $cmd->ParamSetValor("@parametros",$parametros); - $cmd->texto="INSERT INTO procedimientos_acciones(idprocedimiento,orden,idcomando,parametros) VALUES (@idprocedimiento,@ordprocedimiento,@idcomando,@parametros)"; - $resul=$cmd->Ejecutar(); - if($sw_mktarea=='on' && $idprocedimiento!=$idprocedimientotarea){ // Si es tarea se graba para su procedimiento independiente aunque los parametros sean los mismos - $cmd->ParamSetValor("@idprocedimiento",$idprocedimientotarea); - $cmd->texto="INSERT INTO procedimientos_acciones(idprocedimiento,orden,idcomando,parametros) VALUES (@idprocedimiento,@ordprocedimiento,@idcomando,@parametros)"; - $resul=$cmd->Ejecutar(); - } - } - if (!$resul){ - echo '<SCRIPT language="javascript">'; - echo 'resultado_comando(3);'.chr(13); - echo '</SCRIPT>'; - } - else{ - if($sw_mkprocedimiento=='on'){ - echo '<SCRIPT language="javascript">'.chr(13); - echo 'resultado_comando(4);'.chr(13); - echo '</SCRIPT>'.chr(13); - } - } -} -/*-------------------------------------------------------------------------------------------------------------------- - Switch de creación o inclusión en tarea ---------------------------------------------------------------------------------------------------------------------*/ -if($sw_mktarea=='on'){ - $resul=false; - if($idtarea==0){ // Nueva tarea - $cmd->ParamSetValor("@descripcion",$nombretarea); - $cmd->ParamSetValor("@idcentro",$idcentro); - $cmd->ParamSetValor("@ambito",$ambito); - $cmd->ParamSetValor("@idambito",$idambito); - $cmd->texto="INSERT INTO tareas(descripcion,idcentro,ambito,idambito,restrambito) - VALUES (@descripcion,@idcentro,@ambito,@idambito,@restrambito)"; - $resul=$cmd->Ejecutar(); - if($resul) - $idtarea=$cmd->Autonumerico(); - } - if($idtarea>0){ // inclusión en tarea existente - $cmd->ParamSetValor("@idtarea",$idtarea); - $cmd->ParamSetValor("@idprocedimiento",$idprocedimientotarea); - $cmd->ParamSetValor("@ordtarea",$ordtarea); - $cmd->texto="INSERT INTO tareas_acciones(idtarea,orden,idprocedimiento) - VALUES (@idtarea,@ordtarea,@idprocedimiento)"; - $resul=$cmd->Ejecutar(); - //echo $cmd->texto; - } - if (!$resul){ - echo '<SCRIPT language="javascript">'.chr(13); - echo 'resultado_comando(5);'.chr(13); - echo '</SCRIPT>'.chr(13); - } - else{ - echo '<SCRIPT language="javascript">'.chr(13); - echo 'resultado_comando(6);'.chr(13); - echo '</SCRIPT>'.chr(13); - } -} -/* Programación del comando */ -if ($resul){ - if($sw_ejprg=="on" ){ - echo '<SCRIPT language="javascript">'.chr(13); - echo 'var whref="../../varios/programaciones.php?idcomando='.$idcomando.'";'.chr(13); - echo 'whref+="&sesion='.$sesion.'&descripcioncomando='.UrlEncode($descricomando).'&tipoaccion='.$EJECUCION_COMANDO.'";'.chr(13); - echo 'location.href=whref;'; - echo '</SCRIPT>'; - } -} -?> -</BODY> -</HTML> diff --git a/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php b/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php index 4caff0ae..cc7b7670 100644 --- a/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php +++ b/admin/WebConsole/asistentes/includes/asistentes/formCloneRemotePartition.php @@ -1,4 +1,16 @@ +<?php +$disksPartitions = array(); +$diskPartIndex = 0; +// Recorremos todas las configuraciones y vamos creando un array con disco - particion +for($cfgIndex = 0; $cfgIndex < $conKeys; $cfgIndex++){ + if($tbKeys[$cfgIndex]["numpar"] != 0 && $tbKeys[$cfgIndex]["clonable"] == 1){ + $disksPartitions["Disco " . $tbKeys[$cfgIndex]["numdisk"] . " - Part " .$tbKeys[$cfgIndex]["numpar"] ] = $tbKeys[$cfgIndex]["numdisk"]." ".$tbKeys[$cfgIndex]["numpar"]; + $diskPartIndex++; + } +} + +?> <tr> @@ -15,10 +27,11 @@ <br /> <?php echo $TbMsg["WCRP34"] ?> <select name="targetpart" id="targetpart" style="width:220px;"> - <option value="1 1"> 1er disco - 1ª particion </option> - <option value="1 2"> 1er disco - 2ª particion </option> - <option value="1 3"> 1er disco - 3ª particion </option> - <option value="1 4"> 1er disco - 4ª particion </option> + <?php + foreach($disksPartitions as $key => $value){ + echo "<option value='".$value."'>".$key." </option>"; + } + ?> </select> <br /> <?php echo $TbMsg["WCRP35"] ?> diff --git a/admin/WebConsole/asistentes/includes/asistentes/formDeployImage.php b/admin/WebConsole/asistentes/includes/asistentes/formDeployImage.php index c75c9abd..4cbe1916 100644 --- a/admin/WebConsole/asistentes/includes/asistentes/formDeployImage.php +++ b/admin/WebConsole/asistentes/includes/asistentes/formDeployImage.php @@ -7,8 +7,7 @@ $diskPartIndex = 0; // Recorremos todas las configuraciones y vamos creando un array con disco - particion for($cfgIndex = 0; $cfgIndex < $conKeys; $cfgIndex++){ if($tbKeys[$cfgIndex]["numpar"] != 0 && $tbKeys[$cfgIndex]["clonable"] == 1){ - $disksPartitions[$diskPartIndex]["text"] = "Disco ".$tbKeys[$cfgIndex]["numdisk"]." - Part ".$tbKeys[$cfgIndex]["numpar"]; - $disksPartitions[$diskPartIndex]["value"] = $tbKeys[$cfgIndex]["numdisk"].";".$tbKeys[$cfgIndex]["numpar"].";".$tbKeys[$cfgIndex]["tipopar"]; + $disksPartitions["Disco " . $tbKeys[$cfgIndex]["numdisk"] . " - Part " .$tbKeys[$cfgIndex]["numpar"] ] = $tbKeys[$cfgIndex]["numdisk"].";".$tbKeys[$cfgIndex]["numpar"].";".$tbKeys[$cfgIndex]["tipopar"]; $diskPartIndex++; } } @@ -27,8 +26,8 @@ for($cfgIndex = 0; $cfgIndex < $conKeys; $cfgIndex++){ <?php echo $TbMsg["WDI20"] ?> <select name="idparticion" id="idparticion" style="width:220px"> <?php - foreach($disksPartitions as $diskPartition){ - echo "<option value='".$diskPartition["value"]."'>".$diskPartition["text"]." </option>"; + foreach($disksPartitions as $key => $value){ + echo "<option value='".$value."'>".$key." </option>"; } ?> </select> diff --git a/admin/WebConsole/clases/SockHidra.php b/admin/WebConsole/clases/SockHidra.php deleted file mode 100644 index 4f49abba..00000000 --- a/admin/WebConsole/clases/SockHidra.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php - -include_once("EncripDescrip.php"); - -/*================================================================================ - Clase para conectarse con el Servidor OpenGnsys y enviar comandos - Cualquier error producido en los procesos se puede recuperar con los métodos -================================================================================*/ -class SockHidra{ - var $ultimoerror; // Ultimo error detectado - var $descripultimoerror; // Descripción del último error detectado - var $socket; // Stream socket - var $servidor; // El Servidor OpenGnsys - var $puerto; // El puerto donde se conectará - var $timeout; // El tiempo de espera para la conexión - var $encripdescrip; // El encriptador - var $LONGITUD_TRAMA; // Máxima longitud de la trama - - //________________________________________________________________________________________ - // - // Constructor - // Parámetros: - // - servidor: El nombre o la IP del servidor - // - puerto: El puerto usado para las comunicaciones - // - timeout: El tiempo de espera para la conexión - //________________________________________________________________________________________ - function __construct($servidor, $puerto, $timeout=30){ - $this->servidor=$servidor; - if (!$this->_esIP($this->servidor)) - $this->servidor = gethostbyname ($servidor); - $this->puerto=$puerto; - $this->timeout=$timeout; - $this->LONGITUD_TRAMA=4048; - - $this->encripdescrip=new EncripDescrip(); - } - //________________________________________________________________________________________ - // - // Averigua si el parámetro pasado es una IP. devuelve true en caso afirmativo - //________________________________________________________________________________________ - function _esIP(){ - return(false); - } - //________________________________________________________________________________________ - // - // Conecta con el servidor - // Devuelve: - // - false: Si falla la conexión - // - true: En caso contrario - //________________________________________________________________________________________ - function conectar(){ - $this->socket = socket_create (AF_INET, SOCK_STREAM, 0); - if ($this->socket < 0) { - $this->ultimoerror=socket_strerror($this->socket); - $this->descripultimoerror="socket_create() fallo"; - return(false); - } - $result = socket_connect ($this->socket,$this->servidor,$this->puerto); - if ($result < 0) { - $this->ultimoerror=socket_strerror($result); - $this->descripultimoerror="socket_connect() fallo"; - return(false); - } - return(true); - } - //________________________________________________________________________________________ - // - // Cierra la conexión con el servidor - // Devuelve: - // - false: Si falla la conexión - // - true: En caso contrario - //________________________________________________________________________________________ - function desconectar(){ - socket_close ($this->socket); - } - //________________________________________________________________________________________ - // - // Devuelve el código del último error ocurrido durante el proceso anterior. - //________________________________________________________________________________________ - function UltimoError(){ - return($this->ultimoerror); - } - //________________________________________________________________________________________ - // - // Devuelve una cadena con el mensage del último error ocurrido durante el proceso anterior. - //________________________________________________________________________________________ - function DescripUltimoError(){ - return($this->descripultimoerror); - } - //________________________________________________________________________________________ - // - // Envía una petición de comando al servidor - // Parámetros: - // - Parámetros: Parámetros del mensaje - //________________________________________________________________________________________ - function envia_comando($parametros) - { - global $MSG_COMANDO; - - $tipo=$MSG_COMANDO; - return($this->envia_trama($parametros,$tipo)); - } - //________________________________________________________________________________________ - // - // Envía una petición de información al servidor - // Parámetros: - // - Parámetros: Parámetros del mensaje - //________________________________________________________________________________________ - function envia_peticion($parametros) - { - global $MSG_PETICION; - - $tipo=$MSG_PETICION; - return($this->envia_trama($parametros,$tipo)); - } - //________________________________________________________________________________________ - // - // Envía un mensaje al servidor - // Parámetros: - // - trama: Trama a enviar - // - tipo: Tipo de mensaje - //________________________________________________________________________________________ - function envia_trama($parametros,$tipo) - { - global $LONHEXPRM; - global $LONCABECERA; - - $arroba="@"; - $identificador="JMMLCAMDJ_MCDJ"; - - $lonprm=strlen($parametros); - /* Encripta los parámetros */ - $parametros=$this->encripdescrip->Encriptar($parametros,$lonprm); - /* Pasa a hexadecimal la longitud de los parámetros ya encriptados para incluirla dentro de la cabecera */ - $hlonprm=str_pad(dechex($LONCABECERA+$LONHEXPRM+$lonprm),$LONHEXPRM,"0",STR_PAD_LEFT); // Rellena con ceros - - $trama=$arroba.$identificador.$tipo.$hlonprm.$parametros; - $resul=socket_write($this->socket,$trama,$LONCABECERA+$LONHEXPRM+$lonprm); - if (!$resul) { - $this->ultimoerror=socket_strerror($resul); - $this->descripultimoerror="socket_write() fallo"; - return(false); - } - return(true); - } - //________________________________________________________________________________________ - // - // Recibe una trama del servidor - // Parámetros: - // - lon: Longitud de la trama - // Devuelve: - // La trama recibida - //________________________________________________________________________________________ - function recibe_respuesta() - { - global $LONHEXPRM; - global $LONCABECERA; - global $LONBLK; - - $lon=$hlonprm=$lSize=0; - $buffer=""; - $cadenaret=""; - do{ - $bloque = socket_read ($this->socket,$LONBLK);// Lee bloque - $buffer.=$bloque; // Añade bloque - $lon+=strlen($bloque); - if($lSize==0){ // Comprueba tipo de trama y longitud total de los parámetros - if (substr($buffer,0,15)!="@JMMLCAMDJ_MCDJ") - return($cadenaret); // No se reconoce la trama - $hlonprm=hexdec(substr($buffer,$LONCABECERA,$LONHEXPRM)); - $lSize=$hlonprm; // Longitud total de la trama con los parámetros encriptados - } - }while($lon<$lSize); - - $lon=$lSize-($LONCABECERA+$LONHEXPRM); // Longitud de los parámetros aún encriptados - $parametros=substr($buffer,$LONCABECERA+$LONHEXPRM,$lon); // Parámetros encriptados - $parametros=$this->encripdescrip->Desencriptar($parametros,$hlonprm); // Parámetros sin encriptar - $hlonprm=str_pad(dechex($lon),$LONHEXPRM,"0",STR_PAD_LEFT); // Rellena con ceros - $cadenaret=substr($buffer,0,$LONCABECERA).$hlonprm.$parametros; - return($cadenaret); - } - } - diff --git a/admin/WebConsole/comandos/Configurar.php b/admin/WebConsole/comandos/Configurar.php index f6530055..d67eec8d 100644 --- a/admin/WebConsole/comandos/Configurar.php +++ b/admin/WebConsole/comandos/Configurar.php @@ -86,6 +86,11 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; <INPUT type="hidden" name="idambito" value="<?php echo $idambito?>"> <INPUT type="hidden" name="ambito" value="<?php echo $ambito?>"> <INPUT type="hidden" name="cadenaid" value="<?php echo $cadenaid?>"> + <INPUT type="hidden" name="nombreambito" value="<?php echo $nombreambito?>"> + <INPUT type="hidden" name="idcomando" value="<?php echo $idcomando?>"> + <INPUT type="hidden" name="descricomando" value="<?php echo $descricomando?>"> + <INPUT type="hidden" name="gestor" value="<?php echo $gestor?>"> + <INPUT type="hidden" name="funcion" value="<?php echo $funcion?>"> <TABLE class="tabla_busquedas" align=center border=0 cellPadding=0 cellSpacing=0> <TR> <TH height=15 align="center" colspan=14><?php echo $TbMsg[18]?></TH> diff --git a/admin/WebConsole/comandos/IniciarSesion.php b/admin/WebConsole/comandos/IniciarSesion.php index 78f898b2..6d8f1aa9 100644 --- a/admin/WebConsole/comandos/IniciarSesion.php +++ b/admin/WebConsole/comandos/IniciarSesion.php @@ -58,8 +58,6 @@ if (!$cmd) RecopilaIpesMacs($cmd,$ambito,$idambito); ?> - <P align=center><SPAN class=subcabeceras><?php echo $TbMsg[7] ?></SPAN></P> - <BR> <P align=center> <SPAN align=center class=subcabeceras><?php echo $TbMsg[7] ?></SPAN> <br> @@ -136,7 +134,14 @@ function tabla_configuraciones($cmd,$idordenador){ WHERE ordenadores.idordenador=".$idordenador." AND nombresos.nombreso!='DATA' ORDER BY ordenadores_particiones.numpar"; +<<<<<<< HEAD $rs=new Recordset; +======= + + $rs->Comando=&$cmd; + $rs=new Recordset; +>>>>>>> #812: Usar fichero de configuración JSON en comandos Configurar e Iniciar Sesión. + $rs->Comando=&$cmd; $rs->Comando=&$cmd; if (!$rs->Abrir()) return($tablaHtml); // Error al abrir recordset $rs->Primero(); @@ -153,3 +158,7 @@ function tabla_configuraciones($cmd,$idordenador){ $rs->Cerrar(); return($tablaHtml); } +<<<<<<< HEAD +======= + +>>>>>>> #812: Usar fichero de configuración JSON en comandos Configurar e Iniciar Sesión. diff --git a/admin/WebConsole/comandos/InventarioSoftware.php b/admin/WebConsole/comandos/InventarioSoftware.php index e0d98da4..ae63e885 100644 --- a/admin/WebConsole/comandos/InventarioSoftware.php +++ b/admin/WebConsole/comandos/InventarioSoftware.php @@ -16,6 +16,7 @@ include_once("../includes/CreaComando.php"); include_once("../includes/HTMLSELECT.php"); include_once("../includes/pintaTablaConfiguraciones.php"); include_once("../idiomas/php/".$idioma."/comandos/inventariosoftware_".$idioma.".php"); +include_once("../idiomas/php/".$idioma."/pintaParticiones_".$idioma.".php"); include_once("./includes/capturaacciones.php"); include_once("../idiomas/php/".$idioma."/comandos/opcionesacciones_".$idioma.".php"); diff --git a/admin/WebConsole/comandos/RestaurarImagen.php b/admin/WebConsole/comandos/RestaurarImagen.php index e052feb9..21fdda46 100644 --- a/admin/WebConsole/comandos/RestaurarImagen.php +++ b/admin/WebConsole/comandos/RestaurarImagen.php @@ -90,6 +90,11 @@ if (isset($_POST["fk_nombreSO"])) $fk_nombreSO=$_POST["fk_nombreSO"]; <INPUT type="hidden" name="idambito" value="<?php echo $idambito?>"> <INPUT type="hidden" name="ambito" value="<?php echo $ambito?>"> <INPUT type="hidden" name="cadenaid" value="<?php echo $cadenaid?>"> + <INPUT type="hidden" name="nombreambito" value="<?php echo $nombreambito?>"> + <INPUT type="hidden" name="idcomando" value="<?php echo $idcomando?>"> + <INPUT type="hidden" name="descricomando" value="<?php echo $descricomando?>"> + <INPUT type="hidden" name="gestor" value="<?php echo $gestor?>"> + <INPUT type="hidden" name="funcion" value="<?php echo $funcion?>"> <TABLE class="tabla_busquedas" align=center border=0 cellPadding=0 cellSpacing=0> <TR> <TH height=15 align="center" colspan=14><?php echo $TbMsg[18]?></TH> diff --git a/admin/WebConsole/comandos/gestores/gestor_Comandos.php b/admin/WebConsole/comandos/gestores/gestor_Comandos.php index 943fdac7..b0780f1f 100644 --- a/admin/WebConsole/comandos/gestores/gestor_Comandos.php +++ b/admin/WebConsole/comandos/gestores/gestor_Comandos.php @@ -11,10 +11,8 @@ include_once("../../includes/ctrlacc.php"); include_once("../../includes/restfunctions.php"); include_once("../../clases/AdoPhp.php"); -include_once("../../clases/SockHidra.php"); include_once("../../includes/constantes.php"); include_once("../../includes/comunes.php"); -include_once("../../includes/cuestionacciones.php"); include_once("../../includes/CreaComando.php"); include_once("../../includes/RecopilaIpesMacs.php"); //________________________________________________________________________________________________________ @@ -23,13 +21,68 @@ include_once("../includes/capturaacciones.php"); define('OG_CMD_ID_WAKEUP', 1); define('OG_CMD_ID_POWEROFF', 2); +define('OG_CMD_ID_RESTORE_IMAGE', 3); +define('OG_CMD_ID_CREATE_IMAGE', 4); define('OG_CMD_ID_REBOOT', 5); define('OG_CMD_ID_HARDWARE', 6); define('OG_CMD_ID_SOFTWARE', 7); define("OG_CMD_ID_SCRIPT", 8); define('OG_CMD_ID_SESSION', 9); +define('OG_CMD_ID_SETUP', 10); +define('OG_CMD_ID_CREATE_BASIC_IMAGE', 12); +define('OG_CMD_ID_RESTORE_BASIC_IMAGE', 13); +define('OG_CMD_ID_CREATE_INCREMENTAL_IMAGE', 14); +define('OG_CMD_ID_RESTORE_INCREMENTAL_IMAGE', 15); define('OG_CMD_ID_SENDMESSAGE', 16); +function run_command($idcomando, $cadenaip, $cadenamac, $atributos) { + global $cmd; + switch ($idcomando) { + case OG_CMD_ID_WAKEUP: + include("wakeonlan_repo.php"); + break; + case OG_CMD_ID_SETUP: + setup($cadenaip, $atributos); + break; + case OG_CMD_ID_SESSION: + session($cadenaip, $atributos); + break; + case OG_CMD_ID_CREATE_BASIC_IMAGE: + create_basic_image($cadenaip, $atributos); + break; + case OG_CMD_ID_CREATE_INCREMENTAL_IMAGE: + create_incremental_image($cadenaip, $atributos); + break; + case OG_CMD_ID_RESTORE_BASIC_IMAGE: + restore_basic_image($cadenaip, $atributos); + break; + case OG_CMD_ID_RESTORE_INCREMENTAL_IMAGE: + restore_incremental_image($cadenaip, $atributos); + break; + case OG_CMD_ID_POWEROFF: + poweroff($cadenaip); + break; + case OG_CMD_ID_CREATE_IMAGE: + create_image($cadenaip, $atributos); + break; + case OG_CMD_ID_RESTORE_IMAGE: + restore_image($cadenaip, $atributos); + break; + case OG_CMD_ID_REBOOT: + reboot($cadenaip); + break; + case OG_CMD_ID_HARDWARE: + hardware($cadenaip); + break; + case OG_CMD_ID_SOFTWARE: + software($cadenaip, $atributos); + break; + case OG_CMD_ID_SCRIPT: + shell(3, $cadenaip, $atributos); + break; + } +} + // Recoge parametros de seguimiento $sw_ejya=""; $sw_seguimiento=""; @@ -124,27 +177,6 @@ $cmd->CreaParametro("@restrambito","",0); $cmd->CreaParametro("@ordprocedimiento",0,1); $cmd->CreaParametro("@ordtarea",0,1); -/* PARCHE UHU heredado de la version 1.1.0: Si la accion a realizar es Arrancar incluimos una pagina para arrancar desde el repo */ -switch ($idcomando) { - case OG_CMD_ID_WAKEUP: - include("wakeonlan_repo.php"); - break; - case OG_CMD_ID_SESSION: - session($cadenaip, $atributos); - break; - case OG_CMD_ID_POWEROFF: - poweroff($cadenaip); - break; - case OG_CMD_ID_REBOOT: - reboot($cadenaip); - break; - case OG_CMD_ID_HARDWARE: - hardware($cadenaip); - break; - case OG_CMD_ID_SOFTWARE: - software($cadenaip); -} - if($ambito==0){ // Ambito restringido a un subconjuto de ordenadores con formato (idordenador1,idordenador2,etc) $cmd->ParamSetValor("@restrambito",$idambito); $idambito=0; @@ -198,36 +230,15 @@ if($sw_ejya=='on' || $sw_ejprg=="on" ){ else{ $ValorParametros=extrae_parametros($parametros,chr(13),'='); $script=@urldecode($ValorParametros["scp"]); - if($sw_ejya=='on'){ - if ($idcomando != OG_CMD_ID_SENDMESSAGE && - $idcomando != OG_CMD_ID_WAKEUP && - $idcomando != OG_CMD_ID_SESSION && - $idcomando != OG_CMD_ID_POWEROFF && - $idcomando != OG_CMD_ID_HARDWARE && - $idcomando != OG_CMD_ID_SOFTWARE && - $idcomando != OG_CMD_ID_REBOOT) { - // Envío al servidor - $shidra=new SockHidra($servidorhidra,$hidraport); - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $parametros.=$aplicacion; - $parametros.=$acciones; - $resul=$shidra->envia_comando($parametros); - if($resul) - $trama=$shidra->recibe_respuesta(); - if($resul){ - $hlonprm=hexdec(substr($trama,$LONCABECERA,$LONHEXPRM)); - $parametros=substr($trama,$LONCABECERA+$LONHEXPRM,$hlonprm); - $ValorParametros=extrae_parametros($parametros,chr(13),'='); - $resul=$ValorParametros["res"]; - } - $shidra->desconectar(); - } - // Guardamos resultado de ogAgent original - $resulhidra = $resul; - } else { - // En agente nuevo devuelvo siempre correcto - $resulhidra = 1; - } + if($sw_ejya=='on'){ + if (($sw_seguimiento == 1 || $sw_ejprg == "on") && + $idcomando != OG_CMD_ID_WAKEUP) + run_schedule($cadenaip); + else + run_command($idcomando, $cadenaip, $cadenamac, $atributos); + + // En agente nuevo devuelvo siempre correcto + $resulhidra = 1; // Comprobamos si el comando es soportado por el nuevo OGAgent $numip=0; diff --git a/admin/WebConsole/descargas/README.es.html b/admin/WebConsole/descargas/README.es.html index bc548e02..3a543735 100644 --- a/admin/WebConsole/descargas/README.es.html +++ b/admin/WebConsole/descargas/README.es.html @@ -26,6 +26,7 @@ sudo apt install <em>DirectorioDescarga</em>/ogagent_<em>Version</em>_all.deb</pre></li> <li>Configurar el agente: <pre> sudo sed -i "0,/remote=/ s,remote=.*,remote=https://<em>IPServidorOpenGnsys</em>/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg</pre></li> + <li>Para sistemas con GNOME 3: ejecutar GNOME Tweaks y habilitar la extensión TopIcons Plus.</li> <li>Reiniciar el equipo o ejecutar el servicio <em>(se iniciará automáticamente en el proceso de arranque)</em>: <pre> sudo service ogagent start</pre></li> </ul> @@ -39,6 +40,12 @@ <pre> sed -i "0,/remote=/ s,remote=.*,remote=https://<em>IPServidorOpenGnsys</em>/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg</pre></li> <li>Puede ser necesario corregir permisos antes de iniciar el servicio: <pre> chmod +x /etc/init.d/ogagent</pre></li> + <li>Para sistemas con GNOME 3:</li> + <ul> + <li>Instalar TopIcons Plus: + <pre> sudo yum install gnome-shell-extension-topicons-plus</pre></li> + <li>Ejecutar GNOME Tweaks y habilitar la extensión TopIcons Plus.</li> + </ul> <li>Reiniciar el equipo o ejecutar el servicio <em>(se iniciará automáticamente en el proceso de arranque)</em>: <pre> service ogagent start</pre></li> </ul> diff --git a/admin/WebConsole/gestores/gestor_colasacciones.php b/admin/WebConsole/gestores/gestor_colasacciones.php index a8212f33..0821e6a1 100644 --- a/admin/WebConsole/gestores/gestor_colasacciones.php +++ b/admin/WebConsole/gestores/gestor_colasacciones.php @@ -15,7 +15,7 @@ include_once("../clases/AdoPhp.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/CreaComando.php"); -include_once("../clases/SockHidra.php"); +include_once("../includes/restfunctions.php"); //________________________________________________________________________________________________________ $opcion=0; // Inicializa parametros @@ -85,14 +85,14 @@ function gestiona($cmd,$opcion,$acciones){ /* Update de la tabla */ $cmd->texto="UPDATE acciones - SET estado=".$ACCION_INICIADA.",resultado=".$ACCION_SINRESULTADO.",descrinotificacion='',fechahorafin=''"; + SET estado=".$ACCION_INICIADA.",resultado=".$ACCION_SINRESULTADO.",descrinotificacion='',fechahorafin=DEFAULT"; if(!empty($idaccion)) $cmd->texto.=" WHERE idaccion=".$idaccion; else $cmd->texto.=" WHERE tipoaccion=".$tipoaccion." AND idtipoaccion=".$idtipoaccion." AND sesion=".$sesion; $resul=$cmd->Ejecutar(); if($resul) - $resul=enviaComandoActualizar($aplicacion); + run_schedule($rs->campos["cadenaip"]); break; case 3: // Para acciones ============================================================ @@ -139,40 +139,3 @@ function gestiona($cmd,$opcion,$acciones){ } return($resul); } -// _________________________________________________________________________ -// -// Envía un comando de actualizar a los ordenadores tras reinicio de acción -// _________________________________________________________________________ - -function enviaComandoActualizar($aplicacion) -{ - global $servidorhidra; - global $hidraport; - global $LONCABECERA; - global $LONHEXPRM; - - $funcion="Actualizar"; // Nombre de la función que procesa la petición - //________________________________________________________________________________________________________ - // - // Envio al servidor de la petición - //________________________________________________________________________________________________________ - $trama=""; - $shidra=new SockHidra($servidorhidra,$hidraport); - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $parametros="nfn=".$funcion.chr(13); - $parametros.=$aplicacion; - $shidra->envia_comando($parametros); - $trama=$shidra->recibe_respuesta(); - $shidra->desconectar(); - } - else - return(false); // Error de actualización - - $hlonprm=hexdec(substr($trama,$LONCABECERA,$LONHEXPRM)); - $parametros=substr($trama,$LONCABECERA+$LONHEXPRM,$hlonprm); - $ValorParametros=extrae_parametros($parametros,chr(13),'='); - $trama_notificacion=$ValorParametros["res"]; - if($trama_notificacion==1) return(true); // Devuelve respuesta - return(false); // Error de actualización -} - diff --git a/admin/WebConsole/gestores/gestor_ejecutaracciones.php b/admin/WebConsole/gestores/gestor_ejecutaracciones.php index 8e27d1be..edb976f2 100644 --- a/admin/WebConsole/gestores/gestor_ejecutaracciones.php +++ b/admin/WebConsole/gestores/gestor_ejecutaracciones.php @@ -12,13 +12,15 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/ArbolVistaXML.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/CreaComando.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/RecopilaIpesMacs.php"); +include_once("../includes/restfunctions.php"); //________________________________________________________________________________________________________ +define('OG_CMD_ID_WAKEUP', 1); + $opcion=0; // Inicializa parametros $idprocedimiento=0; @@ -48,7 +50,6 @@ if (isset($_GET["swc"])) $swc=$_GET["swc"]; // Switch que indica que la página $cmd=CreaComando($cadenaconexion); // Crea objeto comando $resul=false; if ($cmd){ - $shidra=new SockHidra($servidorhidra,$hidraport); $cadenaid=""; $cadenaip=""; $cadenamac=""; @@ -156,8 +157,12 @@ function ejecucionTarea($idtarea) //________________________________________________________________________________________________________ function recorreProcedimientos($idprocedimiento,$ambito,$idambito) { - global $cmd; + global $cadenamac; + global $cadenaip; global $sesion; + global $cmd; + + $wol_params; $cmd->texto="SELECT idcomando,procedimientoid,parametros FROM procedimientos_acciones @@ -184,11 +189,19 @@ function recorreProcedimientos($idprocedimiento,$ambito,$idambito) $sesion=$nwsesion; $cmd->ParamSetValor("@sesion",$sesion); // Fin ticket 681. + if ($idcomando == OG_CMD_ID_WAKEUP) + $wol_params = $parametros; if(!insertaComando($idcomando,$parametros,$idprocedimiento,$ambito,$idambito)) return(false); } $rs->Siguiente(); } + + if (isset($wol_params)) { + $atributos = substr(trim($wol_params), -1); + include("../comandos/gestores/wakeonlan_repo.php"); + } + return(true); } //________________________________________________________________________________________________________ @@ -268,43 +281,13 @@ function insertaComando($idcomando,$parametros,$idprocedimiento,$ambito,$idambit $resul=$cmd->Ejecutar(); //echo $cmd->texto; if(!$resul) return(false); - - /* Sólo envía por la red el primer comando, el resto, si hubiera, - lo encontrará el cliente a través de los comandos pendientes */ + + // Let the clients know they can start executing pending commands. if(empty($vez)){ - if(!enviaComando($parametros,$sesion)) return(false); + run_schedule($cadenaip); $vez++; } } return(true); } -//________________________________________________________________________________________________________ -// -// Envia un procedimiento a un grupo de ordenadores a través de la red -//________________________________________________________________________________________________________ -function enviaComando($parametros,$sesion) -{ - global $cadenaid; - global $cadenaip; - global $cadenamac; - global $servidorhidra; - global $hidraport; - global $LONCABECERA; - global $shidra; - - // Envio al servidor - - $aplicacion=chr(13)."ido=".$cadenaid.chr(13)."mac=".$cadenamac.chr(13)."iph=".$cadenaip.chr(13); - $acciones=chr(13)."ids=".$sesion.chr(13); // Para seguimiento - - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $parametros.=$aplicacion; - $parametros.=$acciones; - $shidra->envia_comando($parametros); - $trama=$shidra->recibe_respuesta(); - $shidra->desconectar(); - } - return(true); -} - diff --git a/admin/WebConsole/gestores/gestor_pxe.php b/admin/WebConsole/gestores/gestor_pxe.php index ee3bb751..22a5e292 100644 --- a/admin/WebConsole/gestores/gestor_pxe.php +++ b/admin/WebConsole/gestores/gestor_pxe.php @@ -3,7 +3,6 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/MenuContextual.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/CreaComando.php"); diff --git a/admin/WebConsole/gestores/gestor_tareas.php b/admin/WebConsole/gestores/gestor_tareas.php index 47928c92..9bb4498e 100644 --- a/admin/WebConsole/gestores/gestor_tareas.php +++ b/admin/WebConsole/gestores/gestor_tareas.php @@ -12,7 +12,6 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/ArbolVistaXML.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/CreaComando.php"); include_once("../includes/constantes.php"); include_once("../includes/opciones.php"); @@ -140,7 +139,6 @@ function Gestiona(){ global $op_modificacion; global $op_eliminacion; global $op_movida; - global $op_ejecucion; global $tablanodo; $resul=false; @@ -179,9 +177,6 @@ function Gestiona(){ $cmd->texto="UPDATE tareas SET grupoid=@grupoid WHERE idtarea=@idtarea"; $resul=$cmd->Ejecutar(); break; - case $op_ejecucion : - $resul=EjecutandoTareas(); - break; default: break; } @@ -206,106 +201,4 @@ function SubarbolXML_tareas($idtarea,$descripcion,$urlimg){ return($cadenaXML); } //________________________________________________________________________________________________________ -function EjecutandoTareas(){ - - global $EJECUCION_COMANDO; - global $EJECUCION_TAREA; - global $PROCESOS; - global $ACCION_INICIADA; - global $ACCION_SINRESULTADO; - global $idcentro; - global $servidorhidra; - global $hidraport; - global $idtarea; - global $cmd; - - $shidra=new SockHidra($servidorhidra,$hidraport); - - $ambitarea=""; - $paramtarea="cmd="; - - $tbComandos=""; - $tabla_comandos=""; - $cont_comandos=0; - - $rs=new Recordset; - $cmd->texto="SELECT * FROM tareas_comandos WHERE idtarea=".$idtarea; - $cmd->texto.=" ORDER by tareas_comandos.orden"; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(false); // Error al abrir recordset - $rs->Primero(); - // Recorre tareas-comandos - while (!$rs->EOF){ - $tbComandos["idcomando"]=$rs->campos["idcomando"]; - $tbComandos["ambito"]=$rs->campos["ambito"]; - $tbComandos["idambito"]=$rs->campos["idambito"]; - $tbComandos["parametros"]=$rs->campos["parametros"]; - $tbComandos["idnotificador"]=$rs->campos["idtareacomando"]; - $tabla_comandos[$cont_comandos]=$tbComandos; - $cont_comandos++; - - $ambitarea.=$rs->campos["ambito"].":".$rs->campos["idambito"].";"; - $paramtarea.=$rs->campos["idtareacomando"].";"; - - $rs->Siguiente(); - } - $rs->Cerrar(); - - $ambitarea=substr($ambitarea,0,strlen($ambitarea)-1); // Quita la coma final - $paramtarea=substr($paramtarea,0,strlen($paramtarea)-1); // Quita la coma final - - //Creación parametros para inserción - $cmd->CreaParametro("@tipoaccion","",1); - $cmd->CreaParametro("@idtipoaccion",0,1); - $cmd->CreaParametro("@cateaccion",$PROCESOS,1); - $cmd->CreaParametro("@ambito",0,1); - $cmd->CreaParametro("@idambito",0,1); - $cmd->CreaParametro("@ambitskwrk","",0); - $cmd->CreaParametro("@fechahorareg","",0); - $cmd->CreaParametro("@estado",$ACCION_INICIADA,0); - $cmd->CreaParametro("@resultado",$ACCION_SINRESULTADO,0); - $cmd->CreaParametro("@idcentro",$idcentro,1); - $cmd->CreaParametro("@parametros","",0); - $cmd->CreaParametro("@accionid",0,1); - $cmd->CreaParametro("@idnotificador",0,1); - - // Insertar accion:tarea -------------------------------------------------------------------- - $cmd->ParamSetValor("@tipoaccion",$EJECUCION_TAREA); - $cmd->ParamSetValor("@idtipoaccion",$idtarea); - $cmd->ParamSetValor("@ambito",0); - $cmd->ParamSetValor("@idambito",0); - $cmd->ParamSetValor("@ambitskwrk",$ambitarea); - $cmd->ParamSetValor("@fechahorareg",date("d/m/y H:i:s")); - $cmd->ParamSetValor("@parametros",$paramtarea); - $cmd->texto="INSERT INTO acciones (tipoaccion,idtipoaccion,cateaccion,ambito,idambito,ambitskwrk,fechahorareg,estado,resultado,idcentro,parametros,accionid,idnotificador) VALUES (@tipoaccion,@idtipoaccion,@cateaccion,@ambito,@idambito,@ambitskwrk,@fechahorareg,@estado,@resultado,@idcentro,@parametros,0,0)"; - $resul=$cmd->Ejecutar(); - if(!$resul) return(false); - - $accionid=$cmd->Autonumerico(); // Toma identificador dela acción - - // Insertar acciones:comandos - $shidra=new SockHidra($servidorhidra,$hidraport); - for ($i=0;$i<$cont_comandos;$i++){ - $tbComandos=$tabla_comandos[$i]; - $cmd->ParamSetValor("@tipoaccion",$EJECUCION_COMANDO); - $cmd->ParamSetValor("@idtipoaccion",$tbComandos["idcomando"]); - $cmd->ParamSetValor("@ambito",$tbComandos["ambito"]); - $cmd->ParamSetValor("@idambito",$tbComandos["idambito"]); - $cmd->ParamSetValor("@ambitskwrk",""); - $cmd->ParamSetValor("@fechahorareg",date("d/m/y H:i:s")); - $cmd->ParamSetValor("@parametros",$tbComandos["parametros"]); - $cmd->ParamSetValor("@accionid",$accionid); - $cmd->ParamSetValor("@idnotificador",$tbComandos["idnotificador"]); - $cmd->texto="INSERT INTO acciones (tipoaccion,idtipoaccion,cateaccion,ambito,idambito,ambitskwrk,fechahorareg,estado,resultado,idcentro,parametros,accionid,idnotificador) VALUES (@tipoaccion,@idtipoaccion,@cateaccion,@ambito,@idambito,@ambitskwrk,@fechahorareg,@estado,@resultado,@idcentro,@parametros,@accionid,@idnotificador)"; - $resul=$cmd->Ejecutar(); - if(!$resul) return(false); - $tbComandos["parametros"].="ids=".$cmd->Autonumerico().chr(13); - - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $shidra->envia_comando($tbComandos["parametros"]); - $shidra->desconectar(); - } - } - return(true); -} diff --git a/admin/WebConsole/gestores/gestor_tareascomandos.php b/admin/WebConsole/gestores/gestor_tareascomandos.php deleted file mode 100644 index ceffb695..00000000 --- a/admin/WebConsole/gestores/gestor_tareascomandos.php +++ /dev/null @@ -1,122 +0,0 @@ -<?php -// ************************************************************************************************************************************************* -// Aplicación WEB: ogAdmWebCon -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Año 2009-2010 -// Fecha Última modificación: Agosto-2010 -// Nombre del fichero: gestor_tareascomandos.php -// Descripción : -// Gestiona el mantenimiento de la tabla de tareas_comandos -// ************************************************************************************************************************************************* -include_once("../includes/ctrlacc.php"); -include_once("../clases/AdoPhp.php"); -include_once("../includes/CreaComando.php"); -include_once("../includes/opciones.php"); -include_once("../clases/SockHidra.php"); -include_once("../includes/constantes.php"); -//________________________________________________________________________________________________________ -$opcion=0; // Inicializa parametros -$idtareacomando=0; -$orden=0; - -if (isset($_POST["opcion"])) $opcion=$_POST["opcion"]; // Recoge parametros -if (isset($_POST["idtareacomando"])) $idtareacomando=$_POST["idtareacomando"]; -if (isset($_POST["orden"])) $orden=$_POST["orden"]; - -$cmd=CreaComando($cadenaconexion); // Crea objeto comando -$resul=false; -if ($cmd){ - $resul=Gestiona(); - $cmd->Conexion->Cerrar(); -} -$literal=""; -switch($opcion){ - case $op_eliminacion : - $literal="resultado_eliminar_tareacomando"; - break; - case $op_modificacion : - $literal="resultado_modificar_tareacomando"; - break; - case $op_ejecucion : - $literal="resultado_ejecutar_tareacomando"; - break; - default: - break; -} -if ($resul){ - echo $literal."(1,'".$cmd->DescripUltimoError()." ',".$idtareacomando.");".chr(13); -} -else{ - echo $literal."(0,'".$cmd->DescripUltimoError()."',".$idtareacomando.")"; -} -// ************************************************************************************************************************************************* -function Gestiona(){ - global $cmd; - global $opcion; - global $op_modificacion; - global $op_eliminacion; - global $op_ejecucion; - global $EJECUCION_COMANDO; - global $PROCESOS; - global $ACCION_INICIADA; - global $ACCION_SINERRORES; - global $ACCION_SINRESULTADO; - global $servidorhidra; - global $hidraport; - global $idcentro; - global $idtareacomando; - global $orden; - $resul=true; - - $cmd->CreaParametro("@orden",$orden,1); - - switch($opcion){ - case $op_modificacion : - $cmd->texto='UPDATE tareas_comandos set orden=@orden WHERE idtareacomando='.$idtareacomando; - $resul=$cmd->Ejecutar(); - break; - case $op_eliminacion : - $cmd->texto='DELETE FROM tareas_comandos WHERE idtareacomando='.$idtareacomando; - $resul=$cmd->Ejecutar(); - break; - case $op_ejecucion : - $nombreliterales[0]="idcomando"; - $nombreliterales[1]="ambito"; - $nombreliterales[2]="idambito"; - $nombreliterales[3]="parametros"; - $Datos=TomanDatos($cmd,"tareas_comandos",$idtareacomando,"idtareacomando",$nombreliterales); - if(empty($Datos)) return(false); - - $idtipoaccion=$Datos["idcomando"]; - $ambito=$Datos["ambito"]; - $idambito=$Datos["idambito"]; - $parametros=$Datos["parametros"]; - - $cmd->CreaParametro("@tipoaccion",$EJECUCION_COMANDO,1); - $cmd->CreaParametro("@idtipoaccion",$idtipoaccion,1); - $cmd->CreaParametro("@cateaccion",$PROCESOS,1); - $cmd->CreaParametro("@ambito",$ambito,1); - $cmd->CreaParametro("@idambito",$idambito,1); - $cmd->CreaParametro("@ambitskwrk","",0); - $cmd->CreaParametro("@fechahorareg",date("y/m/d H:i:s"),0); - $cmd->CreaParametro("@estado",$ACCION_INICIADA,0); - $cmd->CreaParametro("@resultado",$ACCION_SINRESULTADO,0); - $cmd->CreaParametro("@idcentro",$idcentro,1); - $cmd->CreaParametro("@parametros",$parametros,0); - $cmd->texto="INSERT INTO acciones (tipoaccion,idtipoaccion,cateaccion,ambito,idambito,ambitskwrk,fechahorareg,estado,resultado,idcentro,parametros,accionid) VALUES (@tipoaccion,@idtipoaccion,@cateaccion,@ambito,@idambito,@ambitskwrk,@fechahorareg,@estado,@resultado,@idcentro,@parametros,0)"; - $resul=$cmd->Ejecutar(); - if($resul){ - $parametros.="ids=".$cmd->Autonumerico().chr(13); - } - $shidra=new SockHidra($servidorhidra,$hidraport); - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $shidra->envia_comando($parametros); - $shidra->desconectar(); - } - break; - default: - break; - } - return($resul); -} - diff --git a/admin/WebConsole/gestores/gestor_ubicarordenadores.php b/admin/WebConsole/gestores/gestor_ubicarordenadores.php index 2a7c2e35..98c5bc2e 100644 --- a/admin/WebConsole/gestores/gestor_ubicarordenadores.php +++ b/admin/WebConsole/gestores/gestor_ubicarordenadores.php @@ -3,7 +3,6 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/MenuContextual.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/CreaComando.php"); diff --git a/admin/WebConsole/gestores/gestor_usuarios.php b/admin/WebConsole/gestores/gestor_usuarios.php index 12aa67fd..f346d10b 100644 --- a/admin/WebConsole/gestores/gestor_usuarios.php +++ b/admin/WebConsole/gestores/gestor_usuarios.php @@ -9,7 +9,6 @@ // Gestiona el mantenimiento de la tabla de usuarios // ******************************************************************************************************* include_once("../includes/ctrlacc.php"); -include_once("../clases/SockHidra.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/ArbolVistaXML.php"); diff --git a/admin/WebConsole/idiomas/javascripts/cat/tareascomandos_cat.js b/admin/WebConsole/idiomas/javascripts/cat/tareascomandos_cat.js deleted file mode 100644 index 9e483095..00000000 --- a/admin/WebConsole/idiomas/javascripts/cat/tareascomandos_cat.js +++ /dev/null @@ -1,10 +0,0 @@ -//____________________________________________________________________________ -// -// Fichero de idiomas javascript: tareascomandos_esp.js -// Idioma: Español -//____________________________________________________________________________ -TbMsg=new Array; -TbMsg[0]="ATENCIÓN.- El comando será excluido de la tarea. ¿ Está seguro ?"; -TbMsg[1]="ATENCIÓN: Debe introducir un número de orden"; -TbMsg[2]="El comando ha sido excluido correctamente de esta tarea"; -TbMsg[3]="El comando ha sido modificado correctamente"; diff --git a/admin/WebConsole/idiomas/javascripts/eng/tareascomandos_eng.js b/admin/WebConsole/idiomas/javascripts/eng/tareascomandos_eng.js deleted file mode 100644 index 5e075b18..00000000 --- a/admin/WebConsole/idiomas/javascripts/eng/tareascomandos_eng.js +++ /dev/null @@ -1,10 +0,0 @@ -//____________________________________________________________________________ -// -// Fichero de idiomas javascript: tareascomandos_eng.js -// Idioma: Inglés -//____________________________________________________________________________ -TbMsg=[]; -TbMsg[0]="WARNING: This command will be excluded from this task. Are you sure?"; -TbMsg[1]="WARNING: You must enter a sequence number"; -TbMsg[2]="This command has been excluded successfully from this task"; -TbMsg[3]="This command has been modified successfully"; diff --git a/admin/WebConsole/idiomas/javascripts/esp/tareascomandos_esp.js b/admin/WebConsole/idiomas/javascripts/esp/tareascomandos_esp.js deleted file mode 100644 index 9e483095..00000000 --- a/admin/WebConsole/idiomas/javascripts/esp/tareascomandos_esp.js +++ /dev/null @@ -1,10 +0,0 @@ -//____________________________________________________________________________ -// -// Fichero de idiomas javascript: tareascomandos_esp.js -// Idioma: Español -//____________________________________________________________________________ -TbMsg=new Array; -TbMsg[0]="ATENCIÓN.- El comando será excluido de la tarea. ¿ Está seguro ?"; -TbMsg[1]="ATENCIÓN: Debe introducir un número de orden"; -TbMsg[2]="El comando ha sido excluido correctamente de esta tarea"; -TbMsg[3]="El comando ha sido modificado correctamente"; diff --git a/admin/WebConsole/idiomas/php/cat/pintaParticiones_cat.php b/admin/WebConsole/idiomas/php/cat/pintaParticiones_cat.php index 916f30a4..143d0b18 100644 --- a/admin/WebConsole/idiomas/php/cat/pintaParticiones_cat.php +++ b/admin/WebConsole/idiomas/php/cat/pintaParticiones_cat.php @@ -45,6 +45,7 @@ $TbMsg["INCREMENTAL_IMAGE_REPOSITORY"]='Imagen Incremental / Repositorio'; $TbMsg["CONFIG_NOCONFIG"]='Sense configuració: client no connectat al servidor.'; $TbMsg["CONFIG_NODISK1MSDOS"]='Avís: aquest comandament sol tracta el disc 1 amb taula de particions MSDOS.'; +$TbMsg["CONFIG_NOOS"]='No se ha detectado ningún sistema operativo en el equipo.'; $TbMsg["SYNC_METHOD"]='Método'; $TbMsg["SYNC1_DIR"]='Basada en directorio'; diff --git a/admin/WebConsole/idiomas/php/cat/tareascomandos_cat.php b/admin/WebConsole/idiomas/php/cat/tareascomandos_cat.php deleted file mode 100644 index 7f0406c3..00000000 --- a/admin/WebConsole/idiomas/php/cat/tareascomandos_cat.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php -//________________________________________________________________________________________________________ -// -// Fitxer d'idiomes php: tareascomandos_cat.php -// Idioma: Catal� -//________________________________________________________________________________________________________ - $TbMsg=array(); - $TbMsg[0]='Gesti� Comandes de la Tasca'; - $TbMsg[1]='Comandes incloses'; - $TbMsg[2]='Tasca'; - $TbMsg[3]='Nom Comanda'; - $TbMsg[4]='Ord.'; - $TbMsg[5]='Par�metre'; - $TbMsg[6]='Valor'; - $TbMsg[7]='(*)Per excloure alguna comanda d\'aquesta tasca ha de fer click sobre la casella de verificaci� corresponent'; diff --git a/admin/WebConsole/idiomas/php/eng/pintaParticiones_eng.php b/admin/WebConsole/idiomas/php/eng/pintaParticiones_eng.php index 3c4bd52e..a4e4399f 100644 --- a/admin/WebConsole/idiomas/php/eng/pintaParticiones_eng.php +++ b/admin/WebConsole/idiomas/php/eng/pintaParticiones_eng.php @@ -45,6 +45,7 @@ $TbMsg["INCREMENTAL_IMAGE_REPOSITORY"]='Incremental Image / Repository'; $TbMsg["CONFIG_NOCONFIG"]='No configuration: client not connected to server.'; $TbMsg["CONFIG_NODISK1MSDOS"]='Warning: this command only uses disk 1 with MSDOS partition table.'; +$TbMsg["CONFIG_NOOS"]='No operating system detected on the computer.'; $TbMsg["SYNC_METHOD"]='Method'; $TbMsg["SYNC1_DIR"]='Directory based'; diff --git a/admin/WebConsole/idiomas/php/eng/tareascomandos_eng.php b/admin/WebConsole/idiomas/php/eng/tareascomandos_eng.php deleted file mode 100644 index 94896066..00000000 --- a/admin/WebConsole/idiomas/php/eng/tareascomandos_eng.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php -//________________________________________________________________________________________________________ -// -// Php language file: tareascomandos_eng.php -// Language: English -//________________________________________________________________________________________________________ - $TbMsg=array(); - $TbMsg[0]='Task Commands Management'; - $TbMsg[1]='Included Commands'; - $TbMsg[2]='Task'; - $TbMsg[3]='Command name'; - $TbMsg[4]='Ord.'; - $TbMsg[5]='Parameter'; - $TbMsg[6]='Value'; - $TbMsg[7]='(*)Please check the box to exclude any command from this task.'; diff --git a/admin/WebConsole/idiomas/php/esp/pintaParticiones_esp.php b/admin/WebConsole/idiomas/php/esp/pintaParticiones_esp.php index 3fc9a6a7..e7316dbb 100644 --- a/admin/WebConsole/idiomas/php/esp/pintaParticiones_esp.php +++ b/admin/WebConsole/idiomas/php/esp/pintaParticiones_esp.php @@ -45,6 +45,7 @@ $TbMsg["INCREMENTAL_IMAGE_REPOSITORY"]='Imagen Incremental / Repositorio'; $TbMsg["CONFIG_NOCONFIG"]='Sin configuración: cliente no conectado al servidor.'; $TbMsg["CONFIG_NODISK1MSDOS"]='Aviso: este comando solo trata el disco 1 con tabla de particiones MSDOS.'; +$TbMsg["CONFIG_NOOS"]='No se ha detectado ningún sistema operativo en el equipo.'; $TbMsg["SYNC_METHOD"]='Método'; $TbMsg["SYNC1_DIR"]='Basada en directorio'; diff --git a/admin/WebConsole/idiomas/php/esp/tareascomandos_esp.php b/admin/WebConsole/idiomas/php/esp/tareascomandos_esp.php deleted file mode 100644 index 500ec245..00000000 --- a/admin/WebConsole/idiomas/php/esp/tareascomandos_esp.php +++ /dev/null @@ -1,18 +0,0 @@ -<?php -//________________________________________________________________________________________________________ -// -// Fichero de idiomas php: tareascomandos_esp.php -// Idioma: Español -//________________________________________________________________________________________________________ - $TbMsg=array(); - $TbMsg[0]='Gestión Comandos de la Tarea'; - $TbMsg[1]='Comandos incluidos'; - $TbMsg[2]='Tarea'; - $TbMsg[3]='Nombre Comando'; - $TbMsg[4]='Ord.'; - $TbMsg[5]='Parámetro'; - $TbMsg[6]='Valor'; - $TbMsg[7]='(*)Para excluir algún comando de esta tarea debe hacer click sobre la casilla de verificación correspondiente'; - $TbMsg[8]='Ámbito'; - $TbMsg[9]='Nombre'; - diff --git a/admin/WebConsole/images/M_Iconos.php b/admin/WebConsole/images/M_Iconos.php index 74bd0c4b..eaaf04c3 100644 --- a/admin/WebConsole/images/M_Iconos.php +++ b/admin/WebConsole/images/M_Iconos.php @@ -12,7 +12,6 @@ include_once("../clases/AdoPhp.php"); include_once("../includes/CreaComando.php"); include_once("../includes/TomaDato.php"); include_once("../includes/HTMLCTESELECT.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/FicherosPost.php"); include_once("../idiomas/php/".$idioma."/iconos_".$idioma.".php"); diff --git a/admin/WebConsole/includes/ConfiguracionesParticiones.php b/admin/WebConsole/includes/ConfiguracionesParticiones.php index 319c26be..e7eec775 100644 --- a/admin/WebConsole/includes/ConfiguracionesParticiones.php +++ b/admin/WebConsole/includes/ConfiguracionesParticiones.php @@ -2,6 +2,44 @@ include_once(__DIR__ . "/configfunctions.php"); include_once(__DIR__ . "/pintaParticiones.php"); +/** + * Busca en la configuración JSON los datos de partición para el código hexadecimal correspondiente. + * @param object $json datos JSON de configuración + * @param string $code código hexadecimal de partición + * @return array tipo de partición (string) e indicador de clonable (bool) + */ +function getPartitionData($json, $code) { + if (isset($json->partitiontables)) { + foreach ($json->partitiontables as $tab) { + if (isset($tab->partitions)) { + foreach ($tab->partitions as $par) { + if (hexdec($par->id) == $code) { + return [$par->type, $par->clonable]; + } + } + } + } + } + return [$code, true]; +} + +/** + * Busca en la configuración JSON los datos de tabla de particiones para el código correspondiente. + * @param object $json datos JSON de configuración + * @param string $code código de tabla de particiones + * @return string tipo de tabla de particiones + */ +function getParttableData($json, $code) { + if (isset($json->partitiontables)) { + foreach ($json->partitiontables as $tab) { + if (hexdec($tab->id) == $code) { + return $tab->type; + } + } + } + return ""; +} + /*________________________________________________________________________________________________________ UHU - 2013/05/14 - Se añade la clave número de disco Ramón - 2018/03/09 - Usar fichero de configuración JSON para datos estáticos diff --git a/admin/WebConsole/includes/constantes.php b/admin/WebConsole/includes/constantes.php index 702ece43..9291b355 100644 --- a/admin/WebConsole/includes/constantes.php +++ b/admin/WebConsole/includes/constantes.php @@ -136,13 +136,6 @@ $ACCION_DETENIDA=2; // Acción momentanemente parada $ACCION_FINALIZADA=3; // Acción finalizada $ACCION_PROGRAMADA=4; // Acción programada -// Nombre y path del fichero de intercambio de parametros entre páginas -// Ha sido necesario porque cuando los parametros enviados execedían de cierta longitud -// ocurria una excepción al llamar a la página por GET. - -$fileparam="../includes/PRM_".$usuario; -$pathfileco="/opt/opengnsys/log/clients"; // Path del fichero de eco de consola - // Máxima longitud de los parametros enviados entre páginas $MAXLONPRM=16000; $MAXLONVISUSCRIPT=1024; // Longitud máxima de visualización del script en las colas de acciones diff --git a/admin/WebConsole/includes/cuestionacciones.php b/admin/WebConsole/includes/cuestionacciones.php deleted file mode 100644 index 9c79894d..00000000 --- a/admin/WebConsole/includes/cuestionacciones.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/* ------------------------------------------------------------------------------------------- - Inserta, modifica o elimina un grupo de servidores dhcp de la base de datos ----------------------------------------------------------------------------------------------*/ -function CuestionAcciones($cmd,$shidra,$parametros){ - - global $sw_ejya; - global $sw_seguimiento; - - global $sw_mktarea; - global $nwidtarea; - global $nwdescritarea; - - global $sw_mkprocedimiento; - global $nwidprocedimiento; - global $nwdescriprocedimiento; - - global $identificador; - - if($sw_ejya=='true' ){ // switch de ejecución inmediata ---------------------------------------------------------------------- - if($sw_seguimiento=='true' ){ // switch de ejecución con seguimiento - $cmd->texto="INSERT INTO acciones (tipoaccion,idtipoaccion,cateaccion,ambito,idambito,fechahorareg,estado,resultado,idcentro,parametros,accionid,idnotificador) VALUES (@tipoaccion,@idtipoaccion,@cateaccion,@ambito,@idambito,@fechahorareg,@estado,@resultado,@idcentro,@parametros,0,0)"; - $resul=$cmd->Ejecutar(); - if($resul){ - $parametros.="ids=".$cmd->Autonumerico().chr(13); - } - } - // Envio al servidor hidra - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $shidra->envia_comando($parametros); - $shidra->desconectar(); - } - else - return(false); - } - // Fin ejecución inmediata ------------------------------------------------------------------------------------------------------------- - - if($sw_mkprocedimiento=='true'){ // switch de creación o inclusión en procedimiento --------------------------------------------------------- - if($nwidprocedimiento==0){ - $cmd->ParamSetValor("@descripcion",$nwdescriprocedimiento,0); - $cmd->texto="INSERT INTO procedimientos(descripcion,idcentro) VALUES (@descripcion,@idcentro)"; - $resul=$cmd->Ejecutar(); - if($resul) - $nwidprocedimiento=$cmd->Autonumerico(); - else - return(false); - } - if($nwidprocedimiento>0){ // inclusión en procedimiento existente - $cmd->ParamSetValor("@idprocedimiento",$nwidprocedimiento,1); - $cmd->ParamSetValor("@idcomando",$identificador,1); - $cmd->ParamSetValor("@parametros",Sin_iph($parametros),0); - $cmd->texto="INSERT INTO procedimientos_comandos(idprocedimiento,orden,idcomando,parametros) VALUES (@idprocedimiento,0,@idcomando,@parametros)"; - $resul=$cmd->Ejecutar(); - $cmd->ParamSetValor("@parametros",$parametros); - if(!$resul) return(false); - } - } - - if($sw_mktarea=='true'){ // switch de creación o inclusión en tarea ----------------------------------------------------------- - if($nwidtarea==0){ // Nueva tarea - $cmd->ParamSetValor("@descripcion",$nwdescritarea); - $cmd->texto="INSERT INTO tareas(descripcion,idcentro) VALUES (@descripcion,@idcentro)"; - $resul=$cmd->Ejecutar(); - if($resul) - $nwidtarea=$cmd->Autonumerico(); - else - return(false); - } - if($nwidtarea>0){ // inclusión en tarea existente - $cmd->ParamSetValor("@idtarea",$nwidtarea); - $cmd->ParamSetValor("@idcomando",$identificador); - $cmd->texto="INSERT INTO tareas_comandos(idtarea,orden,idcomando,ambito,idambito,parametros) VALUES (@idtarea,0,@idcomando,@ambito,@idambito,@parametros)"; - $resul=$cmd->Ejecutar(); - if(!$resul) return(false); - } - } - return(true); -} - diff --git a/admin/WebConsole/includes/pintaParticiones.php b/admin/WebConsole/includes/pintaParticiones.php index 95b6b855..ecfbd687 100644 --- a/admin/WebConsole/includes/pintaParticiones.php +++ b/admin/WebConsole/includes/pintaParticiones.php @@ -358,7 +358,7 @@ function pintaParticionesConfigurar($cmd,$configuraciones,$idordenadores,$cc) echo '<tr id="TRIMG_'.$cc.'" align="center">'. "\n<td></td>\n<td></td>\n<td".' style="font-size: 1em; padding: 1px 0; "'.">".$TbMsg["DISK"]."</td>". "\n<td></td>\n<td".' style="font-size: 1em; padding: 1px 0;"> '.(isset($tm)?$tm:("<em>".$TbMsg["VARIABLE"]."</em>")). - "<input type='hidden' id='hdsize$cc' name='hdsize$cc' style='width:100px' value='".$tm."'></td>". + "<input type='hidden' id='hdsize$cc' name='hdsize$cc' style='width:100px' value='".$tm."'></td>". "\n<td></td>\n<td></td>\n</tr>"; echo '<tr><th colspan="'.$colums.'"> '.$TbMsg["WARN_DISKSIZE"].'</th></tr>'; // Mostrar aviso: solo disco 1 con tabla MSDOS. diff --git a/admin/WebConsole/includes/pintaTablaConfiguraciones.php b/admin/WebConsole/includes/pintaTablaConfiguraciones.php index eafb4bfd..8506a0ea 100644 --- a/admin/WebConsole/includes/pintaTablaConfiguraciones.php +++ b/admin/WebConsole/includes/pintaTablaConfiguraciones.php @@ -34,7 +34,7 @@ function tablaConfiguracionesIniciarSesion($cmd,$idambito,$ambito){ $cabeceraTabla.='</tr>'.chr(13); // Mensaje si no existen datos en la base de datos. $tablaSinConfiguracion='<table id="tabla_conf" width="95%" class="tabla_listados_sin" align="center" border="0" cellpadding="0" cellspacing="1">'.chr(13); - $tablaSinConfiguracion.='<tr><th align="center" >'.$TbMsg["CONFIG_NOCONFIG"].'</th><tr>'.chr(13).'</table>'.chr(13); + $tablaSinConfiguracion.='<tr><th align="center" >'.$TbMsg["CONFIG_NOOS"].'</th><tr>'.chr(13).'</table>'.chr(13); // CONSULTA BD: grupo de equipos con iguales sistemas operativos: idordenadores,configuracion // agrupamos equipos con igual conf de disco. @@ -160,7 +160,7 @@ function tablaConfiguracionesInventarioSoftware($cmd,$idordenador){ if ( $tablaHtml == "" ) { // Equipo sin configuracion en base de datos. $tablaHtml='<table id="tabla_conf" width="95%" class="tabla_listados_sin" align="center" border="0" cellpadding="0" cellspacing="1">'.chr(13); - $tablaHtml.='<tr><th align="center" >'.$TbMsg["CONFIG_NOCONFIG"].'</th><tr>'.chr(13); + $tablaHtml.='<tr><th align="center" >'.$TbMsg["CONFIG_NOOS"].'</th><tr>'.chr(13); } else { @@ -434,8 +434,6 @@ function tablaConfiguracionesCrearSoftIncremental($idordenador) echo $tablaHtml; return($tbPAR); } -<<<<<<< .mine -/**/ // Devuelve un Array nombres de los sistemas operativos en BD con sus identificadores. diff --git a/admin/WebConsole/includes/restfunctions.php b/admin/WebConsole/includes/restfunctions.php index 14cace17..653fcbf3 100644 --- a/admin/WebConsole/includes/restfunctions.php +++ b/admin/WebConsole/includes/restfunctions.php @@ -1,3 +1,4 @@ + <?php define('OG_REST_URL', 'http://127.0.0.1:8888/'); @@ -17,6 +18,14 @@ define('OG_REST_CMD_STOP', 'stop'); define('OG_REST_CMD_REFRESH', 'refresh'); define('OG_REST_CMD_HARDWARE', 'hardware'); define('OG_REST_CMD_SOFTWARE', 'software'); +define('OG_REST_CMD_CREATE_IMAGE', 'image/create'); +define('OG_REST_CMD_RESTORE_IMAGE', 'image/restore'); +define('OG_REST_CMD_SETUP', 'setup'); +define('OG_REST_CMD_CREATE_BASIC_IMAGE', 'image/create/basic'); +define('OG_REST_CMD_CREATE_INCREMENTAL_IMAGE', 'image/create/incremental'); +define('OG_REST_CMD_RESTORE_BASIC_IMAGE', 'image/restore/basic'); +define('OG_REST_CMD_RESTORE_INCREMENTAL_IMAGE', 'image/restore/incremental'); +define('OG_REST_CMD_RUN_SCHEDULE', 'run/schedule'); define('OG_REST_PARAM_CLIENTS', 'clients'); define('OG_REST_PARAM_ADDR', 'addr'); @@ -26,9 +35,33 @@ define('OG_REST_PARAM_PART', 'partition'); define('OG_REST_PARAM_RUN', 'run'); define('OG_REST_PARAM_TYPE', 'type'); define('OG_REST_PARAM_STATE', 'state'); - -$conf_file = parse_ini_file(__DIR__ . '/../../etc/ogAdmRepo.cfg'); -define('OG_REST_API_TOKEN', 'Authorization: ' . $conf_file['ApiToken']); +define('OG_REST_PARAM_NAME', 'name'); +define('OG_REST_PARAM_REPOS', 'repository'); +define('OG_REST_PARAM_ID', 'id'); +define('OG_REST_PARAM_CODE', 'code'); +define('OG_REST_PARAM_PROFILE', 'profile'); +define('OG_REST_PARAM_CACHE', 'cache'); +define('OG_REST_PARAM_CACHE_SIZE', 'cache_size'); +define('OG_REST_PARAM_FILE_SYSTEM', 'filesystem'); +define('OG_REST_PARAM_SIZE', 'size'); +define('OG_REST_PARAM_FORMAT', 'format'); +define('OG_REST_PARAM_PARTITION_SETUP', 'partition_setup'); +define('OG_REST_PARAM_SYNC_PARAMS', 'sync_params'); +define('OG_REST_PARAM_SYNC', 'sync'); +define('OG_REST_PARAM_DIFF', 'diff'); +define('OG_REST_PARAM_REMOVE', 'remove'); +define('OG_REST_PARAM_COMPRESS', 'compress'); +define('OG_REST_PARAM_CLEANUP', 'cleanup'); +define('OG_REST_PARAM_CLEANUP_CACHE', 'cleanup_cache'); +define('OG_REST_PARAM_REMOVE_DST', 'remove_dst'); +define('OG_REST_PARAM_PATH', 'path'); +define('OG_REST_PARAM_DIFF_ID', 'diff_id'); +define('OG_REST_PARAM_DIFF_NAME', 'diff_name'); +define('OG_REST_PARAM_METHOD', 'method'); +define('OG_REST_PARAM_ECHO', 'echo'); + +$conf_file = parse_ini_file(__DIR__ . '/../../etc/ogAdmServer.cfg'); +define('OG_REST_API_TOKEN', 'Authorization: ' . $conf_file['APITOKEN']); function common_request($command, $type, $data = null) { @@ -72,9 +105,17 @@ function shell($case, $string_ips, $command) { $ips = explode(';',$string_ips); switch ($case) { + case 3: + $command = substr($command, 4); + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_RUN => $command, + OG_REST_PARAM_ECHO => false); + $command = OG_REST_CMD_RUN; + break; case 1: $data = array(OG_REST_PARAM_CLIENTS => $ips, - OG_REST_PARAM_RUN => $command); + OG_REST_PARAM_RUN => $command, + OG_REST_PARAM_ECHO => true); $command = OG_REST_CMD_RUN; break; default: @@ -153,6 +194,246 @@ function session($string_ips, $params) { common_request(OG_REST_CMD_SESSION, POST, $data); } +function create_image($string_ips, $params) { + + preg_match_all('/(?<=\=)(.*?)(?=\r)/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $code = $matches[0][2]; + $id = $matches[0][3]; + $name = $matches[0][4]; + $repos = $matches[0][5]; + + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part, + OG_REST_PARAM_CODE => $code, + OG_REST_PARAM_ID => $id, + OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos); + + common_request(OG_REST_CMD_CREATE_IMAGE, POST, $data); +} + +function restore_image($string_ips, $params) { + + preg_match_all('/(?<=\=)(.*?)(?=\r)/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $image_id = $matches[0][2]; + $name = $matches[0][3]; + $repos = $matches[0][4]; + $profile = $matches[0][5]; + $type = $matches[0][6]; + + $data = array(OG_REST_PARAM_DISK => $disk, OG_REST_PARAM_PART => $part, + OG_REST_PARAM_ID => $image_id, OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos, + OG_REST_PARAM_PROFILE => $profile, + OG_REST_PARAM_TYPE => $type, + OG_REST_PARAM_CLIENTS => $ips); + + common_request(OG_REST_CMD_RESTORE_IMAGE, POST, $data); +} + +function create_basic_image($string_ips, $params) { + + preg_match_all('/(?<=\=)[^\r]*(?=\r)?/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $code = $matches[0][2]; + $image_id = $matches[0][3]; + $name = $matches[0][4]; + $repos = $matches[0][5]; + + $sync = $matches[0][7]; // Syncronization method + + $diff = $matches[0][8]; // Send the whole file if there are differences + $remove = $matches[0][9]; // Delete files at destination that are not at source + $compress = $matches[0][10]; // Compress before sending + + $cleanup = $matches[0][11]; // Delete image before creating it + $cache = $matches[0][12]; // Copy image to cache + $cleanup_cache = $matches[0][13]; // Delete image from cache before copying + $remove_dst = $matches[0][14]; // Dont delete files in destination + + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part, + OG_REST_PARAM_CODE => $code, + OG_REST_PARAM_ID => $image_id, + OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos, + OG_REST_PARAM_SYNC_PARAMS => array( + OG_REST_PARAM_SYNC => $sync, + OG_REST_PARAM_DIFF => $diff, + OG_REST_PARAM_REMOVE => $remove, + OG_REST_PARAM_COMPRESS => $compress, + OG_REST_PARAM_CLEANUP => $cleanup, + OG_REST_PARAM_CACHE => $cache, + OG_REST_PARAM_CLEANUP_CACHE => $cleanup_cache, + OG_REST_PARAM_REMOVE_DST => $remove_dst, + ) + ); + + common_request(OG_REST_CMD_CREATE_BASIC_IMAGE, POST, $data); +} + +function create_incremental_image($string_ips, $params) { + + preg_match_all('/(?<=\=)[^\r]*(?=\r)?/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $id = $matches[0][2]; + $name = $matches[0][3]; + $repos = $matches[0][4]; + $diff_id = $matches[0][5]; + $diff_name = $matches[0][6]; + $path = $matches[0][7]; + $sync = $matches[0][8]; + $diff = $matches[0][9]; + $remove = $matches[0][10]; + $compress = $matches[0][11]; + $cleanup = $matches[0][12]; + $cache = $matches[0][13]; + $cleanup_cache = $matches[0][14]; + $remove_dst = $matches[0][15]; + + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part, + OG_REST_PARAM_ID => $id, + OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos, + OG_REST_PARAM_SYNC_PARAMS => array( + OG_REST_PARAM_SYNC => $sync, + OG_REST_PARAM_PATH => $path, + OG_REST_PARAM_DIFF => $diff, + OG_REST_PARAM_DIFF_ID => $diff_id, + OG_REST_PARAM_DIFF_NAME => $diff_name, + OG_REST_PARAM_REMOVE => $remove, + OG_REST_PARAM_COMPRESS => $compress, + OG_REST_PARAM_CLEANUP => $cleanup, + OG_REST_PARAM_CACHE => $cache, + OG_REST_PARAM_CLEANUP_CACHE => $cleanup_cache, + OG_REST_PARAM_REMOVE_DST => $remove_dst) + ); + + common_request(OG_REST_CMD_CREATE_INCREMENTAL_IMAGE, POST, $data); +} + +function restore_basic_image($string_ips, $params) { + + preg_match_all('/(?<=\=)[^\r]*(?=\r)?/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $image_id = $matches[0][2]; + $name = $matches[0][3]; + $repos = $matches[0][4]; + $profile = $matches[0][5]; + + $path = $matches[0][6]; + $method = $matches[0][7]; + $sync = $matches[0][8]; // Syncronization method + + $type = $matches[0][9]; + + $diff = $matches[0][10]; // Send the whole file if there are differences + $remove = $matches[0][11]; // Delete files at destination that are not at source + $compress = $matches[0][12]; // Compress before sending + + $cleanup = $matches[0][13]; // Delete image before creating it + $cache = $matches[0][14]; // Copy image to cache + $cleanup_cache = $matches[0][15]; // Delete image from cache before copying + $remove_dst = $matches[0][16]; // Dont delete files in destination + + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part, + OG_REST_PARAM_ID => $image_id, + OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos, + OG_REST_PARAM_PROFILE => $profile, + OG_REST_PARAM_TYPE => $type, + OG_REST_PARAM_SYNC_PARAMS => array( + OG_REST_PARAM_PATH => $path, + OG_REST_PARAM_METHOD => $method, + OG_REST_PARAM_SYNC => $sync, + OG_REST_PARAM_DIFF => $diff, + OG_REST_PARAM_REMOVE => $remove, + OG_REST_PARAM_COMPRESS => $compress, + OG_REST_PARAM_CLEANUP => $cleanup, + OG_REST_PARAM_CACHE => $cache, + OG_REST_PARAM_CLEANUP_CACHE => $cleanup_cache, + OG_REST_PARAM_REMOVE_DST => $remove_dst, + ) + ); + + common_request(OG_REST_CMD_RESTORE_BASIC_IMAGE, POST, $data); +} + +function restore_incremental_image($string_ips, $params) { + + preg_match_all('/(?<=\=)[^\r]*(?=\r)?/', $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; + $image_id = $matches[0][2]; + $name = $matches[0][3]; + $repos = $matches[0][4]; + $profile = $matches[0][5]; + $diff_id = $matches[0][6]; + $diff_name = $matches[0][7]; + $path = $matches[0][8]; + $method = $matches[0][9]; + $sync = $matches[0][10]; + $type = $matches[0][11]; + $diff = $matches[0][12]; + $remove = $matches[0][13]; + $compress = $matches[0][14]; + $cleanup = $matches[0][15]; + $cache = $matches[0][16]; + $cleanup_cache = $matches[0][17]; + $remove_dst = $matches[0][18]; + + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part, + OG_REST_PARAM_ID => $image_id, + OG_REST_PARAM_NAME => $name, + OG_REST_PARAM_REPOS => $repos, + OG_REST_PARAM_PROFILE => $profile, + OG_REST_PARAM_TYPE => $type, + OG_REST_PARAM_SYNC_PARAMS => array( + OG_REST_PARAM_DIFF_ID => $diff_id, + OG_REST_PARAM_DIFF_NAME => $diff_name, + OG_REST_PARAM_PATH => $path, + OG_REST_PARAM_METHOD => $method, + OG_REST_PARAM_SYNC => $sync, + OG_REST_PARAM_DIFF => $diff, + OG_REST_PARAM_REMOVE => $remove, + OG_REST_PARAM_COMPRESS => $compress, + OG_REST_PARAM_CLEANUP => $cleanup, + OG_REST_PARAM_CACHE => $cache, + OG_REST_PARAM_CLEANUP_CACHE => $cleanup_cache, + OG_REST_PARAM_REMOVE_DST => $remove_dst, + ) + ); + + common_request(OG_REST_CMD_RESTORE_INCREMENTAL_IMAGE, POST, $data); +} + function poweroff($string_ips) { $ips = explode(';',$string_ips); @@ -198,15 +479,71 @@ function hardware($string_ips) { common_request(OG_REST_CMD_HARDWARE, POST, $data); } -function software($string_ips) { +function software($string_ips, $params) { + + preg_match_all('/(?<=\=)(.*?)(?=\r)/', $params, $matches); $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $part = $matches[0][1]; - $data = array(OG_REST_PARAM_CLIENTS => $ips); + $data = array(OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_PART => $part); common_request(OG_REST_CMD_SOFTWARE, POST, $data); } +function setup($string_ips, $params) { + + preg_match_all('/(?<=\=)(?!dis)(.*?)((?=\*)|(?=\r)|(?=\!)|(?=\%))/', + $params, $matches); + + $ips = explode(';',$string_ips); + $disk = $matches[0][0]; + $cache = $matches[0][2]; + $cache_size = $matches[0][3]; + $partition_number = array(); + $partition_code = array(); + $file_system = array(); + $part_size = array(); + $format = array(); + for ($x = 0; $x < 4; $x++) { + $partition_number[$x] = $matches[0][4 + 5 * $x]; + $partition_code[$x] = $matches[0][5 + 5 * $x]; + $file_system[$x] = $matches[0][6 + 5 * $x]; + $part_size[$x] = $matches[0][7 + 5 * $x]; + $format[$x] = $matches[0][8 + 5 * $x]; + } + + $data = array( + OG_REST_PARAM_CLIENTS => $ips, + OG_REST_PARAM_DISK => $disk, + OG_REST_PARAM_CACHE => $cache, + OG_REST_PARAM_CACHE_SIZE => $cache_size, + OG_REST_PARAM_PARTITION_SETUP => array() + ); + + for ($i = 0; $i < sizeof($partition_number); $i++) { + $partition_setup = array( + OG_REST_PARAM_PART => $partition_number[$i], + OG_REST_PARAM_CODE => $partition_code[$i], + OG_REST_PARAM_FILE_SYSTEM => $file_system[$i], + OG_REST_PARAM_SIZE => $part_size[$i], + OG_REST_PARAM_FORMAT => $format[$i] + ); + array_push($data[OG_REST_PARAM_PARTITION_SETUP], $partition_setup); + } + + common_request(OG_REST_CMD_SETUP, POST, $data); +} + +function run_schedule($string_ips) { + $ips = explode(';',$string_ips); + $data = array(OG_REST_PARAM_CLIENTS => $ips); + common_request(OG_REST_CMD_RUN_SCHEDULE, POST, $data); +} + /* * @function multiRequest. * @param URLs array (may include header and POST data), cURL options array. diff --git a/admin/WebConsole/jscripts/propiedades_ordenadores.js b/admin/WebConsole/jscripts/propiedades_ordenadores.js index ff7c3c7a..41aef413 100644 --- a/admin/WebConsole/jscripts/propiedades_ordenadores.js +++ b/admin/WebConsole/jscripts/propiedades_ordenadores.js @@ -27,7 +27,7 @@ function cancelar(){ //________________________________________________________________________________________________________ function resultado_insertar_ordenadores(resul,descrierror,nwid,tablanodo){ farbol.resultado_insertar(resul,descrierror,nwid,tablanodo); - selfclose(); + //selfclose(); } //________________________________________________________________________________________________________ // @@ -40,7 +40,7 @@ function resultado_insertar_ordenadores(resul,descrierror,nwid,tablanodo){ //________________________________________________________________________________________________________ function resultado_modificar_ordenadores(resul,descrierror,lit){ farbol.resultado_modificar(resul,descrierror,lit); - selfclose(); + //selfclose(); } //________________________________________________________________________________________________________ // @@ -53,11 +53,11 @@ function resultado_modificar_ordenadores(resul,descrierror,lit){ //________________________________________________________________________________________________________ function resultado_eliminar_ordenadores(resul,descrierror,id){ farbol.resultado_eliminar(resul,descrierror,id); - selfclose(); + //selfclose(); } //________________________________________________________________________________________________________ function selfclose(){ - //document.location.href="../nada.php"; + document.location.href="../nada.php"; } //________________________________________________________________________________________________________ // diff --git a/admin/WebConsole/jscripts/tareascomandos.js b/admin/WebConsole/jscripts/tareascomandos.js deleted file mode 100644 index ff1a3b77..00000000 --- a/admin/WebConsole/jscripts/tareascomandos.js +++ /dev/null @@ -1,78 +0,0 @@ -// ************************************************************************************************************************************************* -// Libreria de scripts de Javascript -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: 2009-2010 -// Fecha Última modificación: Agosto-2010 -// Nombre del fichero: tareascomandos.js -// Descripción : -// Este fichero implementa las funciones javascript del fichero tareascomandos.php -// ************************************************************************************************************************************************* -var currentidtareacomando=null; -//________________________________________________________________________________________________________ -function gestion_comandos(id,o,orden){ - if (o.checked) - var opcion=op_modificacion; - else - var opcion=op_eliminacion; - var wurl="../gestores/gestor_tareascomandos.php"; - var prm="opcion="+opcion+"&idtareacomando="+id+"&orden="+orden; - CallPage(wurl,prm,"retornoGestion","POST"); -} -//______________________________________________________________________________________________________ -function retornoGestion(resul){ - if(resul.length>0){ - eval(resul); - } -} -//________________________________________________________________________________________________________ -function ActualizarAccion(id){ - var objorden=document.getElementById("orden-"+id); - var orden=objorden.value; - if(orden=="" || orden<1){ - alert(TbMsg[1]); - oorden.focus(); - return - } - var ocheckbox=document.getElementById("checkbox-"+id); - gestion_comandos(id,ocheckbox,orden) -} -//________________________________________________________________________________________________________ -function resultado_eliminar_tareacomando(resul,descrierror,idtt){ - if (!resul){ // Ha habido algún error en la eliminación - alert(descrierror); - return - } - alert(TbMsg[2]); - var oTABLE=document.getElementById("TABLACOMANDOS"); - var oTRs=oTABLE.getElementsByTagName('TR'); - for(var i=0;i<oTRs.length;i++){ - if(oTRs[i].getAttribute("id")=='TR-'+currentidtareacomando || oTRs[i].getAttribute("id")=='PAR-'+currentidtareacomando) - oTRs[i].style.display="none" - } -} -//________________________________________________________________________________________________________ -function resultado_modificar_tareacomando(resul,descrierror,id){ - if (!resul){ // Ha habido algún error en la eliminación - alert(descrierror); - return - } - alert(TbMsg[3]) -} -//________________________________________________________________________________________________________ -function ver_parametros(o,sw,ida){ - o=o.parentNode; - o.childNodes[sw].style.display="none"; - sw++; - if(sw>1)sw=0; - o.childNodes[sw].style.display="block"; - while (o.tagName!="TBODY"){ - o=o.parentNode - } - var oTRs=o.getElementsByTagName('TR'); - for(var i=0;i<oTRs.length;i++){ - if(oTRs[i].getAttribute("id")=='PAR-'+ida) - if (oTRs[i].style.display=="none") oTRs[i].style.display="block"; - else - oTRs[i].style.display="none" - } - } diff --git a/admin/WebConsole/principal/actualizar.php b/admin/WebConsole/principal/actualizar.php index 500b0b89..0ef8d7c7 100644 --- a/admin/WebConsole/principal/actualizar.php +++ b/admin/WebConsole/principal/actualizar.php @@ -9,7 +9,6 @@ // Obliga a los clientes a reiniciar la sesión en el sistema // ************************************************************************************************************************************************* include_once("../includes/ctrlacc.php"); - include_once("../clases/SockHidra.php"); include_once("../clases/AdoPhp.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); diff --git a/admin/WebConsole/principal/aula.php b/admin/WebConsole/principal/aula.php index f300c508..05f38a4d 100644 --- a/admin/WebConsole/principal/aula.php +++ b/admin/WebConsole/principal/aula.php @@ -12,7 +12,6 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/MenuContextual.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/CreaComando.php"); diff --git a/admin/WebConsole/principal/boot_grub4dos.php b/admin/WebConsole/principal/boot_grub4dos.php index fbd7e171..680d53ad 100644 --- a/admin/WebConsole/principal/boot_grub4dos.php +++ b/admin/WebConsole/principal/boot_grub4dos.php @@ -31,6 +31,7 @@ switch($litambito){ break; case "gruposordenadores": $seleccion= "and grupoid=" . $idambito . ""; + break; default: $seleccion=""; break; diff --git a/admin/WebConsole/principal/ecoconsola.php b/admin/WebConsole/principal/ecoconsola.php index 26ea1b61..e89b0cd0 100644 --- a/admin/WebConsole/principal/ecoconsola.php +++ b/admin/WebConsole/principal/ecoconsola.php @@ -9,7 +9,6 @@ // Consulta el eco de los clientes a traqvés de la consola remota // ************************************************************************************************************************************************* include_once("../includes/ctrlacc.php"); - include_once("../clases/SockHidra.php"); include_once("../clases/AdoPhp.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); diff --git a/admin/WebConsole/principal/ecoremoto.php b/admin/WebConsole/principal/ecoremoto.php deleted file mode 100644 index 3b022595..00000000 --- a/admin/WebConsole/principal/ecoremoto.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -// ************************************************************************************************************************************************* -// Aplicación WEB: ogAdmWebCon -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Año 2010 -// Fecha Última modificación: Marzo-2010 -// Nombre del fichero: ecoremoto.php -// Descripción : -// Crea una consola remota para escribir comandos de la shell de forma remota -// ************************************************************************************************************************************************* -include_once("../includes/ctrlacc.php"); -include_once("../clases/AdoPhp.php"); -include_once("../includes/constantes.php"); -include_once("../includes/CreaComando.php"); -include_once("../idiomas/php/".$idioma."/ecoremoto_".$idioma.".php"); -//________________________________________________________________________________________________________ -$cmd=CreaComando($cadenaconexion); -if (!$cmd) - Header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. -//___________________________________________________________________________________________________ -$idambito=""; -$litambito=""; -$nomambito=""; - -if (isset($_GET["idambito"])) $idambito=$_GET["idambito"]; -if (isset($_GET["litambito"])) $litambito=$_GET["litambito"]; -if (isset($_GET["nomambito"])) $nomambito=$_GET["nomambito"]; -//___________________________________________________________________________________________________ -?> -<HTML> -<TITLE>Eco-<?php echo $nomambito?></TITLE> -<HEAD> - <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> -<LINK rel="stylesheet" type="text/css" href="../estilos.css"> -</HEAD> -<BODY> -<SCRIPT language="javascript" src="../clases/jscripts/HttpLib.js"></SCRIPT> -<SCRIPT language="javascript" src="../jscripts/ecoremoto.js"></SCRIPT> -<SCRIPT language="javascript" src="../jscripts/constantes.js"></SCRIPT> -<SCRIPT language="javascript"> -//______________________________________________________________________________________________________ -</SCRIPT> - <FORM name="fdatos" action="shellconsola.php"> - <INPUT type=hidden name="idambito" value=<?php echo $idambito?>> - <INPUT type=hidden name="litambito" value=<?php echo $litambito?>> - <INPUT type=hidden name="nomambito" value=<?php echo $nomambito?>> - </FORM> - -<?php -switch($litambito){ - case $LITAMBITO_CENTROS : - $urlimg='../images/iconos/centros.gif'; - $textambito=$TbMsg[0]; - break; - case $LITAMBITO_GRUPOSAULAS : - $urlimg='../images/iconos/carpeta.gif'; - $textambito=$TbMsg[1]; - break; - case $LITAMBITO_AULAS : - $urlimg='../images/iconos/aula.gif'; - $textambito=$TbMsg[2]; - break; - case $LITAMBITO_GRUPOSORDENADORES : - $urlimg='../images/iconos/carpeta.gif'; - $textambito=$TbMsg[3]; - break; - case $LITAMBITO_ORDENADORES : - $urlimg='../images/iconos/ordenador.gif'; - $textambito=$TbMsg[4]; - break; - } -?> - <P align=center class=cabeceras><?php echo $TbMsg[7]?><BR> - <SPAN align=center class=subcabeceras> - <IMG src="<?php echo $urlimg?>"> <?php echo $textambito.": ".$nomambito?></SPAN></P> - <DIV id="Layer_nota" align=center > - <BR> - <SPAN align=center class=notas><I><?php echo $TbMsg[8]?></I></SPAN> - - <table align=center border="0" cellpadding="0" cellspacing="1"> - <tr><td class="presentaciones">Salida</td></tr> - <tr><td> - <div id="diveco" class="marco" align=left style="width:700px;height:500px;overflow:scroll"><P><?php echo $TbMsg[11]?></P></div> - </td></tr> - </table> - </DIV> - -<SCRIPT language="javascript"> - enviaping(); -</SCRIPT> -</BODY> -</HTML> diff --git a/admin/WebConsole/principal/purgar.php b/admin/WebConsole/principal/purgar.php index aef8aebe..66ceb0bd 100644 --- a/admin/WebConsole/principal/purgar.php +++ b/admin/WebConsole/principal/purgar.php @@ -9,7 +9,6 @@ // Obliga a los clientes a reiniciar la sesión en el sistema // ************************************************************************************************************************************************* include_once("../includes/ctrlacc.php"); - include_once("../clases/SockHidra.php"); include_once("../clases/AdoPhp.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); diff --git a/admin/WebConsole/principal/shellconsola.php b/admin/WebConsole/principal/shellconsola.php deleted file mode 100644 index a37276f0..00000000 --- a/admin/WebConsole/principal/shellconsola.php +++ /dev/null @@ -1,192 +0,0 @@ -<?php -// ************************************************************************************************************************************************* -// Aplicación WEB: ogAdmWebCon -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Año 2009-2010 -// Fecha Última modificación: Agosto-2010 -// Nombre del fichero: shellconsola.php -// Descripción : -// Crea una consola remota para enviar comandos de la shell de forma remota y recibir el eco -// ************************************************************************************************************************************************* -include_once("../includes/ctrlacc.php"); -include_once("../clases/SockHidra.php"); -include_once("../clases/AdoPhp.php"); -include_once("../includes/constantes.php"); -include_once("../includes/CreaComando.php"); -include_once("../idiomas/php/".$idioma."/consolaremota_".$idioma.".php"); -//________________________________________________________________________________________________________ -$litambito=0; -$idambito=0; -$comando=""; - -if (isset($_POST["litambito"])) $litambito=$_POST["litambito"]; // Recoge parametros -if (isset($_POST["idambito"])) $idambito=$_POST["idambito"]; -if (isset($_POST["comando"])) $comando=$_POST["comando"]; - -$nombrefuncion="ConsolaRemota"; -$ejecutor="1"; -$cadenaip=""; - -$cmd=CreaComando($cadenaconexion); -if (!$cmd) - Header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. -//________________________________________________________________________________________________________ -if($cmd){ // Compone cadena ip recorriendo ámbitos - switch($litambito){ - case $LITAMBITO_CENTROS : - $cmd->texto="SELECT idcentro,nombrecentro FROM centros WHERE idcentro=".$idambito; - RecorreCentro($cmd); - break; - case $LITAMBITO_GRUPOSAULAS : - $cmd->texto="SELECT idgrupo,nombregrupo FROM grupos WHERE idgrupo=".$idambito." AND tipo=".$AMBITO_GRUPOSAULAS; - RecorreGruposAulas($cmd); - break; - case $LITAMBITO_AULAS : - $cmd->texto="SELECT idaula,nombreaula FROM aulas WHERE idaula=".$idambito; - RecorreAulas($cmd); - break; - case $LITAMBITO_GRUPOSORDENADORES : - $cmd->texto="SELECT idgrupo,nombregrupoordenador FROM gruposordenadores WHERE idgrupo=".$idambito; - RecorreGruposOrdenadores($cmd); - break; - case $LITAMBITO_ORDENADORES : - $cmd->texto="SELECT ip FROM ordenadores WHERE idordenador=".$idambito; - RecorreOrdenadores($cmd); - break; - } -} -$resul=false; -if($cmd){ - $shidra=new SockHidra($servidorhidra,$hidraport); - $cadenaip=preg_replace("/;/", "','", $cadenaip ); - $cmd->texto="SELECT ordenadores.ip as ipord,servidoresrembo.ip FROM ordenadores INNER JOIN servidoresrembo ON ordenadores.idservidorrembo =servidoresrembo.idservidorrembo WHERE ordenadores.ip IN ('".$cadenaip."') ORDER BY servidoresrembo.ip"; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) $resul=false; // Error al abrir recordset - $rs->Primero(); - if(!$rs->EOF){ - $resul=true; - $ipservidorrembo=trim($rs->campos["ip"]); // toma ip servidor rembo - $cadenaip=""; - while(!$rs->EOF && $resul){ - if($ipservidorrembo!=trim($rs->campos["ip"])){ // compara si cambia el servidor rembo - $parametros=$ejecutor; - $parametros.="nfn=".$nombrefuncion.chr(13); - $cadenaip=substr($cadenaip,0,strlen($cadenaip)-1); // Quita la coma - $parametros.="iph=".$cadenaip.chr(13); - $parametros.="rmb=".$ipservidorrembo.chr(13); - $resul=manda_trama(); - $ipservidorrembo=trim($rs->campos["ip"]); // toma ip servidor rembo - $cadenaip=""; - } - $cadenaip.=trim($rs->campos["ipord"]).";"; // toma ip del cliente - $rs->Siguiente(); - } - } - $rs->Cerrar(); - if($resul){ - $parametros=$ejecutor; - $parametros.="nfn=".$nombrefuncion.chr(13); - $parametros.="cmd=".$comando.chr(13); - $cadenaip=substr($cadenaip,0,strlen($cadenaip)-1); // Quita la coma - $parametros.="iph=".$cadenaip.chr(13); - $parametros.="rmb=".$ipservidorrembo.chr(13); - - $resul=manda_trama(); - } -} - - if(!$resul) - echo "alert('".$TbMsg[10]."');"; - -//======================================================================================================= -// Manda una trama del comando shellconsola -//________________________________________________________________________________________________________ -function manda_trama(){ - global $parametros; - global $shidra; - if ($shidra->conectar()){ // Se ha establecido la conexión con el servidor hidra - $shidra->envia_comando($parametros); - $shidra->desconectar(); - return(true); - } - return(false); -} -//________________________________________________________________________________________________________ -function RecorreCentro($cmd){ - global $AMBITO_GRUPOSAULAS; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return; // Error al abrir recordset - $rs->Primero(); - if(!$rs->EOF){ - $idcentro=$rs->campos["idcentro"]; - $cmd->texto="SELECT idgrupo,nombregrupo FROM grupos WHERE idcentro=".$idcentro." AND grupoid=0 AND tipo=".$AMBITO_GRUPOSAULAS." ORDER BY nombregrupo"; - RecorreGruposAulas($cmd); - $cmd->texto="SELECT idaula,nombreaula FROM aulas WHERE idcentro=".$idcentro." AND grupoid=0 ORDER BY nombreaula"; - RecorreAulas($cmd); - } - $rs->Cerrar(); -} -//________________________________________________________________________________________________________ -function RecorreGruposAulas($cmd){ - global $AMBITO_GRUPOSAULAS; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return; // Error al abrir recordset - $rs->Primero(); - while (!$rs->EOF){ - $idgrupo=$rs->campos["idgrupo"]; - $cmd->texto="SELECT idgrupo,nombregrupo FROM grupos WHERE grupoid=".$idgrupo." AND tipo=".$AMBITO_GRUPOSAULAS." ORDER BY nombregrupo"; - RecorreGruposAulas($cmd); - $cmd->texto="SELECT idaula,nombreaula FROM aulas WHERE grupoid=".$idgrupo." ORDER BY nombreaula"; - RecorreAulas($cmd); - $rs->Siguiente(); - } - $rs->Cerrar(); -} -//________________________________________________________________________________________________________ -function RecorreAulas($cmd){ - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return; // Error al abrir recordset - $rs->Primero(); - while (!$rs->EOF){ - $idaula=$rs->campos["idaula"]; - $cmd->texto="SELECT idordenador,nombreordenador,ip,mac FROM ordenadores WHERE idaula=".$idaula; - $k=0; - RecorreOrdenadores($cmd); - $rs->Siguiente(); - } - $rs->Cerrar(); -} -//________________________________________________________________________________________________________ -function RecorreGruposOrdenadores($cmd){ - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return; // Error al abrir recordset - $rs->Primero(); - while (!$rs->EOF){ - $idgrupo=$rs->campos["idgrupo"]; - $cmd->texto="SELECT idgrupo,nombregrupoordenador FROM gruposOrdenadores WHERE grupoid=".$idgrupo." ORDER BY nombregrupoordenador"; - RecorreGruposOrdenadores($cmd); - $cmd->texto="SELECT idordenador,nombreordenador,ip,mac FROM ordenadores WHERE grupoid=".$idgrupo; - RecorreOrdenadores($cmd); - $rs->Siguiente(); - } - $rs->Cerrar(); -} -//________________________________________________________________________________________________________ -function RecorreOrdenadores($cmd){ - global $cadenaip; - $rs=new Recordset; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return; // Error al abrir recordset - $rs->Primero(); - while (!$rs->EOF){ - $cadenaip.=$rs->campos["ip"].";"; - $rs->Siguiente(); - } - $rs->Cerrar(); -} - diff --git a/admin/WebConsole/principal/sondeo.php b/admin/WebConsole/principal/sondeo.php index 90493d58..6cb76baa 100644 --- a/admin/WebConsole/principal/sondeo.php +++ b/admin/WebConsole/principal/sondeo.php @@ -13,7 +13,6 @@ // ************************************************************************************************************************************************* include_once("../includes/ctrlacc.php"); include_once("../includes/restfunctions.php"); - include_once("../clases/SockHidra.php"); include_once("../clases/AdoPhp.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); diff --git a/admin/WebConsole/principal/ubicarordenadores.php b/admin/WebConsole/principal/ubicarordenadores.php index 2cd31b3c..92f2a3e3 100644 --- a/admin/WebConsole/principal/ubicarordenadores.php +++ b/admin/WebConsole/principal/ubicarordenadores.php @@ -86,7 +86,6 @@ include_once("../includes/ctrlacc.php"); include_once("../clases/AdoPhp.php"); include_once("../clases/XmlPhp.php"); include_once("../clases/MenuContextual.php"); -include_once("../clases/SockHidra.php"); include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); include_once("../includes/CreaComando.php"); diff --git a/admin/WebConsole/propiedades/propiedades_aulas.php b/admin/WebConsole/propiedades/propiedades_aulas.php index 7042d5ca..8bf2f8b5 100644 --- a/admin/WebConsole/propiedades/propiedades_aulas.php +++ b/admin/WebConsole/propiedades/propiedades_aulas.php @@ -354,10 +354,10 @@ function abrir_ventana(URL){ echo '<TD colspan=3>'.$pormul.'</TD>'; else { echo '<td colspan="3">'; - for ($i=9000; $i<9100; $i+=2) { + for ($i=9000; $i<9098; $i+=2) { $pormulmetodos.="$i=$i".chr(13); } - $pormulmetodos.="9100=9100"; + $pormulmetodos.="9098=9098"; echo HTMLCTESELECT($pormulmetodos,"pormul","estilodesple","",$pormul,100).'</td>'; } ?> @@ -640,8 +640,6 @@ function TomaPropiedades($cmd,$ida) if(count(explode(",",$idrepositorio))>1) $idrepositorio=0; $idperfilhard=$rs->campos["idperfileshard"]; if(count(explode(",",$idperfilhard))>1) $idperfilhard=0; - $idmenu=$rs->campos["idmenus"]; - if(count(explode(",",$idmenu))>1) $idmenu=0; $idprocedimiento=$rs->campos["idprocedimientos"]; if(count(explode(",",$idprocedimiento))>1) $idprocedimiento=0; diff --git a/admin/WebConsole/propiedades/propiedades_repositorios.php b/admin/WebConsole/propiedades/propiedades_repositorios.php index 7bdb6713..9321b4a7 100644 --- a/admin/WebConsole/propiedades/propiedades_repositorios.php +++ b/admin/WebConsole/propiedades/propiedades_repositorios.php @@ -7,6 +7,7 @@ // Nombre del fichero: propiedades_repositorios.php // Descripción : // Presenta el formulario de captura de datos de un repositorio para insertar,modificar y eliminar +// Version 1.1.1: Si las OU están separadas por directorios, sólo muestra las imágenes del subdir definido // ********************************************************************************************************** include_once("../includes/ctrlacc.php"); include_once("../includes/opciones.php"); @@ -28,11 +29,14 @@ $grupoid=0; $comentarios=""; $ordenadores=0; // Número de ordenador a los que da servicio $numordenadores=0; // Número de ordenador a los que da servicio +$dirOU=""; // Directorio de la unidad organizativa if (isset($_GET["opcion"])) $opcion=$_GET["opcion"]; // Recoge parametros if (isset($_GET["idrepositorio"])) $idrepositorio=$_GET["idrepositorio"]; if (isset($_GET["grupoid"])) $grupoid=$_GET["grupoid"]; if (isset($_GET["identificador"])) $idrepositorio=$_GET["identificador"]; +$idcentro = (isset($_SESSION["widcentro"])) ? $_SESSION["widcentro"] : ""; + //________________________________________________________________________________________________________ $cmd=CreaComando($cadenaconexion); // Crea objeto comando if (!$cmd) @@ -42,6 +46,9 @@ if ($opcion!=$op_alta){ if (!$resul) Header('Location: '.$pagerror.'?herror=3'); // Error de recuperaci�n de datos. } +// Obtenemos directorio de la Unidad Organizativa +if ($idcentro != "") TomaDirectorioOU($cmd,$idcentro); + //________________________________________________________________________________________________________ //######################################################################### @@ -161,10 +168,13 @@ if($apiKeyRepo != ""){ </TR> <?php // Si tenemos informacion del repositorio remoto, mostramos las imagenes - if($repoWithApi == true && is_array($repoImages)){ - echo "<tr class='tabla_listados_sin'><th colspan='4'>".$TbMsg['MSG_CONTENT']." $repodir</th></tr>\n"; + if ($repoWithApi == true) { + $cabeceraTabla= "<tr class='tabla_listados_sin'><th colspan='4'>".$TbMsg['MSG_CONTENT']." $repodir</th></tr>\n". + "<tr><td>".$TbMsg['MSG_IMAGE']." (".$TbMsg['MSG_TYPE'].")</td><td>".$TbMsg['MSG_SIZE']."</td><td>".$TbMsg['MSG_MODIFIED']."</td><td>".$TbMsg['MSG_PERMISSIONS']."</td></tr>\n"; -echo "<tr><td>".$TbMsg['MSG_IMAGE']." (".$TbMsg['MSG_TYPE'].")</td><td>".$TbMsg['MSG_SIZE']."</td><td>".$TbMsg['MSG_MODIFIED']."</td><td>".$TbMsg['MSG_PERMISSIONS']."</td></tr>\n"; + if ($dirOU == "" && is_array($repoImages) && !empty($repoImages)) { + echo $cabeceraTabla; + $cabeceraTabla = ""; foreach($repoImages as $image){ echo "<tr class='tabla_listados_sin'>"; echo "<td>".$image->name." (".$image->type.")</td>"; @@ -173,16 +183,20 @@ echo "<tr><td>".$TbMsg['MSG_IMAGE']." (".$TbMsg['MSG_TYPE'].")</td><td>".$TbMsg[ echo "<td>".$image->mode."</td>"; echo "</tr>\n"; } - foreach($repoOus as $ou) { + } + foreach($repoOus as $ou) { + if ($dirOU != "" && $ou->subdir != $dirOU) continue; + echo $cabeceraTabla; + $cabeceraTabla = ""; foreach($ou->images as $image) { echo "<tr class='tabla_listados_sin'>"; echo "<td>".$ou->subdir." / ".$image->name." (".$image->type.")</td>"; - echo "<td>".$image->size." bytes</td>"; + echo "<td>".humanSize($image->size)."</td>"; echo "<td>".$image->modified."</td>"; echo "<td>".$image->mode."</td>"; echo "</tr>\n"; } - } + } } ?> <?php }else { ?> @@ -237,3 +251,27 @@ EOT; $rs->Cerrar(); return(true); } + +//______________________________________________________________________________ +// Recupera directorio de la unidad organizativa (si no están separados '') +// Parametros: +// - cmd: Una comando ya operativo (con conexión abierta) +// - id: El identificador del repositorio +//________________________________________________________________________________________________________ +function TomaDirectorioOU($cmd,$idOU){ + global $dirOU; + $cmd->texto=<<<EOT +SELECT if(ogunit=1, directorio, "") AS dirOU + FROM entidades, centros + WHERE idcentro='$idOU'; +EOT; + $rs=new Recordset; + $rs->Comando=&$cmd; + if (!$rs->Abrir()) return(true); // Error al abrir recordset + $rs->Primero(); + if (!$rs->EOF){ + $dirOU=$rs->campos["dirOU"]; + } + $rs->Cerrar(); + return(true); +} diff --git a/admin/WebConsole/rest/common.php b/admin/WebConsole/rest/common.php index d26acc4b..5b49cda8 100644 --- a/admin/WebConsole/rest/common.php +++ b/admin/WebConsole/rest/common.php @@ -68,14 +68,10 @@ function jsonResponse($status, $response, $opts=0) { * @return string JSON response. */ function jsonResponseNow($status, $response, $opts=0) { - // Flush buffer. - ob_end_clean(); - ob_end_flush(); - header("Connection: close"); // Compose headers and content. + ignore_user_abort(); http_response_code((int)$status); header('Content-type: application/json; charset=utf-8'); - ignore_user_abort(); ob_start(); echo json_encode($response, $opts); $size = ob_get_length(); @@ -88,12 +84,12 @@ function jsonResponseNow($status, $response, $opts=0) { /** * @brief Validate API key included in "Authorization" HTTP header. - * @return JSON response on error. + * @return string JSON response on error. */ function validateApiKey() { global $cmd; global $userid; - $response = array(); + $response = []; $app = \Slim\Slim::getInstance(); // Read Authorization HTTP header. if (! empty($_SERVER['HTTP_AUTHORIZATION'])) { @@ -110,8 +106,8 @@ function validateApiKey() { // Fetch user id. $userid = $rs->campos["idusuario"]; } else { - // Credentials error. - $response['message'] = 'Login failed. Incorrect credentials'; + // Credentials error. + $response['message'] = 'Login failed, incorrect credentials'; jsonResponse(401, $response); $app->stop(); } @@ -135,6 +131,7 @@ function validateApiKey() { * @return boolean "false" if parameter is null, otherwise "true". */ function checkParameter($param) { + $response = []; if (isset($param)) { return true; } else { @@ -151,7 +148,7 @@ function checkParameter($param) { * @return boolean "true" if all ids are int>0, otherwise "false". */ function checkIds() { - $opts = Array('options' => Array('min_range' => 1)); // Check for int>0 + $opts = ['options' => ['min_range' => 1]]; // Check for int>0 foreach (func_get_args() as $id) { if (filter_var($id, FILTER_VALIDATE_INT, $opts) === false) { return false; @@ -161,62 +158,16 @@ function checkIds() { } /** - * @fn sendCommand($serverip, $serverport, $reqframe, &$values) - * @brief Send a command to an OpenGnsys ogAdmServer and get request. - * @param string serverip Server IP address. - * @param string serverport Server port. - * @param string reqframe Request frame (field's separator is "\r"). - * @param array values Response values (out parameter). - * @return boolean "true" if success, otherwise "false". - */ -function sendCommand($serverip, $serverport, $reqframe, &$values) { - global $LONCABECERA; - global $LONHEXPRM; - - // Connect to server. - $respvalues = ""; - $connect = new SockHidra($serverip, $serverport); - if ($connect->conectar()) { - // Send request frame to server. - $result = $connect->envia_peticion($reqframe); - if ($result) { - // Parse request frame. - $respframe = $connect->recibe_respuesta(); - $connect->desconectar(); - $paramlen = hexdec(substr($respframe, $LONCABECERA, $LONHEXPRM)); - $params = substr($respframe, $LONCABECERA+$LONHEXPRM, $paramlen); - // Fetch values and return result. - $values = extrae_parametros($params, "\r", '='); - return ($values); - } else { - // Return with error. - return (false); - } - } else { - // Return with error. - return (false); - } -} - -/** * @brief Show custom message for "not found" error (404). */ -$app->notFound(function() { - echo "REST route not found."; +$app->notFound( + function() { + $response['message'] = 'REST route not found'; + jsonResponse(404, $response); } ); /** - * @brief Hook to write a REST init log message, if debug is enabled. - * @warning Message will be written in REST log file. - */ -$app->hook('slim.before', function() use ($app) { - if ($app->settings['debug']) - writeRestLog("Init."); - } -); - -/** * @brief Hook to write an error log message and a REST exit log message if debug is enabled. * @warning Error message will be written in web server's error file. * @warning REST message will be written in REST log file. @@ -234,7 +185,7 @@ $app->hook('slim.after', function() use ($app) { substr($app->response->getBody(), 0, 100)); } if ($app->settings['debug']) - writeRestLog("Exit."); + writeRestLog(substr($app->response->getBody(), 0, 30)); } ); @@ -244,8 +195,7 @@ $app->hook('slim.after', function() use ($app) { /** * @brief Get general server information * @note Route: /info, Method: GET - * @param no - * @return JSON object with basic server information (version, services, etc.) + * @return string JSON object with basic server information (version, services, etc.) */ $app->get('/info', function() { $hasOglive = false; @@ -259,7 +209,7 @@ $app->get('/info', function() { } // Getting actived services. @$services = parse_ini_file('/etc/default/opengnsys'); - $response->services = Array(); + $response->services = []; if (@$services["RUN_OGADMSERVER"] === "yes") { array_push($response->services, "server"); $hasOglive = true; @@ -280,10 +230,10 @@ $app->get('/info', function() { /** * @brief Get the server status * @note Route: /status, Method: GET - * @param no - * @return JSON object with all data collected from server status (RAM, %CPU, etc.). + * @return string JSON object with all data collected from server status (RAM, %CPU, etc.). */ $app->get('/status', function() { + $response = []; // Getting memory and CPU information. exec("awk '$1~/Mem/ {print $2}' /proc/meminfo",$memInfo); $memInfo = array("total" => $memInfo[0], "used" => $memInfo[1]); diff --git a/admin/WebConsole/rest/index.php b/admin/WebConsole/rest/index.php index aa7cd483..17f9a568 100644 --- a/admin/WebConsole/rest/index.php +++ b/admin/WebConsole/rest/index.php @@ -6,7 +6,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. * @license GNU GPLv3+ * @author Ramón M. Gómez, ETSII Univ. Sevilla - * @version 1.1 + * @version 1.1.0 * @date 2016-05-19 */ @@ -16,34 +16,33 @@ include_once("../controlacceso.php"); include_once("../clases/AdoPhp.php"); include_once("../includes/CreaComando.php"); -// Connection class. -@include_once("../includes/constantes.php"); +include_once("../includes/constantes.php"); include_once("../includes/comunes.php"); -include_once("../clases/SockHidra.php"); // REST functions. -@include_once("../includes/restfunctions.php"); +include_once("../includes/restfunctions.php"); // Slim framework. include_once("Slim/Slim.php"); \Slim\Slim::registerAutoloader(); // Server access control. $cmd = CreaComando($cnx); -if (!$cmd) - die("Access Error"); +if (!$cmd) { + die("Access Error"); +} -// Install Slim application (development mode). -//$app = new \Slim\Slim(array('mode' => 'production', ... ); -$app = new \Slim\Slim(array( - 'mode' => 'development', - 'log.enabled' => true, - 'log.level' => \Slim\Log::ERROR, - 'debug' => true)); +// Install Slim application. +$app = new \Slim\Slim([ + 'mode' => 'development', // Mode (production or development). + 'log.enabled' => true, // Using logs. + 'log.level' => \Slim\Log::ERROR, // Log level. + 'debug' => true, // Generating debug info. +]); $app->setName('opengnsys'); // Global variables. -$userid = NULL; // User id. with access to REST API. +$userid = NULL; // User id. with access to REST API. -// Common funtions and routes. +// Common functions and routes. include("common.php"); // Check if services are running. @@ -72,4 +71,3 @@ $app->get('/', // Execute REST using Slim. $app->run(); - diff --git a/admin/WebConsole/rest/ogagent.php b/admin/WebConsole/rest/ogagent.php index be62a8d0..ca6d783e 100644 --- a/admin/WebConsole/rest/ogagent.php +++ b/admin/WebConsole/rest/ogagent.php @@ -240,19 +240,18 @@ EOD; // Read query data. $rs->Primero(); $id = $rs->campos['idordenador']; - $redirto[0]['url'] = $rs->campos['urllogout']; + $url = $rs->campos['urllogout']; $reserved = $rs->campos['reserved']; $rs->Cerrar(); if (!is_null($id)) { // Log activity, respond to client and continue processing. writeLog("User logged out: ip=$ip, user=$user."); - $response = ""; - jsonResponseNow(200, $response); } else { throw new Exception("Client is not in the database: ip=$ip, user=$user"); } // Redirect notification to UDS server, if needed. - if ($reserved == 1 and !is_null($redirto[0]['url'])) { + if ($reserved == 1 and !is_null($url)) { + $redirto[0]['url'] = $url; $redirto[0]['get'] = $app->request()->getBody(); $result = multiRequest($redirto); // ... (check response) @@ -268,6 +267,8 @@ EOD; writeLog($app->request()->getResourceUri().": ERROR: ".$response["message"]); jsonResponse(400, $response); } + $response = ""; + jsonResponse(200, $response); } ); diff --git a/admin/WebConsole/rest/opengnsys-api.yml b/admin/WebConsole/rest/opengnsys-api.yml index 13ea37a1..bea6cae2 100644 --- a/admin/WebConsole/rest/opengnsys-api.yml +++ b/admin/WebConsole/rest/opengnsys-api.yml @@ -1,11 +1,11 @@ swagger: '2.0' info: - version: "1.1.0" + version: "1.1.1" title: OpenGnsys REST API definition description: | Information about the OpenGnsys REST API functions (including Server and - Repository Manager). + Repository Manager) contact: name: OpenGnsys Project url: https://opengnsys.es/ @@ -24,11 +24,10 @@ securityDefinitions: type: apiKey name: Authorization in: header -# Paths description. paths: /login: post: - description: Check user login and returns his/her API key. + description: Check user login and returns his/her API key parameters: - in: body name: authdata @@ -62,7 +61,7 @@ paths: properties: message: type: string - "500": + "401": description: Authentication error schema: type: object @@ -74,7 +73,7 @@ paths: - user /info: get: - description: Gets OpenGnsys Server information + description: Get OpenGnsys Server information responses: "200": description: Successful response @@ -134,7 +133,7 @@ paths: - repository /status: get: - description: Gets OpenGnsys Server status information + description: Get OpenGnsys Server status information responses: "200": description: Successful response @@ -169,7 +168,7 @@ paths: - server /ous: get: - description: Gets all `OU` objects. + description: Get all `OU` objects responses: "200": description: Successful response @@ -192,7 +191,7 @@ paths: - ou /ous/{ouid}: get: - description: Get an `OU` object. + description: Get an `OU` object parameters: - $ref: "#/parameters/ouParam" responses: @@ -218,7 +217,7 @@ paths: - ou /ous/{ouid}/groups: get: - description: Get all group of labs defined in an `OU` object. + description: Get all group of labs defined in an `OU` object parameters: - $ref: "#/parameters/ouParam" responses: @@ -258,7 +257,7 @@ paths: - ou /ous/{ouid}/labs: get: - description: Get all `lab` objects defined in an `OU`. + description: Get all `lab` objects defined in an `OU` parameters: - $ref: "#/parameters/ouParam" responses: @@ -301,7 +300,7 @@ paths: - lab /ous/{ouid}/labs/{labid}: get: - description: Get a `lab` object. + description: Get a `lab` object parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -357,7 +356,7 @@ paths: description: Proxy server URL type: string mcastmode: - description: Multicast protocol mode (full-duplex, half-duplex). + description: Multicast protocol mode (full-duplex, half-duplex) type: string enum: [ "full-duplex", "half-duplex" ] default: "full-duplex" @@ -373,7 +372,7 @@ paths: type: integer format: int32 p2pmode: - description: Bittorrent connection type ("peer", "leecher". "seeder"). + description: Bittorrent connection type ("peer", "leecher". "seeder") type: string p2ptime: description: Bittorrent connection extra time (in s.) @@ -390,7 +389,7 @@ paths: - lab /ous/{ouid}/labs/{labid}/clients: get: - description: Get all `client` objects defined in an `lab`. + description: Get all `client` objects defined in a `lab` parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -426,7 +425,7 @@ paths: - client /ous/{ouid}/labs/{labid}/clients/{clientid}: get: - description: Get a `client` object. + description: Get a `client` object parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -451,7 +450,7 @@ paths: description: main network interface type: string netdriver: - description: client MAC address (kernel module) + description: network interface driver (kernel module) type: string mac: description: client MAC address @@ -472,6 +471,9 @@ paths: id: type: integer format: int32 + profclient: + description: check if this client is used to teach (professor cleint) + type: boolean validation: description: boot validation flag type: boolean @@ -481,7 +483,7 @@ paths: picture: description: client's picture file type: string - required: [ id, name, serialno, netiface, netdriver, mac, ip, netmask, routerip, repo, validation, picture ] + required: [ id, name, serialno, netiface, netdriver, mac, ip, netmask, routerip, repo, profclient, validation, picture ] security: - apikey: [] tags: @@ -489,7 +491,7 @@ paths: - client /ous/{ouid}/labs/{labid}/clients/{clientid}/hardware: get: - description: Get the hardware definition of a `client` object. + description: Get the hardware definition of a `client` object parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -528,7 +530,7 @@ paths: - client /ous/{ouid}/labs/{labid}/clients/{clientid}/diskcfg: get: - description: Get disks configuration of a `client` + description: Get disk configuration of a `client` parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -550,7 +552,7 @@ paths: description: | array of disk configuration data, including general disk information and partition/filesystem information (if not specified in paratmeter - description, it is only valid in partition configuration). + description, it is only valid in partition configuration) type: array items: type: object @@ -625,7 +627,7 @@ paths: - client /ous/{ouid}/labs/{labid}/clients/{clientid}/events: post: - description: Store UDS server URLs to resend some events recieved from OGAgent. + description: Store UDS server URLs to resend some events recieved from OGAgent parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -638,10 +640,10 @@ paths: type: object properties: urlLogin: - description: URL to resend a login event. + description: URL to resend a login event type: string urlLogout: - description: URL to resend a logout event. + description: URL to resend a logout event type: string required: [ urlLogin, urlLogout ] responses: @@ -662,7 +664,7 @@ paths: - remotepc /ous/{ouid}/labs/{labid}/clients/{clientid}/session: post: - description: Record session data for a client. + description: Record session data for a client parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -691,7 +693,7 @@ paths: - remotepc /ous/{ouid}/labs/{labid}/clients/{clientid}/unreserve: delete: - description: Unreserve a client, clear its session data and send a poweroff operation. + description: Unreserve a client, clear its session data and send a poweroff operation parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/labParam" @@ -707,7 +709,7 @@ paths: - remotepc /ous/{ouid}/repos: get: - description: Get all `repo` objects defined in an `OU`. + description: Get all `repo` objects defined in an `OU` parameters: - $ref: "#/parameters/ouParam" responses: @@ -737,7 +739,7 @@ paths: - repo /ous/{ouid}/repos/{repoid}: get: - description: Get a `repo` object. + description: Get a `repo` object parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/repoParam" @@ -768,7 +770,7 @@ paths: - repo /ous/{ouid}/images: get: - description: Get all `image` objects defined in an `OU`. + description: Get all `image` objects defined in an `OU` parameters: - $ref: "#/parameters/ouParam" responses: @@ -800,7 +802,7 @@ paths: - image /ous/{ouid}/images/{imageid}: get: - description: Get an `image` object. + description: Get an `image` object parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/imageParam" @@ -846,7 +848,7 @@ paths: type: object properties: id: - description: model client's id. + description: model client's id type: integer format: int32 disk: @@ -914,8 +916,8 @@ paths: /ous/{ouid}/images/{imageid}/reserve: post: description: | - Reserve a client with an installed image and send a boot/reboot operation. - If `labid` is specified, then choose a `client` defined in this lab. + Reserve a client with an installed image and send a boot/reboot operation + (if `labid` is specified, then choose a `client` defined in this lab) parameters: - $ref: "#/parameters/ouParam" - $ref: "#/parameters/imageParam" @@ -931,14 +933,14 @@ paths: format: int32 minimum: 1 maxtime: - description: maximum reservation time, in h. (optional, 24 h. by default) + description: maximum reservation time, in hours (optional, 24 h. by default) type: integer format: int32 minimum: 1 default: 24 responses: "200": - description: Reserve a client to boot using an operating system image. + description: Reserve a client to boot using an operating system image schema: $ref: "#/definitions/SelectedClientModel" security: @@ -965,7 +967,7 @@ paths: items: $ref: "#/definitions/ImageModel" ous: - description: OUs defined + description: defined OUs type: array items: type: object @@ -1027,7 +1029,7 @@ paths: - image /repository/poweron: post: - description: send Wake-On-Lan notification to many clients + description: Send Wake-On-Lan notification to many clients parameters: - in: body name: data @@ -1056,7 +1058,7 @@ paths: - client /ogagent/started: post: - description: Process push notification when OGAgent is started + description: Notification when OGAgent is started parameters: - in: body name: data @@ -1085,7 +1087,7 @@ paths: - agent /ogagent/stopped: post: - description: Process push notification when OGAgent is stopped + description: Notification when OGAgent is stopped parameters: - in: body name: data @@ -1112,7 +1114,7 @@ paths: - agent /ogagent/loggedin: post: - description: Process push notification when an user logged in + description: Notification when an user logs in parameters: - in: body name: data @@ -1141,7 +1143,7 @@ paths: - agent /ogagent/loggedout: post: - description: Process push notification when an user is logged in + description: Notification when an user logs out parameters: - in: body name: data @@ -1173,14 +1175,14 @@ parameters: labParam: name: labid in: path - description: Lab identificator + description: lab identificator required: true type: integer minimum: 1 clientParam: name: clientid in: path - description: Client identificator + description: client identificator required: true type: integer minimum: 1 diff --git a/admin/WebConsole/rest/remotepc.php b/admin/WebConsole/rest/remotepc.php index a0d4ea10..c6dcda51 100644 --- a/admin/WebConsole/rest/remotepc.php +++ b/admin/WebConsole/rest/remotepc.php @@ -82,11 +82,10 @@ $app->post('/ous/:ouid/images/:imageid/reserve(/)', 'validateApiKey', writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: labid=$labid, maxtime=$maxtime"); // Choose older not-reserved client with image installed and get ogAdmServer data. $cmd->texto = <<<EOD -SELECT adm.idusuario, entornos.ipserveradm, entornos.portserveradm, - ordenadores.idordenador, ordenadores.nombreordenador, ordenadores.ip, +SELECT adm.idusuario, ordenadores.idordenador, ordenadores.nombreordenador, ordenadores.ip, ordenadores.mac, ordenadores.agentkey, par.numdisk, par.numpar, aulas.idaula, aulas.idcentro, repo.ip AS repoip, repo.apikey AS repokey - FROM entornos, ordenadores + FROM ordenadores JOIN aulas USING(idaula) RIGHT JOIN administradores_centros AS adm USING(idcentro) RIGHT JOIN usuarios USING(idusuario) @@ -107,8 +106,6 @@ EOD; $rs->Primero(); if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) { // Read query data. - $serverip = $rs->campos["ipserveradm"]; - $serverport = $rs->campos["portserveradm"]; $clntid = $rs->campos["idordenador"]; $clntname = $rs->campos["nombreordenador"]; $clntip = $rs->campos["ip"]; @@ -126,22 +123,17 @@ EOD; writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent status, url=".$ogagent[$clntip]['url']."."); $result = multiRequest($ogagent); if (empty($result[$clntip]['data'])) { - // Client is off, send a boot command to ogAdmServer. + // Client is off, send WOL command to ogAdmServer. // TODO: if client is busy????? - $reqframe = "nfn=Arrancar\r". - "ido=$clntid\r". - "iph=$clntip\r". - "mac=$clntmac\r". - "mar=1\r"; if ($app->settings['debug']) - writeRemotepcLog($app->request()->getResourceUri(). "Send Boot command to ogAdmClient, ido=$clntid,iph=$clntip,mac=$clntmac."); - sendCommand($serverip, $serverport, $reqframe, $values); + writeRemotepcLog($app->request()->getResourceUri(). ": Send boot command through ogAdmServer: iph=$clntip,mac=$clntmac."); + wol(1, [$clntmac], [$clntip]); // Send WOL command to client repository. $repo[$repoip]['url'] = "https://$repoip/opengnsys/rest/repository/poweron"; $repo[$repoip]['header'] = Array("Authorization: ".$repokey); $repo[$repoip]['post'] = '{"macs": ["'.$clntmac.'"], "ips": ["'.$clntip.'"]}'; if ($app->settings['debug']) - writeRemotepcLog($app->request()->getResourceUri(). "Send Boot command to repo: repo=$repoip, ip=$clntip,mac=$clntmac."); + writeRemotepcLog($app->request()->getResourceUri(). ": Send Boot command through repo: repo=$repoip, ip=$clntip,mac=$clntmac."); $result = multiRequest($repo); // ... (check response) //if ($result[$repoip]['code'] != 200) { @@ -220,14 +212,9 @@ EOD; if ($app->settings['debug']) writeRemotepcLog($app->request()->getResourceUri(). ": DB tables and events updated, clntid=$clntid."); // Send init session command if client is booted on ogLive. - $reqframe = "nfn=IniciarSesion\r". - "ido=$clntid\r". - "iph=$clntip\r". - "dsk=$disk\r". - "par=$part\r"; if ($app->settings['debug']) writeRemotepcLog($app->request()->getResourceUri(). ": Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part."); - sendCommand($serverip, $serverport, $reqframe, $values); + session($clntip, "$disk\r$part"); // Compose JSON response. $response['id'] = (int)$clntid; $response['name'] = $clntname; @@ -514,8 +501,8 @@ EOD; // Read query data. $clntip = $rs->campos["ip"]; $agentkey = $rs->campos["agentkey"]; - // DB Transaction: set reservation time to the past and - // remove pending boot commands from client's and agent's queues. + // DB Transaction: set reservation time to the past, remove pending + // boot commands from client's and agent's queues, and drop its event. if ($app->settings['debug']) writeRemotepcLog($app->request()->getResourceUri(). ": Updating database."); $cmd->texto = "START TRANSACTION;"; @@ -537,6 +524,8 @@ DELETE FROM ogagent_queue WHERE clientid = '$clntid' AND command IN ('popup-10', 'popup-5', 'poweroff'); EOD; $cmd->Ejecutar(); + $cmd->texto = "DROP EVENT IF EXISTS e_timeout_$clntid;"; + $cmd->Ejecutar(); $cmd->texto = "COMMIT;"; $cmd->Ejecutar(); // Send a poweroff command to client's OGAgent. diff --git a/admin/WebConsole/rest/repository.php b/admin/WebConsole/rest/repository.php index 736cc1c2..7a32b388 100644 --- a/admin/WebConsole/rest/repository.php +++ b/admin/WebConsole/rest/repository.php @@ -6,18 +6,18 @@ * @note Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx. * @license GNU GPLv3+ * @author Juan Manuel Bardallo SIC Universidad de Huelva - * @version 1.0 + * @version 1.1.0 * @date 2016-04-06 */ -// Auxiliar functions. +// Auxiliary functions. /** * @brief Validate API key included in "Authorization" HTTP header. * @return JSON response on error. */ function validateRepositoryApiKey() { - $response = array(); + $response = []; $app = \Slim\Slim::getInstance(); // Assign user id. that match this key to global variable. @@ -55,18 +55,17 @@ function commandExist($cmd) { } -// Define REST routes. +// REST routes. /** * @brief List all images in the repository * @note Route: /repository/images, Method: GET - * @param no - * @return JSON object with directory, images array, ous array and disk data. + * @return string JSON object with directory, images array, ous array and disk data. */ $app->get('/repository/images(/)', 'validateRepositoryApiKey', function() use ($app) { - $response = array(); + $response = []; // Read repository information file. $cfgFile = '/opt/opengnsys/etc/repoinfo.json'; $response = json_decode(@file_get_contents($cfgFile), true); @@ -123,13 +122,12 @@ $app->get('/repository/images(/)', 'validateRepositoryApiKey', /** * @brief List image data * @note Route: /repository/image/:imagename, Method: GET - * @param no - * @return JSON object with image data. + * @return string JSON object with image data. */ $app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey', function($ouname="/", $imagename) use ($app) { - $images = array(); - $response = array(); + $images = []; + $response = []; // Search image name in repository information file. $cfgFile = '/opt/opengnsys/etc/repoinfo.json'; $json = json_decode(@file_get_contents($cfgFile), true); @@ -180,11 +178,12 @@ $app->get('/repository/image(/:ouname)/:imagename(/)', 'validateRepositoryApiKey /** * @brief Power on a pc or group of pcs with the MAC specified in POST parameters * @note Route: /poweron, Method: POST - * @param macs OU id. - * @return JSON string ok if the power on command was sent + * @param array Array of MAC addresses + * @return string JSON string ok if the power on command was sent */ $app->post('/repository/poweron', 'validateRepositoryApiKey', function() use($app) { + $response = []; // The macs parameter must come in the post (JSON object with array of MACs) $data = json_decode($app->request()->getBody()); if (empty($data->macs)) { @@ -195,6 +194,9 @@ $app->post('/repository/poweron', 'validateRepositoryApiKey', // Execute local wakeonlan command (may be installed) if(commandExist("wakeonlan")) { $strMacs = trim(implode(' ', $data->macs)); + if(stristr($strMacs, ':') === false) { + $strMacs = implode(':', str_split($strMacs, 2)); + } $response["output"] = "Executing wakeonlan ".$strMacs."\n"; $response["output"] .= shell_exec("wakeonlan ".$strMacs); jsonResponse(200, $response); diff --git a/admin/WebConsole/rest/server.php b/admin/WebConsole/rest/server.php index 93cef872..50ee5f67 100644 --- a/admin/WebConsole/rest/server.php +++ b/admin/WebConsole/rest/server.php @@ -67,22 +67,21 @@ function getStatus($ouid, $labid, $clntid=0) { global $cmd; global $LONCABECERA; global $LONHEXPRM; + $app = \Slim\Slim::getInstance(); $response = []; $id = []; $stat = []; $ip = ""; - - $app = \Slim\Slim::getInstance(); - $urls = Array(); + $urls = []; // Status mapping. - $status = Array('OFF'=>"off", - 'INI'=>"initializing", - 'OPG'=>"oglive", - 'BSY'=>"busy", - 'LNX'=>"linux", - 'OSX'=>"macos", - 'WIN'=>"windows", - 'UNK'=>"unknown"); + $status = ['OFF'=>"off", + 'INI'=>"initializing", + 'OPG'=>"oglive", + 'BSY'=>"busy", + 'LNX'=>"linux", + 'OSX'=>"macos", + 'WIN'=>"windows", + 'UNK'=>"unknown"]; // Parameters. $ouid = htmlspecialchars($ouid); $labid = htmlspecialchars($labid); @@ -90,9 +89,8 @@ function getStatus($ouid, $labid, $clntid=0) { // Database query. $cmd->texto = <<<EOD -SELECT adm.idusuario, entornos.ipserveradm, entornos.portserveradm, - aulas.idaula, ordenadores.idordenador, ordenadores.ip - FROM entornos, ordenadores +SELECT adm.idusuario, aulas.idaula, ordenadores.idordenador, ordenadores.ip + FROM ordenadores JOIN aulas USING(idaula) RIGHT JOIN administradores_centros AS adm USING(idcentro) WHERE adm.idusuario = '$userid' @@ -112,100 +110,72 @@ EOD; $rs->Primero(); // Check if user is an UO admin and asset exists. if (checkAdmin($rs->campos["idusuario"]) and (($single and checkParameter($rs->campos["idordenador"])) or (! $single and checkParameter($rs->campos["idaula"])))) { - // First, try to connect to ogAdmCleint service. - $serverip = $rs->campos["ipserveradm"]; - $serverport = $rs->campos["portserveradm"]; while (!$rs->EOF) { $id[$rs->campos["ip"]] = $rs->campos["idordenador"]; $stat[$rs->campos["ip"]] = $status['OFF']; $rs->Siguiente(); } - // Connect to reset client's status. + // Get client status. $clientid = implode(",", $id); $clientip = implode(";", array_keys($id)); - $reqframe = "nfn=Sondeo\r". - "ido=$clientid\r". - "iph=$clientip\r"; - $result = sendCommand($serverip, $serverport, $reqframe, $values); - // Connect to fetch client's status. - // Asuming client is off by default. - $values["tso"]="OFF"; - // Iterate to check client's status. - // Exit if status!=OFF or end iterations (status=OFF). - $maxIter = 30; - for ($i=1; $i<$maxIter and preg_match('/OFF/', $values["tso"]); $i++) { - // Connect to check status. - $reqframe = "nfn=respuestaSondeo\r". - "ido=$clientid\r". - "iph=$clientip\r"; - $result = sendCommand($serverip, $serverport, $reqframe, $values); - // Wait until next checking (0.1 ms). - usleep(100000); - } - // Parse status response. - if ($result) { - // Check status type. - if (checkParameter($values["tso"])) { - foreach (explode(";", $values["tso"]) as $data) { - if (!empty($data)) { - list($clip, $clst) = explode("/", $data); - if ($clst != "OFF") { - // Update current status. - $stat[$clip] = $status[$clst]; - } + $result = clients(2, $clientip); + // Check status type. + if (checkParameter($result)) { + foreach (explode(";", $result) as $data) { + if (!empty($data)) { + list($clip, $clst) = explode("/", $data); + if ($clst != "OFF") { + // Update current status. + $stat[$clip] = $status[$clst]; } } } - // Prepare request to new OGAgent for OSes. - foreach ($stat as $ip => $st) { - if ($st == "off") { - $urls[$ip] = "https://$ip:8000/opengnsys/status"; - } - } - // Send request to OGAgents. - if (isset($urls)) { - $result = multiRequest($urls); - } - // Parse responses. - reset($urls); - foreach ($result as $res) { - if (!empty($res['data'])) { - // Get status and session data. - $ip = key($urls); - $data = json_decode($res['data']); - if (@isset($status[$data->status])) { - $stat[$ip] = $status[$data->status]; - $logged[$ip] = $data->loggedin; - } else { - $stat[$ip] = $status['UNK']; - } - } - unset($urls[$ip]); + } + // Prepare request to new OGAgent for OSes. + foreach ($stat as $ip => $st) { + if ($st == "off") { + $urls[$ip] = "https://$ip:8000/opengnsys/status"; } - // Compose JSON response. - if ($single) { - // Single response. - $response['id'] = (int)reset($id); - $response['ip'] = key($id); - $response['status'] = $stat[$ip]; - empty($logged[$ip]) || $response['loggedin'] = $logged[$ip]; - } else { - // Multiple responses. - foreach ($stat as $ip => $st) { - $tmp = Array(); - $tmp['id'] = (int)$id[$ip]; - $tmp['ip'] = $ip; - $tmp['status'] = $stat[$ip]; - empty($logged[$ip]) || $tmp['loggedin'] = $logged[$ip]; - array_push($response, $tmp); + } + // Send request to OGAgents. + if (isset($urls)) { + $result = multiRequest($urls); + } + // Parse responses. + reset($urls); + foreach ($result as $res) { + if (!empty($res['data'])) { + // Get status and session data. + $ip = key($urls); + $data = json_decode($res['data']); + if (@isset($status[$data->status])) { + $stat[$ip] = $status[$data->status]; + $logged[$ip] = $data->loggedin; + } else { + $stat[$ip] = $status['UNK']; } } - jsonResponse(200, $response); + unset($urls[$ip]); + } + // Compose JSON response. + if ($single) { + // Single response. + $response['id'] = (int)reset($id); + $response['ip'] = key($id); + $response['status'] = $stat[key($id)]; + empty($logged[$ip]) || $response['loggedin'] = $logged[$ip]; } else { - // Access error. - $response['message'] = "Cannot access to OpenGnsys server"; - jsonResponse(500, $response); + // Multiple responses. + foreach ($stat as $ip => $st) { + $tmp = Array(); + $tmp['id'] = (int)$id[$ip]; + $tmp['ip'] = $ip; + $tmp['status'] = $stat[$ip]; + empty($logged[$ip]) || $tmp['loggedin'] = $logged[$ip]; + array_push($response, $tmp); + } } + jsonResponse(200, $response); } $rs->Cerrar(); } @@ -1039,7 +1009,7 @@ EOD; while (!$rs->EOF) { // Ignoring empty fields. if (!is_null($rs->campos["descripcion"])) { - array_push($response['software']['application'], $rs->campos["descripcion"]); + array_push($response['software']['applications'], $rs->campos["descripcion"]); } $rs->Siguiente(); } diff --git a/admin/WebConsole/varios/tareascomandos.php b/admin/WebConsole/varios/tareascomandos.php deleted file mode 100644 index 648502fa..00000000 --- a/admin/WebConsole/varios/tareascomandos.php +++ /dev/null @@ -1,216 +0,0 @@ -<?php -// ************************************************************************************************************************************************* -// Aplicación WEB: ogAdmWebCon -// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla -// Fecha Creación: Año 2009-2010 -// Fecha Última modificación: Agosto-2010 -// Nombre del fichero: tareascomandos.php -// Descripción : -// Administra los comandos que forman parte de una tarea -// ************************************************************************************************************************************************* -include_once("../includes/ctrlacc.php"); -include_once("../clases/AdoPhp.php"); -include_once("../includes/constantes.php"); -include_once("../includes/comunes.php"); -include_once("../includes/CreaComando.php"); -include_once("../includes/TomaDato.php"); -include_once("../idiomas/php/".$idioma."/tareascomandos_".$idioma.".php"); -//________________________________________________________________________________________________________ - -$idtarea=0; -$descripciontarea=""; -if (isset($_GET["idtarea"])) $idtarea=$_GET["idtarea"]; // Recoge parametros -if (isset($_GET["descripciontarea"])) $descripciontarea=$_GET["descripciontarea"]; // Recoge parametros - -$cmd=CreaComando($cadenaconexion); // Crea objeto comando -if (!$cmd) - Header('Location: '.$pagerror.'?herror=2'); // Error de conexión con servidor B.D. -//________________________________________________________________________________________________________ -?> -<HTML> -<HEAD> - <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> -<LINK rel="stylesheet" type="text/css" href="../estilos.css"> -<SCRIPT language="javascript" src="../jscripts/tareascomandos.js"></SCRIPT> -<SCRIPT language="javascript" src="../jscripts/opciones.js"></SCRIPT> -<SCRIPT language="javascript" src="../clases/jscripts/HttpLib.js"></SCRIPT> -<?php echo '<SCRIPT language="javascript" src="../idiomas/javascripts/'.$idioma.'/tareascomandos_'.$idioma.'.js"></SCRIPT>'?> -</HEAD> -<BODY> -<FORM name="fdatos"> - <INPUT type=hidden value="<?php echo $idcentro?>" id=idcentro> - <P align=center class=cabeceras><IMG src="../images/iconos/tareas.gif"> <?php echo $TbMsg[0]?><BR> - <SPAN align=center class=subcabeceras><?php echo $TbMsg[1]?></SPAN> <IMG src="../images/iconos/comandos.gif"><BR><BR> - <SPAN align=center class=presentaciones><B><?php echo $TbMsg[2]?>: </B><?php echo $descripciontarea?></SPAN></P> - <DIV align=center id="Layer_componentes"> - <TABLE class="tabla_listados" cellspacing=1 cellpadding=0 id="TABLACOMANDOS"> - <TR height=20> - <TH><IMG src="../images/iconos/eliminar.gif"></TH> - <TH align=left> <?php echo $TbMsg[3]?></TH> - <TH><?php echo $TbMsg[4]?></TH> - <TH>A</TH> - </TR> - <?php - $rs=new Recordset; - $cmd->texto='SELECT tareas_acciones.*, comandos.descripcion,comandos.visuparametros - FROM tareas_acciones - INNER JOIN procedimientos ON tareas_acciones.idprocedimiento = procedimientos.idprocedimiento - INNER JOIN procedimientos_acciones ON procedimientos.idprocedimiento = procedimientos_acciones.idprocedimiento - INNER JOIN comandos ON procedimientos_acciones.idcomando = comandos.idcomando - WHERE tareas_acciones.idtarea='.$idtarea.' ORDER BY tareas_acciones.orden'; - $rs->Comando=&$cmd; - if ($rs->Abrir()){ - $rs->Primero(); - $tabla_parametros=""; // Tabla para localizar parametros - $cont_parametros=0; // Contador de la tabla - CreaTablaParametros($cmd); // Crea tabla especificaciones de parametros - while (!$rs->EOF){ - echo '<TR id=TR-'.$rs->campos["idtareacomando"].'>'; - echo '<TD align=center ><INPUT id=checkbox-'.$rs->campos["idtareacomando"].' type=checkbox - onclick="gestion_comandos('.$rs->campos["idtareacomando"].',this)" checked ></INPUT></TD>'; - // Descripcion de la comando - echo '<TD> '.$rs->campos["descripcion"].'</TD>'; - // Orden del item del item - echo '<TD align=center > <INPUT class="formulariodatos" id=orden-'.$rs->campos["idtareacomando"].' - style="WIDTH:20px" type=text value="'.$rs->campos["orden"].'"></INPUT></TD>'; - echo '<TD width="10%" align=center id="imgact-'.$rs->campos["idtareacomando"].'"> - <IMG src="../images/iconos/actualizar.gif" style="cursor:hand" onclick="ActualizarAccion('.$rs->campos["idtareacomando"].')"></TD>'; - echo '</TR>'; - pintacomandos($cmd,$rs); - echo '<TR height=3><TD style="BACKGROUND-COLOR: #999999;" colspan=5></TD></TR>'.chr(13); - $rs->Siguiente(); - } - } - $rs->Cerrar(); - ?> - </TABLE> - </DIV> - <DIV id="Layer_nota" align=center> - <br> - <span align=left class=notas><I><?php echo $TbMsg[7]?>.</I></span> - </DIV> -</FORM> -</BODY> -</HTML> -<?php -// ************************************************************************************************************************************************* -function pintacomandos($cmd,$rs){ - global $TbMsg; - global $AMBITO_CENTROS; - global $AMBITO_GRUPOSAULAS; - global $AMBITO_AULAS; - global $AMBITO_GRUPOSORDENADORES; - global $AMBITO_ORDENADORES; - global $tabla_parametros; - global $cont_parametros; - - $HTMLparametros='<TR id="PAR-'.$rs->campos["idtareacomando"].'">'.chr(13); - $HTMLparametros.= '<TD> </TD>'.chr(13); - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #D4D4D4; " >'.$TbMsg[5].'</TH>'.chr(13); - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #D4D4D4;" >'.$TbMsg[6].'</TH>'.chr(13); - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #D4D4D4;" > </TH>'.chr(13); - $HTMLparametros.= '</TR>'.chr(13); - - $textambito=""; - $urlimg=""; - $nombre=""; - switch($rs->campos["ambito"]){ - case $AMBITO_CENTROS : - $urlimg='../images/iconos/centros.gif'; - $textambito="Center"; - $nombre=TomaDato($cmd,0,'centros',$rs->campos["idambito"],'idcentro','nombrecentro'); - break; - case $AMBITO_GRUPOSAULAS : - $urlimg='../images/iconos/carpeta.gif'; - $textambito="Group of labs"; - $nombre=TomaDato($cmd,0,'grupos',$rs->campos["idambito"],'idgrupo','nombregrupo'); - break; - case $AMBITO_AULAS : - $urlimg='../images/iconos/aula.gif'; - $textambito="Labs"; - $nombre=TomaDato($cmd,0,'aulas',$rs->campos["idambito"],'idaula','nombreaula'); - break; - case $AMBITO_GRUPOSORDENADORES : - $urlimg='../images/iconos/carpeta.gif'; - $textambito="Group of computers"; - $nombre=TomaDato($cmd,0,'gruposordenadores',$rs->campos["idambito"],'idgrupo','nombregrupoordenador'); - break; - case $AMBITO_ORDENADORES : - $urlimg='../images/iconos/ordenador.gif'; - $textambito="Computers"; - $nombre=TomaDato($cmd,0,'ordenadores',$rs->campos["idambito"],'idordenador','nombreordenador'); - break; - } - $HTMLparametros.='<TR id="PAR-'.$rs->campos["idtareacomando"].'">'.chr(13); - $HTMLparametros.= '<TD> </TD>'.chr(13); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$TbMsg[8].' </TD>'.chr(13); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$textambito.' '; - $HTMLparametros.= '<IMG src="'.$urlimg.'"> </TD>'.chr(13); - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #b5daad;" > </TH>'.chr(13); - $HTMLparametros.= '</TR>'; - - $HTMLparametros.='<TR id="PAR-'.$rs->campos["idtareacomando"].'">'.chr(13); - $HTMLparametros.= '<TD> </TD>'.chr(13); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$TbMsg[9].' </TD>'.chr(13); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$nombre.' </TD>'.chr(13); - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #b5daad;" > </TH>'.chr(13); - $HTMLparametros.= '</TR>'; - - $auxVP=explode(";",$rs->campos["visuparametros"]); // Parametros visualizables - $auxP=explode(chr(13),$rs->campos["parametros"]); // Recorre parametros para visualizar los que así sean - for ($i=0;$i<sizeof($auxP);$i++){ - $dualparam=explode("=",$auxP[$i]); - for ($k=0;$k<sizeof($auxVP);$k++){ - if($auxVP[$k]==$dualparam[0]){ - $posp=busca_indicebinariodual($dualparam[0],$tabla_parametros,$cont_parametros); // Busca datos del parámetro en la tabla cargada previamentre con todos los parámetros - if ($posp>=0){ - $auxtabla_parametros=$tabla_parametros[$posp][1]; - $HTMLparametros.='<TR id="PAR-'.$rs->campos["idtareacomando"].'">'.chr(13); - $HTMLparametros.= '<TD> </TD>'.chr(13); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$auxtabla_parametros["descripcion"].' </TD>'.chr(13); - if($auxtabla_parametros["tipopa"]==1){ - $valor=TomaDato($cmd,0,$auxtabla_parametros["nomtabla"],$dualparam[1],$auxtabla_parametros["nomidentificador"],$auxtabla_parametros["nomliteral"]); - }else - $valor=$dualparam[1]; - if($dualparam[0]!="iph") - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$valor.' </TD>'.chr(13); - else{ - $tablaipes=PintaOrdenadores($cmd,$valor); - $HTMLparametros.= '<TD style="BACKGROUND-COLOR: #b5daad;"> '.$tablaipes.' </TD>'.chr(13); - } - $HTMLparametros.= '<TH style="FONT-WEIGHT: 700;COLOR: #000000;BACKGROUND-COLOR: #b5daad;" > </TH>'.chr(13); - $HTMLparametros.= '</TR>'.chr(13); - } - } - } - } - echo $HTMLparametros; -} -//________________________________________________________________________________________________________ -function PintaOrdenadores($cmd,$cadenaip){ - $auxP=explode(";",$cadenaip); - if(sizeof($auxP)<1) return(""); - $clauslaIN="'".$auxP[0]."'"; - for ($i=1;$i<sizeof($auxP);$i++) - $clauslaIN.=",'".$auxP[$i]."'"; - $rs=new Recordset; - $contor=0; - $maxord=7; // Máximos ordenadores por linea - $cmd->texto=" SELECT nombreordenador,ip FROM ordenadores INNER JOIN aulas ON aulas.idaula=ordenadores.idaula WHERE ip IN(".$clauslaIN.") ORDER by nombreaula,nombreordenador"; - $rs->Comando=&$cmd; - if (!$rs->Abrir()) return(""); // Error al abrir recordset - $tablaHtml='<TABLE align=left border=0><TR>'; - while (!$rs->EOF){ - $contor++; - $tablaHtml.= '<TD align=center style="BACKGROUND-COLOR: #b5daad;FONT-FAMILY: Arial, Helvetica, sans-serif; BORDER-BOTTOM:#000000 none;FONT-SIZE: 8px"> - <IMG src="../images/iconos/ordenador.gif"><br><span style="FONT-SIZE:9px" >'.$rs->campos["nombreordenador"].'</TD>'; - if($contor>$maxord){ - $contor=0; - $tablaHtml.='</TR><TR>'; - } - $rs->Siguiente(); - } - $tablaHtml.='</TR>'; - $tablaHtml.= '</TR></TABLE>'; - return($tablaHtml); -} diff --git a/client/INSTALL b/client/INSTALL deleted file mode 100644 index e69de29b..00000000 --- a/client/INSTALL +++ /dev/null diff --git a/client/boot-tools/boottoolsfunctions.lib b/client/boot-tools/boottoolsfunctions.lib index 3ad38d15..972f0fe2 100755 --- a/client/boot-tools/boottoolsfunctions.lib +++ b/client/boot-tools/boottoolsfunctions.lib @@ -149,7 +149,7 @@ case "${1,,}" in exit 1 ;; esac -BRANCH="devel" +BRANCH="master" GITURL="https://api.github.com/repos/opengnsys/OpenGnsys/commits?sha=$BRANCH&path=/client" GITRELEASE=$(curl -s "$GITURL" | jq -r '"r" + (.[0].commit.committer.date | split("-") | join("")[:8]) + "." + (.[0].sha[:7])') NAMEISOCLIENT="$VERSIONBOOTTOOLS-$OSCODENAME-$OSRELEASE-$OSARCH-$GITRELEASE" diff --git a/client/engine/Boot.lib b/client/engine/Boot.lib index 6808f094..7060fac9 100755 --- a/client/engine/Boot.lib +++ b/client/engine/Boot.lib @@ -784,7 +784,7 @@ function ogGrubInstallMbr () # Variables locales. local PART DISK VERSION FIRSTAGE SECONSTAGE CHECKOS KERNELPARAM BACKUPNAME -local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB +local EFIDISK EFIPART EFISECONDSTAGE EFISUBDIR EFIOPTGRUB GRUBENTRY NEWORDER # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -890,9 +890,15 @@ EVAL=$? if ogIsEfiActive; then mv ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI/BOOT/* ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI - cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot + cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi # Nombre OpenGnsys para cargador - cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{shimx64.efi.signed,ogloader.efi} + cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi} + + # Creamos entrada NVRAM y la ponemos en segundo lugar + ogNvramAddEntry grub /EFI/grub/Boot/shimx64.efi + GRUBENTRY=$(ogNvramList| awk '{if ($2=="grub") print $1}') + NEWORDER="$(ogNvramGetOrder|awk -v ENTRY=$GRUBENTRY '{gsub(",", " "); printf "%x %x %s\n", $1 , ENTRY , substr($0, index($0,$2))}')" + ogNvramSetOrder $NEWORDER fi return $EVAL @@ -1028,7 +1034,7 @@ if ogIsEfiActive; then rm -rf ${EFISECONDSTAGE}/EFI/$EFISUBDIR/EFI cp /usr/lib/shim/shimx64.efi.signed ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/shimx64.efi # Nombre OpenGnsys para cargador - cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{shimx64.efi,ogloader.efi} + cp ${EFISECONDSTAGE}/EFI/$EFISUBDIR/Boot/{grubx64.efi,ogloader.efi} fi return $EVAL @@ -1603,7 +1609,7 @@ function ogBurgInstallMbr () { # Variables locales. -local PART DISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG +local BINARYAVAILABLE PART DISK DEVICE MOUNTDISK FIRSTAGE SECONSTAGE PREFIXSECONDSTAGE CHECKOS KERNELPARAM BACKUPNAME FILECFG # Si se solicita, mostrar ayuda. if [ "$*" == "help" ]; then @@ -1616,34 +1622,46 @@ fi # Error si no se reciben 2 parametros. [ $# -ge 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?) +#Error si no tenemos el binario burg +BINARYAVAILABLE=$(burg-install -v &>/dev/null && echo "YES" ||echo "NO") +if [ "$BINARYAVAILABLE" == NO ]; then + if [ -e $OGLIB/burg/burg.tgz ]; then + cd / ; tar xzvf $OGLIB/burg/burg.tgz --strip 1 &>/dev/null + else + return $(ogRaiseError $OG_ERR_NOTEXEC "Binary burg not found"; echo $?) + fi +fi DISK=$1; PART=$2; CHECKOS=${3:-"FALSE"} KERNELPARAM=$4 BACKUPNAME=".backup.og" -#Error si no es linux. -ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg no soporta esta particion"; echo $?) - - -#La primera etapa del grub se fija en el primer disco duro +#Controlar disco no uefi +ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?) +#Controlar particionado tipo msdos +ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?) +#Controlar existencia de disco y particion +DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $? +MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $? +#Controlar particion segunda etapa del burg +ogCheckStringInGroup $(ogGetFsType $DISK $PART) "CACHE EXT4 EXT3 EXT2" || return $(ogRaiseError $OG_ERR_PARTITION "burg.cfg soporta solo particiones linux"; echo $?) +#Controlar acceso de escritura a la particion segunda etapa del burg +ogIsReadonly $DISK $PART && return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?) + +#Asigar la primera etapa del grub en el primer disco duro FIRSTSTAGE=$(ogDiskToDev 1) - -#localizar disco segunda etapa del grub +#Localizar disco segunda etapa del grub SECONDSTAGE=$(ogMount $DISK $PART) -# prepara el directorio principal de la segunda etapa (y copia los binarios) -[ -d ${SECONDSTAGE}/boot/burg/ ] || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; #*/ ## (comentario Dogygen) #*/ ## (comentario Dogygen) - -#Copiamos el tema +#Preparar el directorio principal de la segunda etapa (y copia los binarios) +[ -d ${SECONDSTAGE}/boot/burg/ ] || mkdir -p ${SECONDSTAGE}/boot/burg/; cp -prv /boot/burg/* ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; cp -prv $OGLIB/burg/themes ${SECONDSTAGE}/boot/burg/ 2>&1>/dev/null; #*/ ## (comentario Dogygen) #*/ ## (comentario Dogygen) +#Copiar el tema de opengnsys mkdir -p ${SECONDSTAGE}/boot/burg/themes/OpenGnsys cp -prv "$OGLIB/burg/themes" "${SECONDSTAGE}/boot/burg/" 2>&1>/dev/null -#Localizar directorio segunda etapa del grub -#PREFIXSECONDSTAGE="/boot/burg/" - -# Si Reconfigurar segunda etapa (grub.cfg) == FALSE -if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ] +# No configurar la segunda etapa (grub.cfg). Parámetro FALSE +if [ -f ${SECONDSTAGE}/boot/burg/burg.cfg -o -f ${SECONDSTAGE}/boot/burg/burg.cfg$BACKUPNAME ]; then if [ "$CHECKOS" == "false" -o "$CHECKOS" == "FALSE" ] then @@ -1652,24 +1670,19 @@ then fi fi -# SI Reconfigurar segunda etapa (burg.cfg) == TRUE +# Configurrar la segunda etapa (burg.cfg) == tercer parámetro TRUE -#llamada a updateBootCache para que aloje la primera fase del ogLive +#llamar a updateBootCache para que aloje la primera fase del ogLive updateBootCache #Configur la sintaxis grub para evitar menus de "recovery" en el OGLive echo "GRUB_DISABLE_RECOVERY=\"true\"" >> /etc/default/grub echo "GRUB_DISABLE_LINUX_UUID=\"true\"" >> /etc/default/grub - #Preparar configuración segunda etapa: crear ubicacion mkdir -p ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/ - #Preparar configuración segunda etapa: crear cabecera del fichero -#/etc/burg.d/00_header > ${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg - FILECFG=${SECONDSTAGE}${PREFIXSECONDSTAGE}/boot/burg/burg.cfg - #/* ## (comentario Dogygen) cat > "$FILECFG" << EOF @@ -1757,7 +1770,6 @@ EOF #Preparar configuración segunda etapa: crear entrada del sistema operativo grubSyntax "$KERNELPARAM" >> "$FILECFG" - #Instalar el burg burg-install --force --root-directory=${SECONDSTAGE} $FIRSTSTAGE 2>&1>/dev/null } @@ -2776,19 +2788,96 @@ else [ -f $DIR/Boot/grubx64.efi ] && echo " icon /EFI/refind/icons/os_linux.png" >> $CFGFILE echo "}" >> $CFGFILE done - # Configuración ogLive - # Comantamos temporalmente: Con la versión nueva de refind falla - #if [ "$OGLIVE" != "" ]; then - # echo "menuentry \"OpenGnsys Live\" {" >> $CFGFILE - # echo " volume CACHE" >> $CFGFILE - # echo " ostype Linux" >> $CFGFILE - # echo " loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE - # echo " initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE - # echo " options \"$CMDLINE\"" >> $CFGFILE - # echo "}" >> $CFGFILE - - # # Ponemos ogLive como la entrada por defecto - # sed -i '1 i\default_selection "OpenGnsys Live"' $CFGFILE - #fi + # Configuración ogLive si secureboot no está activado + if ! dmesg|grep secureboot.*enabled &>/dev/null; then + if [ "$OGLIVE" != "" ]; then + echo "menuentry \"OpenGnsys Live\" {" >> $CFGFILE + echo " volume CACHE" >> $CFGFILE + echo " ostype Linux" >> $CFGFILE + echo " loader /boot/$(basename ${OGLIVE%/*})/ogvmlinuz" >> $CFGFILE + echo " initrd /boot/$(basename ${OGLIVE%/*})/oginitrd.img" >> $CFGFILE + echo " options \"$CMDLINE\"" >> $CFGFILE + echo "}" >> $CFGFILE + + # Ponemos ogLive como la entrada por defecto + sed -i '1 i\default_selection "OpenGnsys Live"' $CFGFILE + fi + fi fi } + +#/** +# ogGrub4dosInstallMbr int_ndisk +#@brief Genera un nuevo Codigo de arranque en el MBR del disco indicado, compatible con los SO tipo Windows, Linux. +#@param int_ndisk nº de orden del disco +#@param int_ndisk nº de orden del particion +#@return +#@exception OG_ERR_FORMAT Formato incorrecto. +#@exception OG_ERR_NOTFOUND Tipo de partición desconocido o no se puede montar. +#@exception OG_ERR_NOTBIOS Equipo no firmware BIOS legacy +#@exception OG_ERR_NOMSDOS Disco duro no particioniado en modo msdos +#@exception OG_ERR_NOTWRITE Particion no modificable. +#@version 1.1.1 - Adaptacion a OpenGnSys. +#@author Alberto GarcÃa Padilla / Antonio J. Doblas Viso. Universidad de Malaga +#@date 2009-10-17 +#*/ ## + +function ogGrub4dosInstallMbr () +{ +# Variables locales. +local DISK PART DEVICE MOUNTDISK GRUBDISK BINBDIR + +# Si se solicita, mostrar ayuda. +if [ "$*" == "help" ]; then + ogHelp "$FUNCNAME" "$FUNCNAME int_ndisk int_part " \ + "$FUNCNAME 1 1 " + return +fi +# Error si no se recibe 2 parámetros. +[ $# == 2 ] || return $(ogRaiseError $OG_ERR_FORMAT; echo $?) + +DISK="$1" +PART="$2" + +#Controlar existencia de disco y particion +DEVICE=$(ogDiskToDev $DISK) || ogRaiseError $OG_ERR_NOTFOUND || return $? +MOUNTDISK=$(ogMount $DISK $PART) || ogRaiseError $OG_ERR_PARTITION "$MSG_ERROR " || return $? +#Controlar acceso de escritura a la particion +ogIsReadonly $DISK $PART && return $(ogRaiseError $OG_ERR_NOTWRITE ": $DISK $PART" || echo $?) +#Controlar disco no uefi +ogIsEfiActive && return $(ogRaiseError $OG_ERR_NOTBIOS " : grub4dos solo soporta PC con bios legacy"; echo $?) +#Controlar particionado tipo msdos +ogCheckStringInGroup $(ogGetPartitionTableType $DISK) "MSDOS" || return $(ogRaiseError $OG_ERR_NOMSDOS ": grub2dos requiere particionado tipo MSDOS"; echo $?) +#Controlar la existencia del grub4dos con acceso a ntfs +BINDIR="${OGLIB}/grub4dos/grub4dos-0.4.6a" +[ -f ${BINDIR}/bootlace.com ] || ogRaiseError $OG_ERR_NOTFOUND ": ${BINDIR}/bootlace.com" || return $? + +#instalar el bootloader de grlrd en el MBR +${BINDIR}/bootlace64.com $DEVICE &>/dev/null +#copiar grld a la particion +cp ${BINDIR}/grldr $MOUNTDISK +#Instalar y configurar grub4dos +if [[ -f $MOUNTDISK/Boot/ ]]; then + GRUBDIR="$MOUNTDISK/Boot/grub/" +fi +if [[ -f $MOUNTDISK/Boot/grub/menu.lst ]]; then + rm $MOUNTDISK/Boot/grub/menu.lst + rmdir /$MOUNTDISK/Boot/grub +fi +if [[ ! -f $MOUNTDISK/Boot/grub/menu.lst ]]; then + mkdir -p /$MOUNTDISK/Boot/grub + touch /$MOUNTDISK/Boot/grub/menu.lst + + GRUBDISK=$[$1-1] + +cat << EOT >/$MOUNTDISK/Boot/grub/menu.lst +##NO-TOCAR-ESTA-LINEA MBR +timeout 0 +title MBR +root (hd$GRUBDISK,0) +chainloader (hd$GRUBDISK,0)+1 +boot +EOT + +fi +}
\ No newline at end of file diff --git a/client/engine/Inventory.lib b/client/engine/Inventory.lib index f3a779d7..92b46ef4 100755 --- a/client/engine/Inventory.lib +++ b/client/engine/Inventory.lib @@ -109,7 +109,8 @@ fi # Obtener nº de serie (ignorar los no especificados). SERIALNO=$(dmidecode -s system-serial-number | egrep -vi "(^[ 0]+$|not specified|to be filled|invalid entry|default string)") -# Truncar cadena si >25 caracteres. +# Quitar espacios y truncar cadena si >25 caracteres. +SERIALNO="${SERIALNO// /}" [ ${#SERIALNO} -gt 25 ] && SERIALNO="${SERIALNO:0:22}..." [ -n "$SERIALNO" ] && echo "$SERIALNO" return 0 diff --git a/client/engine/PostConf.lib b/client/engine/PostConf.lib index 08f4621f..eb5f6eb0 100755 --- a/client/engine/PostConf.lib +++ b/client/engine/PostConf.lib @@ -467,43 +467,6 @@ EOT #/** -# ogInstallLinuxClient int_ndisk int_filesys -#@brief Instala el cliente OpenGnSys para sistemas operativos GNU/Linux (obsoleta). -#@version 1.0.4 - Primera adaptación para OpenGnSys. -#@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2012-04-10 -#@version 1.0.5 - Evitar duplicidad de instalación del cliente. -#@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2014-03-06 -#@version 1.1.1 - Marked as obsolete. -#@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2019-09-25 -#*/ ## -function ogInstallLinuxClient () -{ -} - - -#/** -# ogInstallWindowsClient int_ndisk int_filesys str_filename -#@brief Instala el cliente OpenGnSys para sistemas operativos Windows (obsoleta). -#@version 1.0.4 - Primera adaptación para OpenGnSys. -#@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2012-04-11 -#@version 1.0.5 - Cambios en los parametros de entrada y funcionamiento de la funcion -#@author Jonathan Alonso Martinez - Universidad Autonoma de Barcelona -#@date 2013-02-12 -#@version 1.1.1 - Marked as obsolete. -#@author Ramon Gomez, ETSII Universidad de Sevilla -#@date 2019-09-25 -#*/ ## - -function ogInstallWindowsClient () -{ -} - - -#/** # ogUninstallLinuxClient int_ndisk int_filesys #@brief Desinstala el cliente OpenGnSys para sistemas operativos GNU/Linux. #@param int_ndisk nº de orden del disco diff --git a/client/engine/Protocol.lib b/client/engine/Protocol.lib index c58d262b..f54edc4f 100755 --- a/client/engine/Protocol.lib +++ b/client/engine/Protocol.lib @@ -399,7 +399,7 @@ fi ##### BEGIN SERVER SESSION ##### # 2º param check: controlamos el primer componente comun de las sesiones de servidor y cliente: PORTBASE PORTBASE=${SESSION[0]} -ogCheckStringInGroup ${SESSION[0]} "$(seq 9000 2 9100)" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || PERROR=3 #return $? +ogCheckStringInGroup ${SESSION[0]} "$(seq 9000 2 9098)" || ogRaiseError $OG_ERR_FORMAT "McastSession portbase ${SESSION[0]}" || PERROR=3 #return $? # 2º param check: Controlamos el resto de componenentes de la sesion del servidor. if [ $MODE == "server" ] then diff --git a/client/engine/Rsync.lib b/client/engine/Rsync.lib index a68ea382..2478956a 100755 --- a/client/engine/Rsync.lib +++ b/client/engine/Rsync.lib @@ -4,12 +4,13 @@ # rsync #@brief Función para utilizar la versión de rsync situada en $OPENGNSYS/bin en vez de la del sistema operativo. #@param los mismos que el comando rsync del sistema operativo. +#@warning Solo en clientes ogLive de 32 bits. #@return instrucción para ser ejecutada. #*/ function rsync () { local RSYNC -[ -x $OPENGNSYS/bin/rsync ] && RSYNC=$OPENGNSYS/bin/rsync +[ "$(arch)" == "i686" -a -x $OPENGNSYS/bin/rsync ] && RSYNC=$OPENGNSYS/bin/rsync RSYNC=${RSYNC:-$(which rsync)} $RSYNC "$@" diff --git a/client/engine/System.lib b/client/engine/System.lib index 77f77b48..261cacf3 100755 --- a/client/engine/System.lib +++ b/client/engine/System.lib @@ -227,6 +227,7 @@ case "$CODE" in $OG_ERR_IMGSIZEPARTITION) MSG="$MSG_ERR_IMGSIZEPARTITION \"$2\"" ;; $OG_ERR_UPDATECACHE) MSG="$MSG_ERR_UPDATECACHE \"$2\"" ;; $OG_ERR_DONTFORMAT) MSG="$MSG_ERR_DONTFORMAT \"$2\"" ;; + $OG_ERR_IMAGEFILE) MSG="$MSG_ERR_IMAGEFILE \"$2\"" ;; $OG_ERR_UCASTSYNTAXT) MSG="$MSG_ERR_UCASTSYNTAXT \"$2\"" ;; $OG_ERR_UCASTSENDPARTITION) MSG="$MSG_ERR_UCASTSENDPARTITION \"$2\"" ;; $OG_ERR_UCASTSENDFILE) MSG="$MSG_ERR_UCASTSENDFILE \"$2\"" ;; @@ -244,6 +245,8 @@ case "$CODE" in $OG_ERR_NOTDIFFERENT) MSG="$MSG_ERR_NOTDIFFERENT \"$2\"" ;; $OG_ERR_SYNCHRONIZING) MSG="$MSG_ERR_SYNCHRONIZING \"$2\"" ;; $OG_ERR_NOTUEFI) MSG="$MSG_ERR_NOTUEFI \"$2\"" ;; + $OG_ERR_NOMSDOS) MSG="$MSG_ERR_NOMSDOS \"$2\"" ;; + $OG_ERR_NOTBIOS) MSG="$MSG_ERR_NOTBIOS \"$2\"" ;; *) MSG="$MSG_ERR_GENERIC"; CODE=$OG_ERR_GENERIC ;; esac diff --git a/client/engine/UEFI.lib b/client/engine/UEFI.lib index cd7168e7..1a8bb952 100644 --- a/client/engine/UEFI.lib +++ b/client/engine/UEFI.lib @@ -129,14 +129,14 @@ BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2) OSVERSION=$(ogGetOsVersion $1 $2) case $OSVERSION in *Windows\ 10*) - for f in $EFIDIR/EFI/{$BOOTLABEL,Microsoft}/Boot/bootmgfw.efi; do + for f in $EFIDIR/EFI/{Microsoft,$BOOTLABEL}/Boot/bootmgfw.efi; do [ -r $f ] && LOADER=$f done [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($OSVERSION, EFI)" || return $? # Si existe el directorio Boot lo borramos - [ -d $MNTDIR/Boot ] && rm -rf $MNTDIR/Boot + [ -d $MNTDIR/ogBoot ] && rm -rf $MNTDIR/ogBoot DIRLOADER=$(realpath "${LOADER%/*}/..") - cp -r ${DIRLOADER}/Boot $MNTDIR + cp -r ${DIRLOADER}/Boot $MNTDIR/ogBoot ;; esac } @@ -413,13 +413,16 @@ OSVERSION=$(ogGetOsVersion $1 $2) case $OSVERSION in *Windows\ 10*) BOOTLABEL=$(printf "Part-%02d-%02d" $1 $2) - LOADER=$(ogGetPath $MNTDIR/Boot/bootmgfw.efi) + LOADER=$(ogGetPath $MNTDIR/ogBoot/bootmgfw.efi) [ -n "$LOADER" ] || ogRaiseError $OG_ERR_NOTOS "$1 $2 ($OSVERSION, EFI)" || return $? - [ -r $EFIDIR/$BOOTLABEL ] && rm -rf $EFIDIR/$BOOTLABEL + [ -r $EFIDIR/EFI/$BOOTLABEL ] && rm -rf $EFIDIR/EFI/$BOOTLABEL mkdir -p $EFIDIR/EFI/$BOOTLABEL - cp -r "${LOADER%/*}" $EFIDIR/EFI/$BOOTLABEL + cp -r "${LOADER%/*}" $EFIDIR/EFI/$BOOTLABEL/Boot # Nombre OpenGnsys para cargador cp $LOADER $EFIDIR/EFI/$BOOTLABEL/Boot/ogloader.efi + + # Si existe subcarpeta Microsoft en la partición EFI la renombramos + [ "$(ogGetPath $EFIDIR/EFI/Microsoft)" == "" ] || mv $EFIDIR/EFI/{Microsoft,Microsoft.backup.og} ;; esac } diff --git a/client/shared/etc/engine.json b/client/shared/etc/engine.json index ef34de5e..7d9e75fb 100644 --- a/client/shared/etc/engine.json +++ b/client/shared/etc/engine.json @@ -366,6 +366,11 @@ "clonable": true }, { + "id": "27", + "type": "HNTFS-WINRE", + "clonable": true + }, + { "id": "82", "type": "LINUX-SWAP", "clonable": false diff --git a/client/shared/etc/lang.ca_ES.conf b/client/shared/etc/lang.ca_ES.conf index 92e97598..c36e4139 100644 --- a/client/shared/etc/lang.ca_ES.conf +++ b/client/shared/etc/lang.ca_ES.conf @@ -1,4 +1,7 @@ # Fichero de idioma: catalá. +#@version 1.1.1 +#@author + # Mensajes de error. MSG_ERR_GENERIC="Error imprevisto no definido" @@ -10,13 +13,16 @@ MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" MSG_ERR_CACHE="Error en partición de caché local" MSG_ERR_NOGPT="El disco indicado no contiene una particion GPT" MSG_ERR_REPO="Error al montar el repositorio de imágenes" +MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS" MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" +MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone" MSG_ERR_NOTEXEC="Programa o función no ejecutable" MSG_ERR_NOTWRITE="No hay acceso de escritura" MSG_ERR_NOTCACHE="No existe particion Cache en el cliente" MSG_ERR_NOTUEFI="La interfaz UEFI no está activa" +MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa" MSG_ERR_CACHESIZE="El espacio de la cache local o remota no es suficiente" MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos" MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos" @@ -348,7 +354,7 @@ MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculamos el tamaño de la imagen." MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobamos si hay que la imagen del repositorio es mayor que la de la cache." MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la cache y actuar según engine.cfg" -MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesion multicast: ServidorMcast:PuertoSession:PuertoDatos" +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesion multicast: ServidorMcast:PuertoDatos" # interface sustituye temporalmente al scritp restore MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg" diff --git a/client/shared/etc/lang.en_GB.conf b/client/shared/etc/lang.en_GB.conf index b21a270f..b43c3868 100644 --- a/client/shared/etc/lang.en_GB.conf +++ b/client/shared/etc/lang.en_GB.conf @@ -13,13 +13,16 @@ MSG_ERR_LOCKED="Resource locked by exclusive use operation" MSG_ERR_CACHE="Local cache error" MSG_ERR_NOGPT="Current disk does not include GPT partition" MSG_ERR_REPO="Failed when mounting images repository" +MSG_ERR_NOMSDOS="Current disk does not include MSDOS partition" MSG_ERR_FILESYS="Unknown or unmountable file system" MSG_ERR_NOTOS="Cannot detect or boot OS" MSG_ERR_IMAGE="Cannot create or restore a system image" +MSG_ERR_IMAGEFILE="Image file corrupt or of other partclone version" MSG_ERR_NOTEXEC="Non executable program or function" MSG_ERR_NOTWRITE="Write access denied" MSG_ERR_NOTCACHE="No client cache partition" MSG_ERR_NOTUEFI="UEFI isn't active" +MSG_ERR_NOTBIOS="BIOS legacy isn't active" MSG_ERR_CACHESIZE="Not enough space in local or remote cache" MSG_ERR_REDUCEFS="Error when reducing file system" MSG_ERR_EXTENDFS="Error when expanding file system" @@ -350,7 +353,7 @@ MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calculate image size." MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Check if repository image file size is bigger than Cache size." MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Check free Cache and apply engine.cfg" -MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Checking Multicast Session McastServer:SessionPort:DataPort" +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Checking Multicast Session McastServer:DataPort" # interface temporarily replaces restore script MSG_SCRIPTS_CHECK_ENGINE="Analyze process to carry out according to engine.cfg" diff --git a/client/shared/etc/lang.es_ES.conf b/client/shared/etc/lang.es_ES.conf index 27d0cd64..78ce3de2 100644 --- a/client/shared/etc/lang.es_ES.conf +++ b/client/shared/etc/lang.es_ES.conf @@ -1,4 +1,7 @@ # Fichero de idioma: español. +#@version 1.1.1 +#@author + # Mensajes de error. MSG_ERR_GENERIC="Error imprevisto no definido" @@ -10,13 +13,16 @@ MSG_ERR_LOCKED="Recurso bloqueado por operación de uso exclusivo" MSG_ERR_CACHE="Error en partición de caché local" MSG_ERR_NOGPT="El disco indicado no contiene una partición GPT" MSG_ERR_REPO="Error al montar el repositorio de imágenes" +MSG_ERR_NOMSDOS="El disco indicado no contiene una partición MSDOS" MSG_ERR_FILESYS="Sistema de archivos desconocido o no se puede montar" MSG_ERR_NOTOS="Sistema operativo no detectado o no se puede iniciar" MSG_ERR_IMAGE="No se puede crear o restaurar una image de sistema" +MSG_ERR_IMAGEFILE="Archivo de imagen corrupto o de otra versión de partclone" MSG_ERR_NOTEXEC="Programa o función no ejecutable" MSG_ERR_NOTWRITE="No hay acceso de escritura" MSG_ERR_NOTCACHE="No existe partición caché en el cliente" MSG_ERR_NOTUEFI="La interfaz UEFI no está activa" +MSG_ERR_NOTBIOS="La interfaz BIOS Legacy no está activa" MSG_ERR_CACHESIZE="El espacio de la caché local o remota no es suficiente" MSG_ERR_REDUCEFS="Error al reducir el sistema de archivos" MSG_ERR_EXTENDFS="Error al expandir el sistema de archivos" @@ -347,7 +353,7 @@ MSG_SCRIPTS_UPDATECACHE_CHECKSIZEDIR="Calcular el tamaño de la imagen." MSG_SCRIPTS_UPDATECACHE_CHECKSIZEIMG="Comprobar si la imagen del repositorio es mayor que la de la caché." MSG_SCRIPTS_UPDATECACHE_IFNOTCACHEDO="Comprobar el espacio libre de la caché y actuar según engine.cfg" -MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesión Multicast: ServidorMcast:PuertoSession:PuertoDatos" +MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION="Comprobando sesión Multicast: ServidorMcast:PuertoDatos" # interface sustituye temporalmente al scritp restore MSG_SCRIPTS_CHECK_ENGINE="Analizar proceso a realizar según engine.cfg" diff --git a/client/shared/etc/preinit/loadenviron.sh b/client/shared/etc/preinit/loadenviron.sh index c442eb5f..ceb6ca48 100755 --- a/client/shared/etc/preinit/loadenviron.sh +++ b/client/shared/etc/preinit/loadenviron.sh @@ -104,3 +104,4 @@ fi eval $(jq -r 'foreach .errors[] as $err (""; "export "+$err.name+"="+($err.id|tostring))' $ENGINECFG 2>/dev/null) export OG_ERR_NOTUEFI=80 # La interfaz UEFI no está activa +export OG_ERR_NOTBIOS=81 # La interfaz BIOS legacy no está activa diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/COPYING b/client/shared/lib/grub4dos/grub4dos-0.4.6a/COPYING new file mode 100755 index 00000000..eeb586b3 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) 19yy <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/Get_Source_of_This_Build.txt b/client/shared/lib/grub4dos/grub4dos-0.4.6a/Get_Source_of_This_Build.txt new file mode 100755 index 00000000..886a99ae --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/Get_Source_of_This_Build.txt @@ -0,0 +1,8 @@ +-e Get the source code of this build in this way:
+
+ git clone git://github.com/chenall/grub4dos.git
+ cd grub4dos
+ git checkout 34ca1a9 -b build
+
+-e and now you may do a "make" to compile.
+
diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/badgrub.exe b/client/shared/lib/grub4dos/grub4dos-0.4.6a/badgrub.exe Binary files differnew file mode 100755 index 00000000..060ed6da --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/badgrub.exe diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace.com b/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace.com Binary files differnew file mode 100755 index 00000000..a7bf25c5 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace.com diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace64.com b/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace64.com Binary files differnew file mode 100755 index 00000000..d57e6620 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/bootlace64.com diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/eltorito.sys b/client/shared/lib/grub4dos/grub4dos-0.4.6a/eltorito.sys Binary files differnew file mode 100755 index 00000000..d5e12d2e --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/eltorito.sys diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr Binary files differnew file mode 100755 index 00000000..eb064275 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.mbr b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.mbr Binary files differnew file mode 100755 index 00000000..d168da09 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.mbr diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.pbr b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.pbr Binary files differnew file mode 100755 index 00000000..b71b10a9 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr.pbr diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr_cd.bin b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr_cd.bin Binary files differnew file mode 100755 index 00000000..5443b118 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grldr_cd.bin diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.exe b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.exe Binary files differnew file mode 100755 index 00000000..24d91400 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.exe diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.pif b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.pif Binary files differnew file mode 100755 index 00000000..28b43805 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/grub.pif diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/hmload.com b/client/shared/lib/grub4dos/grub4dos-0.4.6a/hmload.com Binary files differnew file mode 100755 index 00000000..04c794c3 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/hmload.com diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/ipxegrldr b/client/shared/lib/grub4dos/grub4dos-0.4.6a/ipxegrldr Binary files differnew file mode 100755 index 00000000..425e6df9 --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/ipxegrldr diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/config.sys b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/config.sys new file mode 100755 index 00000000..9aa253ef --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/config.sys @@ -0,0 +1,6 @@ +rem load grub.exe before emm386.exe
+device=grub.exe --bypass --time-out=5 --config-file="color black/cyan yellow/cyan;timeout 60;default 0;title find and load NTLDR of Windows NT/2K/XP;find --set-root /ntldr;chainloader /ntldr;title find and load CMLDR, the Recovery Console of Windows NT/2K/XP;find --set-root /cmldr;chainloader /cmldr;write 0x7C03 0x63646D63;write 0x7C07 0x00736E6F;title find and load IO.SYS of Windows 9x/Me;find --set-root /io.sys;chainloader /io.sys;title floppy (fd0);chainloader (fd0)+1;rootnoverify (fd0);title find and boot Linux with menu.lst already installed;find --set-root /sbin/init;configfile /boot/grub/menu.lst;title find and boot Mandriva with menu.lst already installed;find --set-root /etc/mandriva-release;configfile /boot/grub/menu.lst;title back to dos;quit;title commandline;commandline;title reboot;reboot;title halt;halt;"
+
+device=c:\windows\himem.sys
+device=c:\windows\emm386.exe
+
diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/default b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/default new file mode 100755 index 00000000..689c3c8b --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/default @@ -0,0 +1,46 @@ +
+#
+#
+#
+#
+#
+#
+#
+#
+#
+#
+# !!!!!!! The file size is 2048 bytes. Don't change the file size !!!!!!!
+# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# WARNING: If you want to edit this file directly, do not remove any line
+# from this file, including this warning. XXXXXXXXXXXXXXXXXXXXXXXXXXX
+# XXXXXXXXXXXXXXXXXXXXX
+# !!!!!!! The file size is 2048 bytes. Don't change the file size !!!!!!!
+# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
diff --git a/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/menu.lst b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/menu.lst new file mode 100755 index 00000000..27ce716c --- /dev/null +++ b/client/shared/lib/grub4dos/grub4dos-0.4.6a/sample/menu.lst @@ -0,0 +1,151 @@ +# This is a sample menu.lst file. You should make some changes to it.
+# The old install method of booting via the stage-files has been removed.
+# Please install GRLDR boot strap code to MBR with the bootlace.com
+# utility under DOS/Win9x or Linux.
+#
+# It must be UTF-8 encoding for multi-lingual support. Font lines can be
+# appended to the file. The font lines should be in the unifont.hex format.
+
+color blue/green yellow/red white/magenta white/magenta
+timeout 30
+## menu border color
+color border=0xEEFFEE
+## set vbe mode
+graphicsmode -1 640:800 480:600 24:32 || graphicsmode -1 -1 -1 24:32
+## loading splashimage
+splashimage /boot/grub/splashimage.xpm || splashimage /boot/grub/splashimage.bmp
+default /default
+## Menu AutoNumber
+write 0x8274 0x2001
+
+title find and load NTLDR of Windows NT/2K/XP\n find and load NTLDR of Windows NT/2K/XP
+fallback +1
+find --set-root --ignore-floppies --ignore-cd /ntldr
+map () (hd0)
+map (hd0) ()
+map --rehook
+find --set-root --ignore-floppies --ignore-cd /ntldr
+chainloader /ntldr
+savedefault --wait=2
+
+#iftitle only show when command in [] returns true
+# set a variable named bootmgr where /bootmgr is found.
+iftitle [find --set-root --devices=h /bootmgr && call set bootmgr=%@root^%] load BOOTMGR of Windows VISTA/WIN7/WIN2008 on %bootmgr%
+fallback +1
+chainloader %bootmgr%/bootmgr
+savedefault --wait=2
+
+title find and load CMLDR, the Recovery Console of Windows NT/2K/XP
+fallback +1
+find --set-root --ignore-floppies --ignore-cd /cmldr
+map () (hd0)
+map (hd0) ()
+map --rehook
+find --set-root --ignore-floppies --ignore-cd /cmldr
+chainloader /cmldr
+#####################################################################
+# write string "cmdcons" to memory 0000:7C03 in 2 steps:
+#####################################################################
+# step 1. Write 4 chars "cmdc" at 0000:7C03
+#write 0x7C03 0x63646D63
+# step 2. Write 3 chars "ons" and an ending null at 0000:7C07
+#write 0x7C07 0x00736E6F
+
+# or.
+#write --offset=3 (md)0x3e+1 cmdcons\0
+# or
+calc *0x7c03=0x00736E6F63646D63
+
+savedefault --wait=2
+
+title Chainload IO.SYS for booting MS-DOS/Windows 9x/Me
+fallback +1
+find --set-root --ignore-floppies --ignore-cd /io.sys
+chainloader /io.sys
+savedefault --wait=2
+#
+# Or in this way:
+#
+# find --set-root --ignore-floppies --ignore-cd chainloader /io.sys
+# boot
+#
+# The above boot command is needed in this case.
+# See "Delimitors or comments between titles" in grub4dos_readme.txt.
+
+title find /boot/grub/menu.lst for booting Linux (Mageia, Mandriva, etc)
+fallback +1
+find --set-root --ignore-floppies --ignore-cd /boot/grub/menu.lst
+configfile /boot/grub/menu.lst
+
+title Switch to GRUB2 core.img for booting Linux (Ubuntu, etc)
+fallback +1
+find --set-root --ignore-floppies --ignore-cd /boot/grub/i386-pc/core.img
+kernel /boot/grub/i386-pc/core.img
+
+title commandline
+commandline
+
+title 0PE LiveISO
+find --set-root --ignore-floppies --ignore-cd /0PE.ISO
+map /0PE.ISO (0xff)
+map --hook
+chainloader (0xff)
+savedefault --wait=2
+
+title MicroPE LiveISO
+find --set-root --ignore-floppies --ignore-cd /boot/MicroPE.ISO
+map /boot/MicroPE.ISO (0xff)
+map --hook
+chainloader (0xff)
+savedefault --wait=2
+
+title Parted Magic LiveISO
+find --set-root --ignore-floppies --ignore-cd /pmagic.iso
+map /pmagic.iso (0xff)
+map --hook
+chainloader (0xff)
+savedefault --wait=2
+
+title Ultimate Boot CD LiveISO
+find --set-root --ignore-floppies --ignore-cd /ubcd.iso
+map /ubcd.iso (0xff)
+map --hook
+chainloader (0xff)
+savedefault --wait=2
+
+title SliTaz LiveISO
+find --set-root --ignore-floppies --ignore-cd /slitaz.iso
+map /slitaz.iso (0xff)
+map --hook
+chainloader (0xff)
+
+title Mageia Installation ISO
+find --set-root --ignore-floppies --ignore-cd /Mageia-2-x86_64-DVD.iso
+map /Mageia-2-x86_64-DVD.iso (0xff)
+map --hook
+chainloader (0xff)
+
+title reboot (重启)
+reboot
+
+title halt (关机)
+halt
+
+title MAXDOS.IMG
+find --set-root --ignore-floppies --ignore-cd /boot/MAXDOS.IMG
+map --mem /boot/MAXDOS.IMG (fd0)
+map --hook
+chainloader (fd0)+1
+rootnoverify (fd0)
+
+# In the end, font lines for unicode chars in unifont.hex format.
+# It should include all unicode chars used in the above menu code.
+# Surely normal ASCII chars are not necessary to be included here.
+
+5173:10100810082000003FF8010001000100FFFE010002800280044008203018C006
+542F:010000801FFC1004100410041FFC10001000100017FC24042404440487FC0404
+673A:100011F011101110FD10111031103910551055109110111211121212120E1400
+91CD:001000F83F000100FFFE01001FF011101FF011101FF001003FF80100FFFE0000
+
+
+
diff --git a/client/shared/scripts/configureOs b/client/shared/scripts/configureOs index 2e529c9e..3f39c235 100755 --- a/client/shared/scripts/configureOs +++ b/client/shared/scripts/configureOs @@ -70,10 +70,10 @@ case "$OSTYPE" in # Cambiar nombre en sistemas Windows. HOST=${HOST:-"pc"} ogSetWindowsName $1 $2 "$HOST" - # Si es UEFI copio el cargador de arranque a la partición EFI e instalo rEFInd. + # Si es UEFI copio el cargador de arranque a la partición EFI e instalo Grub. if ogIsEfiActive; then ogRestoreEfiBootLoader $1 $2 - ogRefindInstall + ogGrubInstallMbr $(ogGetEsp) TRUE else # Configurar el boot sector de la partición Windows. ogFixBootSector $1 $2 @@ -93,10 +93,10 @@ case "$OSTYPE" in Linux) # Postconfiguración de GNU/Linux. # Configuro fstab: particion de Swap y si es UEFI además la partición EFI. ogConfigureFstab $1 $2 + # Si es UEFI instalo Grub en la partición EFI + ogIsEfiActive && ogGrubInstallMbr $(ogGetEsp) TRUE ## Instala (no configura) el codigo de arranque del Grub en la partición (no lo configura, se mantiene el original de la imagen) ogGrubInstallPartition $1 $2 - # Si es UEFI instalo rEFInd. - ogIsEfiActive && ogRefindInstall # Eliminar el antiguo cliente de Linux. [ -n "$(find $MNTDIR/usr/sbin $MNTDIR/sbin $MNTDIR/usr/local/sbin -name ogAdmLnxClient -print)" ] && ogUninstallLinuxClient $1 $2 # Configurar nuevo agente OGAgent. @@ -173,4 +173,3 @@ EOT ;; esac exit 0 - diff --git a/client/shared/scripts/deployImage b/client/shared/scripts/deployImage index 9406d80e..d74d3ac2 100755 --- a/client/shared/scripts/deployImage +++ b/client/shared/scripts/deployImage @@ -98,7 +98,12 @@ fi #Informacioin previa de la imagen IMGOS=$(ogGetImageInfo `ogGetPath $MODE $IMGNAME.img`) -[ -n "$IMGOS" ] || exit $(ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2"; echo $?) +case $? in + 0) ;; + 1) ogRaiseError session $OG_ERR_NOTFOUND "$REPO $2" || exit $? ;; + 5) ogRaiseError session $OG_ERR_IMAGEFILE "$REPO $2" || exit $? ;; + *) ogRaiseError session $OG_ERR_GENERIC || exit $? ;; +esac IMGSIZE=$(ls -s `ogGetPath $MODE $IMGNAME.img`| cut -f1 -d" ") ogEcho log session "[1] REPO=$REPO IMG-FILE=$IMGNAME.img SIZE=$IMGSIZE (KB) METADATA=$IMGOS" diff --git a/client/shared/scripts/grubSyntax b/client/shared/scripts/grubSyntax index aa1adb2e..8997c97b 100755 --- a/client/shared/scripts/grubSyntax +++ b/client/shared/scripts/grubSyntax @@ -34,11 +34,11 @@ grub_probe=${grub_probe:-$OGBIN/grub-probe1.99_$(arch)} #librerias del osProber para kernel antiguos: detecta e identifica sistema operativos. if grub-install --version | grep 1.99 ; then - cp -r /opt/opengnsys/lib/os-probes/* /usr/lib/os-probes/ + cp -r /opt/opengnsys/lib/os-probes/* /usr/lib/os-probes/ else - # Librería os-probe para cargador de microsoft en dir part-x-y (uefi) - OSPROBE_MS_PART="/opt/opengnsys/lib/os-probes/mounted/efi/31part-x-y" - [ -f $OSPROBE_MS_PART ] && cp $OSPROBE_MS_PART /usr/lib/os-probes/mounted/efi + # Librería os-probe para cargador de microsoft en dir part-x-y (uefi) + OSPROBE_MS_PART="/opt/opengnsys/lib/os-probes/mounted/efi/31part-x-y" + [ -f $OSPROBE_MS_PART ] && cp $OSPROBE_MS_PART /usr/lib/os-probes/mounted/efi fi @@ -60,62 +60,80 @@ fi OG_prepare_grub_to_access_device () { - device="$1" - loop_file= - case ${device} in - /dev/loop/*|/dev/loop[0-9]) - grub_loop_device="${device#/dev/}" - loop_file=`losetup "${device}" | sed -e "s/^[^(]*(\([^)]\+\)).*/\1/"` - case $loop_file in - /dev/*) ;; - *) - loop_device="${device}" - device=`"${grub_probe}" --target=device "${loop_file}"` || return 0 - ;; - esac - ;; - esac - if dmsetup status $device 2>/dev/null | grep -q 'crypt[[:space:]]$'; then - grub_warn \ - "$device is a crypto device, which GRUB cannot read directly. Some" \ - "necessary modules may be missing from /boot/grub/grub.cfg. You may" \ - "need to list them in GRUB_PRELOAD_MODULES in /etc/default/grub. See" \ - "http://bugs.debian.org/542165 for details." - return 0 - fi - # Abstraction modules aren't auto-loaded. - abstraction="`"${grub_probe}" --device "${device}" --target=abstraction`" - for module in ${abstraction} ; do - echo "insmod ${module}" - done - partmap="`"${grub_probe}" --device "${device}" --target=partmap`" - for module in ${partmap} ; do - case "${module}" in - netbsd | openbsd) - echo "insmod part_bsd";; - *) - echo "insmod part_${module}";; - esac - done - fs="`"${grub_probe}" --device "${device}" --target=fs`" - for module in ${fs} ; do - echo "insmod ${module}" - done - # If there's a filesystem UUID that GRUB is capable of identifying, use it; - # otherwise set root as per value in device.map. - #OG modificacion - echo "set root='`"${grub_probe}" --device "${device}" --target=drive`'" - #if fs_uuid="`"${grub_probe}" --device "${device}" --target=fs_uuid 2> /dev/null`" ; then - # echo "search --no-floppy --fs-uuid --set=root ${fs_uuid}" - #fi - - if [ "x${loop_file}" != x ]; then - loop_mountpoint="$(awk '"'${loop_file}'" ~ "^"$2 && $2 != "/" { print $2 }' /proc/mounts | tail -n1)" - if [ "x${loop_mountpoint}" != x ]; then - echo "loopback ${grub_loop_device} ${loop_file#$loop_mountpoint}" - echo "set root=(${grub_loop_device})" - fi - fi + device="$1" + loop_file= + case ${device} in + /dev/loop/*|/dev/loop[0-9]) + grub_loop_device="${device#/dev/}" + loop_file=`losetup "${device}" | sed -e "s/^[^(]*(\([^)]\+\)).*/\1/"` + case $loop_file in + /dev/*) ;; + *) + loop_device="${device}" + device=`"${grub_probe}" --target=device "${loop_file}"` || return 0 + ;; + esac + ;; + esac + if dmsetup status $device 2>/dev/null | grep -q 'crypt[[:space:]]$'; then + grub_warn \ + "$device is a crypto device, which GRUB cannot read directly. Some" \ + "necessary modules may be missing from /boot/grub/grub.cfg. You may" \ + "need to list them in GRUB_PRELOAD_MODULES in /etc/default/grub. See" \ + "http://bugs.debian.org/542165 for details." + return 0 + fi + # Abstraction modules aren't auto-loaded. + abstraction="`"${grub_probe}" --device "${device}" --target=abstraction`" + for module in ${abstraction} ; do + echo "insmod ${module}" + done + partmap="`"${grub_probe}" --device "${device}" --target=partmap`" + for module in ${partmap} ; do + case "${module}" in + netbsd | openbsd) + echo "insmod part_bsd";; + *) + echo "insmod part_${module}";; + esac + done + fs="`"${grub_probe}" --device "${device}" --target=fs`" + for module in ${fs} ; do + echo "insmod ${module}" + done + # If there's a filesystem UUID that GRUB is capable of identifying, use it; + # otherwise set root as per value in device.map. + #OG modificacion + # PARCHE UHU ...SI el disco es nvme se cambia su nomenclatura, ya que grub_probe no funciona bien + if [[ $DEVICE == *"nvme"* ]]; then + #DEVICE=`echo $DEVICE | sed -e "s/\/dev\/nvme/hd/g" | sed -e "s/n.*p/,gpt/g"` + #TODO Detectar si es GPT o no... + read -r D P <<< `ogDevToDisk $DEVICE` + if [ "`ogGetPartitionTableType $D`" == "GPT" ]; then + # Si es gpt se sustituye por "hd(X-1),gptY" + #device=`echo $device | sed -e "s/\/dev\/nvme/hd/g" | sed -e "s/n.*p/,gpt/g"` + nvmeDevice=`echo "hd"$(expr $D - 1)",gpt$P"` + + else + # Sino se sustituye por hd(X-1),(Y-1) + nvmeDevice=`echo "hd"$(expr $D - 1)","$(expr $P - 1)` + fi + echo "set root='$nvmeDevice'" + else + echo "set root='`"${grub_probe}" --device "${device}" --target=drive`'" + fi + + #if fs_uuid="`"${grub_probe}" --device "${device}" --target=fs_uuid 2> /dev/null`" ; then + # echo "search --no-floppy --fs-uuid --set=root ${fs_uuid}" + #fi + + if [ "x${loop_file}" != x ]; then + loop_mountpoint="$(awk '"'${loop_file}'" ~ "^"$2 && $2 != "/" { print $2 }' /proc/mounts | tail -n1)" + if [ "x${loop_mountpoint}" != x ]; then + echo "loopback ${grub_loop_device} ${loop_file#$loop_mountpoint}" + echo "set root=(${grub_loop_device})" + fi + fi } @@ -148,16 +166,16 @@ libdir=${exec_prefix}/lib found_other_os= make_timeout () { - if [ "x${found_other_os}" = "x" ] ; then - if [ "x${1}" != "x" ] ; then - if [ "x${GRUB_HIDDEN_TIMEOUT_QUIET}" = "xtrue" ] ; then - verbose= - else - verbose=" --verbose" - fi - - if [ "x${1}" = "x0" ] ; then - cat <<EOF + if [ "x${found_other_os}" = "x" ] ; then + if [ "x${1}" != "x" ] ; then + if [ "x${GRUB_HIDDEN_TIMEOUT_QUIET}" = "xtrue" ] ; then + verbose= + else + verbose=" --verbose" + fi + + if [ "x${1}" = "x0" ] ; then + cat <<EOF if [ "x\${timeout}" != "x-1" ]; then if keystatus; then if keystatus --shift; then @@ -173,7 +191,7 @@ if [ "x\${timeout}" != "x-1" ]; then fi EOF else - cat << EOF + cat << EOF if [ "x\${timeout}" != "x-1" ]; then if sleep$verbose --interruptible ${GRUB_HIDDEN_TIMEOUT} ; then set timeout=0 @@ -186,28 +204,28 @@ EOF } adjust_timeout () { - if [ "x$GRUB_BUTTON_CMOS_ADDRESS" != "x" ]; then - cat <<EOF + if [ "x$GRUB_BUTTON_CMOS_ADDRESS" != "x" ]; then + cat <<EOF if cmostest $GRUB_BUTTON_CMOS_ADDRESS ; then EOF - make_timeout "${GRUB_HIDDEN_TIMEOUT_BUTTON}" "${GRUB_TIMEOUT_BUTTON}" - echo else - make_timeout "${GRUB_HIDDEN_TIMEOUT}" "${GRUB_TIMEOUT}" - echo fi +make_timeout "${GRUB_HIDDEN_TIMEOUT_BUTTON}" "${GRUB_TIMEOUT_BUTTON}" +echo else +make_timeout "${GRUB_HIDDEN_TIMEOUT}" "${GRUB_TIMEOUT}" +echo fi else - make_timeout "${GRUB_HIDDEN_TIMEOUT}" "${GRUB_TIMEOUT}" + make_timeout "${GRUB_HIDDEN_TIMEOUT}" "${GRUB_TIMEOUT}" fi } if [ "x${GRUB_DISABLE_OS_PROBER}" = "xtrue" ]; then - adjust_timeout - exit 0 + adjust_timeout + exit 0 fi if [ -z "`which os-prober 2> /dev/null`" -o -z "`which linux-boot-prober 2> /dev/null`" ] ; then - # missing os-prober and/or linux-boot-prober - adjust_timeout - exit 0 + # missing os-prober and/or linux-boot-prober + adjust_timeout + exit 0 fi case "$1" in @@ -233,59 +251,59 @@ fi if [ -z "${OSPROBED}" ] ; then - # empty os-prober output, nothing doing - adjust_timeout - exit 0 + # empty os-prober output, nothing doing + adjust_timeout + exit 0 fi osx_entry() { found_other_os=1 - cat << EOF + cat << EOF menuentry "${LONGNAME} (${2}-bit) (on ${DEVICE})" --class osx --class darwin --class os { EOF - save_default_entry | sed -e "s/^/\t/" - prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - cat << EOF - load_video - set do_resume=0 - if [ /var/vm/sleepimage -nt10 / ]; then - if xnu_resume /var/vm/sleepimage; then - set do_resume=1 - fi - fi - if [ \$do_resume = 0 ]; then - xnu_uuid ${OSXUUID} uuid - if [ -f /Extra/DSDT.aml ]; then - acpi -e /Extra/DSDT.aml - fi - $1 /mach_kernel boot-uuid=\${uuid} rd=*uuid - if [ /System/Library/Extensions.mkext -nt /System/Library/Extensions ]; then - xnu_mkext /System/Library/Extensions.mkext - else - xnu_kextdir /System/Library/Extensions - fi - if [ -f /Extra/Extensions.mkext ]; then - xnu_mkext /Extra/Extensions.mkext - fi - if [ -d /Extra/Extensions ]; then - xnu_kextdir /Extra/Extensions - fi - if [ -f /Extra/devprop.bin ]; then - xnu_devprop_load /Extra/devprop.bin - fi - if [ -f /Extra/splash.jpg ]; then - insmod jpeg - xnu_splash /Extra/splash.jpg - fi - if [ -f /Extra/splash.png ]; then - insmod png - xnu_splash /Extra/splash.png - fi - if [ -f /Extra/splash.tga ]; then - insmod tga - xnu_splash /Extra/splash.tga - fi - fi +save_default_entry | sed -e "s/^/\t/" +prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" +cat << EOF + load_video + set do_resume=0 + if [ /var/vm/sleepimage -nt10 / ]; then + if xnu_resume /var/vm/sleepimage; then + set do_resume=1 + fi + fi + if [ \$do_resume = 0 ]; then + xnu_uuid ${OSXUUID} uuid + if [ -f /Extra/DSDT.aml ]; then + acpi -e /Extra/DSDT.aml + fi + $1 /mach_kernel boot-uuid=\${uuid} rd=*uuid + if [ /System/Library/Extensions.mkext -nt /System/Library/Extensions ]; then + xnu_mkext /System/Library/Extensions.mkext + else + xnu_kextdir /System/Library/Extensions + fi + if [ -f /Extra/Extensions.mkext ]; then + xnu_mkext /Extra/Extensions.mkext + fi + if [ -d /Extra/Extensions ]; then + xnu_kextdir /Extra/Extensions + fi + if [ -f /Extra/devprop.bin ]; then + xnu_devprop_load /Extra/devprop.bin + fi + if [ -f /Extra/splash.jpg ]; then + insmod jpeg + xnu_splash /Extra/splash.jpg + fi + if [ -f /Extra/splash.png ]; then + insmod png + xnu_splash /Extra/splash.png + fi + if [ -f /Extra/splash.tga ]; then + insmod tga + xnu_splash /Extra/splash.tga + fi + fi } EOF } @@ -293,156 +311,156 @@ EOF wubi= for OS in ${OSPROBED} ; do - DEVICE="`echo ${OS} | cut -d ':' -f 1`" - LONGNAME="`echo ${OS} | cut -d ':' -f 2 | tr '^' ' '`" - LABEL="`echo ${OS} | cut -d ':' -f 3 | tr '^' ' '`" - BOOT="`echo ${OS} | cut -d ':' -f 4`" + DEVICE="`echo ${OS} | cut -d ':' -f 1`" + LONGNAME="`echo ${OS} | cut -d ':' -f 2 | tr '^' ' '`" + LABEL="`echo ${OS} | cut -d ':' -f 3 | tr '^' ' '`" + BOOT="`echo ${OS} | cut -d ':' -f 4`" - if [ -z "${LONGNAME}" ] ; then - LONGNAME="${LABEL}" - fi + if [ -z "${LONGNAME}" ] ; then + LONGNAME="${LABEL}" + fi - echo "Found ${LONGNAME} on ${DEVICE}" >&2 - - case ${BOOT} in - chain) - - case ${LONGNAME} in - Windows*) - if [ -z "$wubi" ]; then - if [ -x /usr/share/lupin-support/grub-mkimage ] && \ - /usr/share/lupin-support/grub-mkimage --test; then - wubi=yes - else - wubi=no - fi - fi - if [ "$wubi" = yes ]; then - echo "Skipping ${LONGNAME} on Wubi system" >&2 - continue - fi - ;; - esac - #adv - LABELCLASS=$(echo "${LONGNAME}" | awk '{print tolower($1$2);}') - - found_other_os=1 - cat << EOF + echo "Found ${LONGNAME} on ${DEVICE}" >&2 + + case ${BOOT} in + chain) + + case ${LONGNAME} in + Windows*) + if [ -z "$wubi" ]; then + if [ -x /usr/share/lupin-support/grub-mkimage ] && \ + /usr/share/lupin-support/grub-mkimage --test; then + wubi=yes + else + wubi=no + fi + fi + if [ "$wubi" = yes ]; then + echo "Skipping ${LONGNAME} on Wubi system" >&2 + continue + fi + ;; + esac + #adv + LABELCLASS=$(echo "${LONGNAME}" | awk '{print tolower($1$2);}') + + found_other_os=1 + cat << EOF menuentry "${LONGNAME} (on ${DEVICE})" --class $LABELCLASS --class windows { EOF - save_default_entry | sed -e "s/^/\t/" +save_default_entry | sed -e "s/^/\t/" #ADV prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - OG_prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" +OG_prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - case ${LONGNAME} in +case ${LONGNAME} in Windows\ Vista*|Windows\ 7*|Windows\ Server\ 2008*) - ;; + ;; *) -#ADV cat << EOF -#ADV drivemap -s (hd0) \${root} -#ADV EOF - ;; - esac + #ADV cat << EOF + #ADV drivemap -s (hd0) \${root} + #ADV EOF + ;; +esac - cat <<EOF +cat <<EOF chainloader +1 } EOF - ;; +;; efi) - found_other_os=1 - EFIPATH=${DEVICE#*@} - DEVICE=${DEVICE%@*} - onstr="$(gettext_printf "(on %s)" "${DEVICE}")" - cat << EOF + found_other_os=1 + EFIPATH=${DEVICE#*@} + DEVICE=${DEVICE%@*} + onstr="$(gettext_printf "(on %s)" "${DEVICE}")" + cat << EOF menuentry '$(echo "${LONGNAME} $onstr" | grub_quote)' --class windows --class os \$menuentry_id_option 'osprober-efi-$(grub_get_device_id "${DEVICE}")' { EOF - save_default_entry | sed -e "s/^/\t/" +save_default_entry | sed -e "s/^/\t/" #ADV prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - OG_prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" +OG_prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - cat <<EOF - chainloader ${EFIPATH} +cat <<EOF + chainloader ${EFIPATH} } EOF - ;; +;; linux) - KERNELPARAM="" - #linuxprobed detecta todos los kernels de una partición. - LINUXPROBED="`linux-boot-prober ${DEVICE} 2> /dev/null | tr ' ' '^' | paste -s -d ' '`" -#esta opcion de linuxprobe solo interpreta el primer kernel detectado de la partición -#Si queremos que autoincluya todos los kernels hay que comentar esta filtrado de LINUXPROBED - LINUXPROBED=$(echo $LINUXPROBED | awk '{ print $1}') - prepare_boot_cache= - # echo "ADV listado de los kerenel encontrados linux-boot-prober ${DEVICE} $LINUXPROBED" - for LINUX in ${LINUXPROBED} ; do - LINUX=$LINUXPROBED - LROOT="`echo ${LINUX} | cut -d ':' -f 1`" - LBOOT="`echo ${LINUX} | cut -d ':' -f 2`" - LLABEL="`echo ${LINUX} | cut -d ':' -f 3 | tr '^' ' '`" - LKERNEL="`echo ${LINUX} | cut -d ':' -f 4`" - LINITRD="`echo ${LINUX} | cut -d ':' -f 5`" - LPARAMS="`echo ${LINUX} | cut -d ':' -f 6- | tr '^' ' '`" - # En los parámetros cambiamos el UUID por el valor de LROOT - UUID=$(blkid -s UUID -o value $LROOT) - LPARAMS="$(echo $LPARAMS | sed "s|UUID=$UUID|$LROOT|g")" - if [ -z "${LLABEL}" ] ; then - LLABEL="${LONGNAME}" - fi - - if [ "${LROOT}" != "${LBOOT}" ]; then - LKERNEL="${LKERNEL#/boot}" - LINITRD="${LINITRD#/boot}" - fi - - found_other_os=1 - LABELCLASS=$(echo "${LLABEL}" | awk '{print tolower($1);}') - cat << EOF + KERNELPARAM="" + #linuxprobed detecta todos los kernels de una partición. + LINUXPROBED="`linux-boot-prober ${DEVICE} 2> /dev/null | tr ' ' '^' | paste -s -d ' '`" + #esta opcion de linuxprobe solo interpreta el primer kernel detectado de la partición + #Si queremos que autoincluya todos los kernels hay que comentar esta filtrado de LINUXPROBED + LINUXPROBED=$(echo $LINUXPROBED | awk '{ print $1}') + prepare_boot_cache= + # echo "ADV listado de los kerenel encontrados linux-boot-prober ${DEVICE} $LINUXPROBED" + for LINUX in ${LINUXPROBED} ; do + LINUX=$LINUXPROBED + LROOT="`echo ${LINUX} | cut -d ':' -f 1`" + LBOOT="`echo ${LINUX} | cut -d ':' -f 2`" + LLABEL="`echo ${LINUX} | cut -d ':' -f 3 | tr '^' ' '`" + LKERNEL="`echo ${LINUX} | cut -d ':' -f 4`" + LINITRD="`echo ${LINUX} | cut -d ':' -f 5`" + LPARAMS="`echo ${LINUX} | cut -d ':' -f 6- | tr '^' ' '`" + # En los parámetros cambiamos el UUID por el valor de LROOT + UUID=$(blkid -s UUID -o value $LROOT) + LPARAMS="$(echo $LPARAMS | sed "s|UUID=$UUID|$LROOT|g")" + if [ -z "${LLABEL}" ] ; then + LLABEL="${LONGNAME}" + fi + + if [ "${LROOT}" != "${LBOOT}" ]; then + LKERNEL="${LKERNEL#/boot}" + LINITRD="${LINITRD#/boot}" + fi + + found_other_os=1 + LABELCLASS=$(echo "${LLABEL}" | awk '{print tolower($1);}') + cat << EOF menuentry "${LLABEL} (on ${DEVICE})" --class $LABELCLASS --class linux --class os { EOF - save_default_entry | sed -e "s/^/\t/" - if [ -z "${prepare_boot_cache}" ]; then -#ADV prepare_boot_cache="$(prepare_grub_to_access_device ${LBOOT} | sed -e "s/^/\t/")" - prepare_boot_cache="$(OG_prepare_grub_to_access_device ${LBOOT} | sed -e "s/^/\t/")" - fi - printf '%s\n' "${prepare_boot_cache}" - if [ "$LABELCLASS" == "opengnsys" ]; then - KERNELPARAM=$(cat /proc/cmdline) - fi - cat << EOF +save_default_entry | sed -e "s/^/\t/" +if [ -z "${prepare_boot_cache}" ]; then + #ADV prepare_boot_cache="$(prepare_grub_to_access_device ${LBOOT} | sed -e "s/^/\t/")" + prepare_boot_cache="$(OG_prepare_grub_to_access_device ${LBOOT} | sed -e "s/^/\t/")" +fi +printf '%s\n' "${prepare_boot_cache}" +if [ "$LABELCLASS" == "opengnsys" ]; then + KERNELPARAM=$(cat /proc/cmdline) +fi +cat << EOF linux ${LKERNEL} ${LPARAMS} ${KERNELPARAM} EOF - if [ -n "${LINITRD}" ] ; then - cat << EOF +if [ -n "${LINITRD}" ] ; then + cat << EOF initrd ${LINITRD} EOF - fi - cat << EOF + fi + cat << EOF } EOF done - ;; + ;; macosx) - OSXUUID="`grub-probe --target=fs_uuid --device ${DEVICE} 2> /dev/null`" - osx_entry xnu_kernel 32 - osx_entry xnu_kernel64 64 - ;; + OSXUUID="`grub-probe --target=fs_uuid --device ${DEVICE} 2> /dev/null`" + osx_entry xnu_kernel 32 + osx_entry xnu_kernel64 64 + ;; hurd) - found_other_os=1 - cat << EOF + found_other_os=1 + cat << EOF menuentry "${LONGNAME} (on ${DEVICE})" --class hurd --class gnu --class os { EOF - save_default_entry | sed -e "s/^/\t/" - prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" - grub_device="`${grub_probe} --device ${DEVICE} --target=drive`" - mach_device="`echo "${grub_device}" | sed -e 's/(\(hd.*\),msdos\(.*\))/\1s\2/'`" - grub_fs="`${grub_probe} --device ${DEVICE} --target=fs`" - case "${grub_fs}" in +save_default_entry | sed -e "s/^/\t/" +prepare_grub_to_access_device ${DEVICE} | sed -e "s/^/\t/" +grub_device="`${grub_probe} --device ${DEVICE} --target=drive`" +mach_device="`echo "${grub_device}" | sed -e 's/(\(hd.*\),msdos\(.*\))/\1s\2/'`" +grub_fs="`${grub_probe} --device ${DEVICE} --target=fs`" +case "${grub_fs}" in *fs) hurd_fs="${grub_fs}" ;; *) hurd_fs="${grub_fs}fs" ;; - esac - cat << EOF +esac +cat << EOF multiboot /boot/gnumach.gz root=device:${mach_device} module /hurd/${hurd_fs}.static ${hurd_fs} --readonly \\ --multiboot-command-line='\${kernel-command-line}' \\ @@ -453,10 +471,10 @@ EOF module /lib/ld.so.1 exec /hurd/exec '\$(exec-task=task-create)' } EOF - ;; +;; *) - echo " ${LONGNAME} is not yet supported by grub-mkconfig." >&2 - ;; + echo " ${LONGNAME} is not yet supported by grub-mkconfig." >&2 + ;; esac done diff --git a/client/shared/scripts/updateCache b/client/shared/scripts/updateCache index 73086bb7..f1d64adf 100755 --- a/client/shared/scripts/updateCache +++ b/client/shared/scripts/updateCache @@ -223,7 +223,7 @@ case "$PROTOCOLO" in fi ;; MULTICAST) - ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION : $REPOIP:$PORTAUX:$PORT" + ogEcho log session "$MSG_SCRIPTS_UPDATECACHE_CHECKMCASTSESSION: $REPOIP:${OPTPROTOCOLO%%:*}" #TODO: ticket 379 NUMBER=$[ ( $RANDOM % 30 ) + 1 ] sleep $NUMBER diff --git a/doc/CHANGELOG.es.txt b/doc/CHANGELOG.es.txt index 4908db14..fd28330e 100644 --- a/doc/CHANGELOG.es.txt +++ b/doc/CHANGELOG.es.txt @@ -1,7 +1,22 @@ + LISTA DE CAMBIOS CHANGELOG.es.txt ======================================== +Lista de cambios incluidos en OpenGnsys 1.1.1a (versión de mantenimiento) +---------------------------------------------- + +Tickets resueltos en módulo OpenGnsys Cloning Engine: +#935 ogGrub4dosInstallMbr nueva función para arranques de MBR y discos PCIe (NVMe) + +Tickets resueltos en módulo OpenGnsys Web Admin Console: +#934 Netboot Avanzado no filtra correctamente el ámbito grupo de ordenadores (corrección) +#936 Asistente deploy muestra particiones destino duplicadas (corrección) +#937 Particiones remotas debe soportar la clonación de particiones en en un segundo disco duro + +Tickets genéricos resueltos: +#939 Subir documentación curso básico 1.1.0a + Lista de cambios incluidos en OpenGnsys 1.1.1 (Espeto) ------------------------------------------------------ @@ -20,6 +35,7 @@ Tickets resueltos en módulo OpenGnsys Cloning Engine: #920 Error al guardar en la BD el número de serie (corrección) #923 Mejora de control de errores en deployImagen (corrección) #926 bootOsCustom soportará varios discos y una partición de datos +#931 Fallo en el inventario Software (corrección) Tickets resueltos en módulo OpenGnsys Client: #847 La ISO del ogLive debe de utilzar la revisión de Git y no de SVN @@ -46,8 +62,13 @@ Tickets resueltos en módulo OpenGnsys Server: #892 Usar Wake-On-Lan en ogAdmServer y en repositorio #897 No usar tipo socket en ogAdmServer #898 Eliminar rutinas obsoletas de encriptación y desencriptación +#896 Enviar Wake On Lan por la interfaz correcta #899 Eliminar código obsoleto en ogAdmLib #900 Fichero de configuración unificado (duplicado de #140) +#915 API REST para ogAdmServer (tarea) +#924 ogAdmServer: Aunque la restauración falle se modifica la configuración del equipo (corrección) +#925 Script para generar API tokens de servicios +#929 Autenticación de clave pública entre los ogLive Tickets resueltos en módulo OpenGnsys Web Admin Console: #772 Módulo de administración web para dispositivos smartphones y tablets (no se resolverá) @@ -60,6 +81,7 @@ Tickets resueltos en módulo OpenGnsys Web Admin Console: #903 Formulario "Añadir Nuevo Ordenador" no valida dirección MAC (corrección) #921 Cola de acciones: no muestra nada (corrección) #928 Multicast: ampliar el rango de puertos posibles (mejora) +#932 Remote PC no arranca equipos en repositorio secundario (corrección) Tickets resueltos en módulo OpenGnsys Installer: #784 Mejorar rendimiento de PHP sobre Apache @@ -70,6 +92,7 @@ Tickets resueltos en módulo OpenGnsys Installer: Tickets genéricos resueltos: #785 Usar Grub2 como gestor PXE para soporte UEFI (tarea) #802 Gestión equipos UEFI (tarea) +#914 Liberar versión OpenGnsys 1.1.1 Espeto (tarea) #917 Problemas de compatibilidad con Ubuntu 18.04 (corrección) diff --git a/doc/COMPATIBILITY.en.txt b/doc/COMPATIBILITY.en.txt index 0e79796e..03f81c55 100644 --- a/doc/COMPATIBILITY.en.txt +++ b/doc/COMPATIBILITY.en.txt @@ -10,7 +10,7 @@ Installation of OpenGnsys services has been tested on the following GNU/Linux di - Ubuntu Server 18.04 LTS 64-bit (recommended) - Ubuntu Server 16.04 LTS 64-bit (not fully tested) - - CentOS 7.5 64-bit (not fully tested) + - CentOS 7.x 64-bit (not fully tested) OpenGnsys Clients @@ -18,8 +18,8 @@ OpenGnsys Clients Installation and cloning operations have been tested on the following operating systems and filesystems: - - Ubuntu Desktop 16.04.4 64-bit and 18.04.1 64-bit with Ext4 filesystem and Swap partition + - Ubuntu Desktop 14.04 LTS 64-bit, 16.04 LTS 64-bit and 18.04 LTS 64-bit with Ext4 filesystem and Swap partition - Windows 7 Enterprise 64-bit with NTFS filesystem - - Windows 10 Education 1709 64-bit and 1803 64-bit with NTFS filesystem + - Windows 10 Education 1709 64-bit, 1803 64-bit, 1809 64-bit and 1903 64-bit with NTFS filesystem diff --git a/doc/INSTALL.en.txt b/doc/INSTALL.en.txt index fac27547..84492e6e 100644 --- a/doc/INSTALL.en.txt +++ b/doc/INSTALL.en.txt @@ -1,10 +1,10 @@ -Installing OpenGnsys Server 1.1.0 -================================= +Installing OpenGnsys Server 1.1.1 (Espeto) +========================================== Before installation ------------------- -OpenGnsys Server 1.1.0 is meant to be installed under Ubuntu Server 16.04 LTS or newer, though it has also been tested under operating systems based on CentOS 7. +OpenGnsys Server 1.1.1 (codename Espeto) is meant to be installed under Ubuntu Server 18.04 LTS or newer (some tests have been done on CentOS 7-based systems). Network connection is needed in order to download the required packages, the source code and the preconfigured client. @@ -22,16 +22,16 @@ Installing To install OpenGnsys, run opengnsys_installer.sh script after unpacking the release file (opengnsys-release.tar.gz) or after downloading it directly from https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh Unpacking example: - tar xvzf opengnsys-Version.tar.gz + tar xvzf opengnsys-VERSION.tar.gz cd opengnsys/installer Downloading examples: * Download with wget. - wget https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh + wget https://raw.githubusercontent.com/opengnsys/OpenGnsys/VERSION/installer/opengnsys_installer.sh * Download with curl. - curl https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh -o opengnsys_installer.sh + curl https://raw.githubusercontent.com/opengnsys/OpenGnsys/VERSION/installer/opengnsys_installer.sh -o opengnsys_installer.sh You must be root to run the installation script: @@ -71,6 +71,8 @@ Once the installation process is finished, you can start working with the system Updating / upgrading -------------------- +Warning: if you are going to upgrade OpenGnsys from a version earlier than 1.1.1 (Espeto), you must first upgrade Ubuntu to version 18.04 LTS and restart the server. + There is a system self-upgrading script with the following features: * Network connection is needed to obtain the latest updates / upgrades. * If the script updates itself, then it must be run once again. diff --git a/doc/INSTALL.es.txt b/doc/INSTALL.es.txt index 7fd679de..a8fd4e00 100644 --- a/doc/INSTALL.es.txt +++ b/doc/INSTALL.es.txt @@ -1,10 +1,10 @@ -Instalación de OpenGnsys Server 1.1.0 -===================================== +Instalación de OpenGnsys Server 1.1.1 (Espeto) +============================================== Notas iniciales --------------- -Se presupone que el servidor de OpenGnsys 1.1.0 va a ser instalado en una distribución del sistema operativo Ubuntu Server a partir de la versión 16.04 LTS (también ha sido probado en sistemas basados en CentOS 7). +Se presupone que el servidor de OpenGnsys 1.1.1 (Espeto) va a ser instalado en una distribución del sistema operativo Ubuntu Server a partir de la versión 18.04 LTS (se han hecho algunas pruebas en sistemas basados en CentOS 7). El serividor debe tener acceso a Internet para descargar los paquetes necesarios, el código del proyecto y el cliente preconfigurado. @@ -22,16 +22,16 @@ La instalación de OpenGnsys se realiza ejecutando el script de instalación ope Ejemplos de descompresión del programa: - tar xvzf opengnsys-Version.tar.gz + tar xvzf opengnsys-VERSION.tar.gz cd opengnsys/installer Ejemplos de descarga con varias herramientas: * Descargar con wget. - wget https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh + wget https://raw.githubusercontent.com/opengnsys/OpenGnsys/VERSION/installer/opengnsys_installer.sh * Descargar con curl. - curl https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh -o opengnsys_installer.sh + curl https://raw.githubusercontent.com/opengnsys/OpenGnsys/VERSION/installer/opengnsys_installer.sh -o opengnsys_installer.sh El script de instalación debe ser ejecutado como usuario root: @@ -71,6 +71,8 @@ Una vez finalizada la ejecución del instalador, puede empezarse a trabajar con Actualización ------------- +Nota importante: si se va a actualizar OpenGnsys desde una versión anterior a la 1.1.1 (Espeto), debe actualizarse antes la distribución de Ubuntu a la versión 18.04 LTS y reiniciar el servidor. + Se dispone de un script de auto-actualización del sistema, con las siguientes características: * Es necesario conexión a Internet para obtener las últimas actualizaciones. * Si el script se actualiza a sí mismo, debe ser ejecutado de nuevo. diff --git a/doc/userManual/Tema0-Laboratorio_virtual.pdf b/doc/userManual/Tema0-Laboratorio_virtual.pdf Binary files differindex 3eacafb0..9bf32595 100644..100755 --- a/doc/userManual/Tema0-Laboratorio_virtual.pdf +++ b/doc/userManual/Tema0-Laboratorio_virtual.pdf diff --git a/doc/userManual/Tema1-Introduccion.pdf b/doc/userManual/Tema1-Introduccion.pdf Binary files differindex eed9744f..97120043 100644..100755 --- a/doc/userManual/Tema1-Introduccion.pdf +++ b/doc/userManual/Tema1-Introduccion.pdf diff --git a/doc/userManual/Tema2-Instalacion.pdf b/doc/userManual/Tema2-Instalacion.pdf Binary files differindex 1ab9461f..6311ae0c 100644..100755 --- a/doc/userManual/Tema2-Instalacion.pdf +++ b/doc/userManual/Tema2-Instalacion.pdf diff --git a/doc/userManual/Tema3.1-Administracion_componentes.pdf b/doc/userManual/Tema3.1-Administracion_componentes.pdf Binary files differindex 69e1d4f7..c43eff3e 100644..100755 --- a/doc/userManual/Tema3.1-Administracion_componentes.pdf +++ b/doc/userManual/Tema3.1-Administracion_componentes.pdf diff --git a/doc/userManual/Tema3.2-Administracion_consola_web.pdf b/doc/userManual/Tema3.2-Administracion_consola_web.pdf Binary files differindex 26aad817..c84aed81 100644..100755 --- a/doc/userManual/Tema3.2-Administracion_consola_web.pdf +++ b/doc/userManual/Tema3.2-Administracion_consola_web.pdf diff --git a/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf b/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf Binary files differindex 1828aa49..7c46a9b5 100644..100755 --- a/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf +++ b/doc/userManual/Tema3.3-Administracion_unidad_organizativa.pdf diff --git a/doc/userManual/Tema4-Ambito_aplicacion.pdf b/doc/userManual/Tema4-Ambito_aplicacion.pdf Binary files differindex 1989899d..1b505e6e 100644..100755 --- a/doc/userManual/Tema4-Ambito_aplicacion.pdf +++ b/doc/userManual/Tema4-Ambito_aplicacion.pdf diff --git a/doc/userManual/Tema5-Particionado_discos.pdf b/doc/userManual/Tema5-Particionado_discos.pdf Binary files differindex d5fbdbcd..0eb5d389 100644..100755 --- a/doc/userManual/Tema5-Particionado_discos.pdf +++ b/doc/userManual/Tema5-Particionado_discos.pdf diff --git a/doc/userManual/Tema6.1-Creacion_imagenes.pdf b/doc/userManual/Tema6.1-Creacion_imagenes.pdf Binary files differindex 94c4ae26..04569346 100644..100755 --- a/doc/userManual/Tema6.1-Creacion_imagenes.pdf +++ b/doc/userManual/Tema6.1-Creacion_imagenes.pdf diff --git a/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf b/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf Binary files differindex 3e5df4e3..c1029659 100644..100755 --- a/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf +++ b/doc/userManual/Tema6.2-Restauracion_y_despliegue_imagenes.pdf diff --git a/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf b/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf Binary files differindex 592cb324..f5c3df35 100644..100755 --- a/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf +++ b/doc/userManual/Tema6.3-Eliminacion_imagenes.pdf diff --git a/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf b/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf Binary files differindex fb59c355..fb59c355 100644..100755 --- a/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf +++ b/doc/userManual/Tema7-Acciones_y_menus_usuario.pdf diff --git a/installer/README.es.txt b/installer/README.es.txt index 0642e4ed..cb6f36c1 100644 --- a/installer/README.es.txt +++ b/installer/README.es.txt @@ -25,5 +25,3 @@ eliminar el Proyecto OpenGnsys. - vagrant directorio con ficheros de configuración para despliegue de entornos de prueba y desarrollo con Vagrant -- install_ticket_wolunicast.sh programa de instalación del parche para ejecutar - arranque Wake-On-Lan por IP usando protocolo Unicast diff --git a/installer/ogagent-devel-installer.sh b/installer/ogagent-devel-installer.sh index 71f7c7c0..201e67f9 100755 --- a/installer/ogagent-devel-installer.sh +++ b/installer/ogagent-devel-installer.sh @@ -12,8 +12,8 @@ # Variables. PROGDIR="$PWD/ogagent" -BRANCH="branches/devel" -SVNURL="https://github.com/opengnsys/OpenGnsys/$BRANCH/admin/Sources/Clients/ogagent" +BRANCH="master" +SVNURL="https://github.com/opengnsys/OpenGnsys/branches/$BRANCH/admin/Sources/Clients/ogagent" # Show prerequisites needed to build the environment. mkdir -p $PROGDIR || exit 1 diff --git a/installer/opengnsys_import.sh b/installer/opengnsys_import.sh index 528b8c3e..e2f13d50 100755 --- a/installer/opengnsys_import.sh +++ b/installer/opengnsys_import.sh @@ -35,8 +35,8 @@ MYSQLFILE="$TMPDIR/$CATALOG.sql" MYSQLBCK="$OPENGNSYS/doc/$CATALOG.sql-$DATE" LOG_FILE=$OPENGNSYS/log/${PROG%.sh}.log -BRANCH="branches/devel" -SVN_URL="https://github.com/opengnsys/OpenGnsys/$BRANCH/admin/Database" +BRANCH="master" +SVN_URL="https://github.com/opengnsys/OpenGnsys/branches/$BRANCH/admin/Database" DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot" # Clave por defecto root de MySQL # Si se solicita, mostrar ayuda. @@ -327,8 +327,6 @@ if [ -f $OPENGNSYS/tftpboot/menu.lst/templates/01 ]; then BIOSPXEDIR="$OPENGNSYS/tftpboot/menu.lst/templates" mv $BIOSPXEDIR/01 $BIOSPXEDIR/10 sed -i "s/\bMBR\b/1hd/" $BIOSPXEDIR/10 - sed -i "s/\b1hd-1partition\b/1hd-1os/" $BIOSPXEDIR/11 - sed -i "s/\b1hd-2partition\b/1hd-2os/" $BIOSPXEDIR/12 # Cambiamos el valor en la base de datos. Si no lo hacemos desaparecen de las columnas del NetBootAvanzado. mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e "update ordenadores set arranque='10' where arranque='01';" &>/dev/null diff --git a/installer/opengnsys_installer.sh b/installer/opengnsys_installer.sh index 89c94082..95cd86ea 100755 --- a/installer/opengnsys_installer.sh +++ b/installer/opengnsys_installer.sh @@ -132,9 +132,9 @@ function globalSetup () else REMOTE=1 fi - BRANCH="devel" + BRANCH="master" CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH" - API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH" + API_URL="https://api.github.com/repos/opengnsys/OpenGnsys" # Directorios de instalación y destino de OpenGnsys. WORKDIR=/tmp/opengnsys_installer @@ -189,7 +189,7 @@ OSVERSION="${OSVERSION%%.*}" # Configuración según la distribución GNU/Linux (usar minúsculas). case "$OSDISTRIB" in ubuntu|debian|linuxmint) - DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev shim-signed grub-efi-amd64-signed ) + DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev libssl-dev shim-signed grub-efi-amd64-signed gawk ) UPDATEPKGLIST="apt-get update" INSTALLPKG="apt-get -y install --force-yes" CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install" @@ -226,7 +226,7 @@ case "$OSDISTRIB" in TFTPCFGDIR=/var/lib/tftpboot ;; fedora|centos) - DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++-devel.i686 make wget curl doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm ) + DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++-devel.i686 make wget curl doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules gawk http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm ) [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm" INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://ftp.acc.umu.se/mirror/bittornado/BitTornado-0.3.18.tar.gz && tar xvzf BitTornado-0.3.18.tar.gz && cd BitTornado-CVS && python setup.py install && ln -fs btlaunchmany.py /usr/bin/btlaunchmany && ln -fs bttrack.py /usr/bin/bttrack; popd' ) INSTALLPKG="yum install -y libstdc++ libstdc++.i686" @@ -692,9 +692,6 @@ function mysqlImportSqlFileToDb() local i=0 local dev="" local status - # Claves aleatorias para acceso a las APIs REST. - local OPENGNSYS_APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') - OPENGNSYS_REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));') if [ ! -f $sqlfile ]; then errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!" @@ -708,8 +705,6 @@ function mysqlImportSqlFileToDb() sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \ - -e "s/APIKEY/$OPENGNSYS_APIKEY/g" \ - -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \ $sqlfile > $tmpfile fi let i++ @@ -838,10 +833,12 @@ function checkNetworkConnection() { echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity." OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"} - if which wget &>/dev/null; then - wget --spider -q $OPENGNSYS_SERVER - elif which curl &>/dev/null; then - curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null + if which curl &>/dev/null; then + curl --connect-timeout 10 -s "https://$OPENGNSYS_SERVER/" -o /dev/null && \ + curl --connect-timeout 10 -s "http://$OPENGNSYS_SERVER/" -o /dev/null + elif which wget &>/dev/null; then + wget --spider -q "https://$OPENGNSYS_SERVER/" && \ + wget --spider -q "http://$OPENGNSYS_SERVER/" else echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"." return 1 @@ -1492,10 +1489,8 @@ function openGnsysConfigure() -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \ -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \ - -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \ $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ - -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \ $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg sed -e "s/SERVERIP/${SERVERIP[i]}/g" \ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ @@ -1544,9 +1539,17 @@ EOT $DISABLESERVICE fi - echoAndLog "${FUNCNAME}(): Starting OpenGnsys services." + # Actualizar tokens de autenticación e iniciar los servicios. service="opengnsys" - $ENABLESERVICE; $STARTSERVICE + $ENABLESERVICE + if [ -x $INSTALL_TARGET/bin/settoken ]; then + echoAndLog "${FUNCNAME}(): Setting authentication tokens and starting OpenGnsys services." + $INSTALL_TARGET/bin/settoken "$OPENGNSYS_DB_USER" + $INSTALL_TARGET/bin/settoken -f + else + echoAndLog "${FUNCNAME}(): Starting OpenGnsys services." + $STARTSERVICE + fi } @@ -1565,8 +1568,10 @@ function installationSummary() # de código o si no está incluida en el fichero de versión. if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit). - REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])') - jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE + RELEASE=$(curl -s "$API_URL/branches/$BRANCH" | jq -r '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])' 2>/dev/null) + # Obtener revisión para etiqueta de versión en vez de rama de código. + [ -z "$RELEASE" ] && RELEASE=$(curl -s $(curl -s "$API_URL/tags" | jq -r ".[] | select(.name==\"$BRANCH\").commit.url" 2>/dev/null) | jq -r '"r" + (.commit.committer.date | split("-") | join("")[:8]) + "." + .sha[:7]' 2>/dev/null) + jq ".release=\"$RELEASE\"" $VERSIONFILE | sponge $VERSIONFILE fi VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)" @@ -1580,7 +1585,7 @@ function installationSummary() echoAndLog "Repository directory: $INSTALL_TARGET/images" echoAndLog "DHCP configuration directory: $DHCPCFGDIR" echoAndLog "TFTP configuration directory: $TFTPCFGDIR" - echoAndLog "Installed ogLive client(s): $(oglivecli list | awk '{print $2}')" + echoAndLog "Installed ogLive client: $(oglivecli list | awk '{print $2}')" echoAndLog "Samba configuration directory: $SAMBACFGDIR" echoAndLog "Web Console URL: $OPENGNSYS_CONSOLEURL" echoAndLog "Web Console access data: entered by the user" @@ -1595,6 +1600,8 @@ function installationSummary() echoAndLog "It's strongly recommended to synchronize this server with an NTP server." echoAndLog "Review or edit all configuration files." echoAndLog "Insert DHCP configuration data and restart service." + echoAndLog "Optional: If you want to use BURG as boot manager, run" + echoAndLog " \"curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz\" as root." echoAndLog "Optional: Log-in as Web Console admin user." echoAndLog " - Review default Organization data and assign access to users." echoAndLog "Log-in as Web Console organization user." @@ -1615,6 +1622,12 @@ if [ "$(whoami)" != 'root' ]; then fi globalSetup +# Comprobar instalación previa. +if cat $INSTALL_TARGET/doc/VERSION.* &>/dev/null; then + echo "ERROR: OpenGnsys is already installed. Run \"$INSTALL_TARGET/lib/opengnsys_update.sh\" as root to update." + exit 2 +fi + echoAndLog "OpenGnsys installation begins at $(date)" # Introducir datos de configuración y establecer variables globales. userData diff --git a/installer/opengnsys_makecompress.sh b/installer/opengnsys_makecompress.sh index 6b09deb5..a15d5434 100755 --- a/installer/opengnsys_makecompress.sh +++ b/installer/opengnsys_makecompress.sh @@ -21,7 +21,7 @@ for PROG in jq unzip; do done # Variables. -BRANCH="devel" +BRANCH="master" CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH" API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH" REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])') diff --git a/installer/opengnsys_update.sh b/installer/opengnsys_update.sh index a59e1d99..55620b05 100755 --- a/installer/opengnsys_update.sh +++ b/installer/opengnsys_update.sh @@ -73,7 +73,7 @@ if [ -d "$PROGRAMDIR/../installer" ]; then else REMOTE=1 fi -BRANCH="devel" +BRANCH="master" CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH" API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH" RAW_URL="https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH" @@ -118,7 +118,7 @@ function autoConfigure() # Configuración según la distribución de Linux. if [ -f /etc/debian_version ]; then # Distribución basada en paquetes Deb. - DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev shim-signed grub-efi-amd64-signed php-fpm ) + DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev libssl-dev shim-signed grub-efi-amd64-signed php-fpm gawk ) # Paquete correcto para realpath. [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} ) UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update" @@ -143,7 +143,7 @@ function autoConfigure() INETDCFGDIR=/etc/xinetd.d elif [ -f /etc/redhat-release ]; then # Distribución basada en paquetes rpm. - DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules ) + DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules gawk ) # Repositorios para PHP 7 en CentOS. [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum update -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm" INSTALLPKGS="yum install -y" @@ -301,7 +301,6 @@ function importSqlFile() local tmpfile=$(mktemp) local mycnf=/tmp/.my.cnf.$$ local status - local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') if [ ! -r $sqlfile ]; then errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!" @@ -311,8 +310,7 @@ function importSqlFile() echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..." chmod 600 $tmpfile sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \ - -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \ - -e "s/APIKEY/$APIKEY/g" -e "s/REPOKEY/$REPOKEY/g" $sqlfile > $tmpfile + -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile # Componer fichero con credenciales de conexión. touch $mycnf chmod 600 $mycnf @@ -452,9 +450,11 @@ function checkNetworkConnection() { OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"} if which curl &>/dev/null; then - curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null + curl --connect-timeout 10 -s "https://$OPENGNSYS_SERVER" -o /dev/null && \ + curl --connect-timeout 10 -s "http://$OPENGNSYS_SERVER" -o /dev/null elif which wget &>/dev/null; then - wget --spider -q $OPENGNSYS_SERVER + wget --spider -q "https://$OPENGNSYS_SERVER" && \ + wget --spider -q "http://$OPENGNSYS_SERVER" else echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"." return 1 @@ -847,7 +847,6 @@ function updateDatabase() fi popd >/dev/null - REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));') if [ -n "$FILES" ]; then for file in $FILES; do importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file @@ -944,8 +943,6 @@ function updateServerFiles() BIOSPXEDIR="$INSTALL_TARGET/tftpboot/menu.lst/templates" mv $BIOSPXEDIR/01 $BIOSPXEDIR/10 sed -i "s/\bMBR\b/1hd/" $BIOSPXEDIR/10 - sed -i "s/\b1hd-1partition\b/1hd-1os/" $BIOSPXEDIR/11 - sed -i "s/\b1hd-2partition\b/1hd-2os/" $BIOSPXEDIR/12 fi } @@ -988,10 +985,8 @@ function compileServices() hayErrores=1 fi popd - # Parar antiguo servicio de repositorio y añadir clave de acceso REST en su fichero de configuración. + # Parar antiguo servicio de repositorio. pgrep ogAdmRepo > /dev/null && service="ogAdmRepo" $STOPSERVICE - sed -i -n -e "/^ApiToken=/!p" -e "$ a\ApiToken=$REPOKEY" $INSTALL_TARGET/etc/ogAdmRepo.cfg - sed -i -n -e "/^APITOKEN=/!p" -e "$ a\APITOKEN=$REPOKEY" $INSTALL_TARGET/etc/ogAdmServer.cfg # Compilar OpenGnsys Agent echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Server Agent" pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent @@ -1144,7 +1139,7 @@ function updateSummary() fi echoAndLog "Warnings:" echoAndLog " - You must to clear web browser cache before loading OpenGnsys page" - echoAndLog " - Generated new key to access Repository REST API (file ogAdmRepo.cfg)" + echoAndLog " - Run \"settoken\" script to update authentication tokens" if [ -n "$INSTALLEDOGLIVE" ]; then echoAndLog " - Installed new ogLive Client: $INSTALLEDOGLIVE" fi @@ -1152,6 +1147,9 @@ function updateSummary() echoAndLog " - MySQL must be reconfigured, run next code as DB root user and restart service:" echoAndLog " $MYSQLCONFIG" fi + echoAndLog " - If you want to use BURG as boot manager, run following command as root:" + echoAndLog " curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz" + echo } @@ -1190,7 +1188,7 @@ if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then checkAutoUpdate if [ $? -ne 0 ]; then echoAndLog "OpenGnsys updater has been overwritten" - echoAndLog "Please, rerun this script" + echoAndLog "Please, run this script again" exit fi fi diff --git a/installer/vagrant/README.es.txt b/installer/vagrant/README.es.txt index 6f300afe..bc5888fe 100644 --- a/installer/vagrant/README.es.txt +++ b/installer/vagrant/README.es.txt @@ -5,7 +5,7 @@ Preparar entorno virtual de desarrollo para OpenGnsys Ficheros de configuración disponibles: - - Vagrantfile-prod-vbox Vagrantfile para OpenGnsys estable con proveedor VirtualBox. + - Vagrantfile-prod-vbox Vagrantfile para OpenGnsys última versión estable con proveedor VirtualBox. - Vagrantfile-devel-vbox Vagrantfile para OpenGnsys en desarrollo con proveedor VirtualBox. - Vagrantfile-boottools-vbox Vagrantfile para preparar el entorno de generación del cliente ogLive (recomendado solo para desarrolladores experimentados). - Vagrantfile-browser-vbox Vagrantfile para preparar el entorno de desarrollo del Browser del cliente (recomendado solo para miembros del grupo de desarrollo). @@ -14,15 +14,15 @@ Ficheros de configuración disponibles: Requisitos previos. - - Instalar Oracle VM VirtualBox 5.x con su Extension Pack. - - Instalar la última versión oficial de Vagrant (no usar la incluida en Ubuntu 14.04). + - Instalar Oracle VM VirtualBox con su Extension Pack. + - Instalar la última versión oficial de Vagrant. El entorno de trabajo de OpenGnsys. - ogAdministrator: MV para servidor OpenGnsys basada en Ubuntu 16.04 y 2º disco para repositorio. - pc11: MV cliente mlodelo con Ubuntu 16.04 instalado. - - pc12 - ogclientN: MV clientes para restaurar con disco vacío. + - pc12 - pcX: MV clientes para restaurar con disco vacío. Ejecutar el entorno virtual (Vagrantfile-prod-vbox y Vagrantfile-devel-vbox). diff --git a/installer/vagrant/Vagrantfile-1.1.0a-vbox b/installer/vagrant/Vagrantfile-1.1.0a-vbox new file mode 100644 index 00000000..07d43556 --- /dev/null +++ b/installer/vagrant/Vagrantfile-1.1.0a-vbox @@ -0,0 +1,170 @@ +# Vagrantfile to install OpenGnsys virtual environment (production version) using VirtualBox provider. + +VAGRANTFILE_API_VERSION = "2" +# VM provider: Oracle VM VirtualBox. +ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# Language (accepted values: es_ES, ca_ES, en_GB). +LANGUAGE = "es_ES" +ENV['LC_ALL'] = LANGUAGE + ".UTF-8" +# Number of OpenGnsys clients (accepted values: from 2 to 9). +NCLIENTS = 4 +# Repository virtual disk: file and size (GB). +REPODISK = "ogRepo.vdi" +REPOSIZE = 50 +# Amount of memory for server and clients (MB) +SERVERMEM = 1024 # Minimum: 512 +CLIENTMEM = 512 # Minimum: 256 +# Prefixes for MAC and IP addresses. +MACPREFIX = "08:00:27:0E:65" +NETPREFIX = "192.168.2" +# OpenGnsys Server IP address. +SERVERIP = "#{NETPREFIX}.10" +# Local port to access OpenGnsys Server. +LOCALWEBPORT = 8443 + +# OpenGnsys Server provisioning script: prepare repo disk, install OpenGnsys, change default interface, configure DHCP server. +OGSERVERSCRIPT = <<EOT +# Exit if OpenGnsys is installed. +[ -f /opt/opengnsys/doc/VERSION.json ] && echo "Cannot provision, OpenGnsys is already installed." && exit 1 +# Create repository disk using LVM, if necesary. +if [ -z "$(blkid /dev/mapper/og-images | grep ext4)" ]; then + pvcreate /dev/sdb + vgcreate og /dev/sdb + vgchange -ay + lvcreate -ay -n images -l 100%VG og + mkfs -t ext4 /dev/mapper/og-images + mkdir -p /opt/opengnsys/images + echo "/dev/mapper/og-images /opt/opengnsys/images ext4 defaults 0 0" >> /etc/fstab + mount -a +fi +# Install OpenGnsys and change server address. +if which curl &>/dev/null; then + DOWNLOAD="curl -s" +elif which wget &>/dev/null; then + DOWNLOAD="wget -q -O -" +fi +BRANCH="opengnsys-1.1.0a" +$DOWNLOAD https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH/installer/opengnsys_installer.sh | bash || exit $? +mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log +echo y | /opt/opengnsys/bin/setserveraddr $(ip -o link show | tail -1 | cut -d: -f2) +# Insert DHCP data. +for ((i=#{NCLIENTS+10}; i>10; i--)); do + sed -i "/^}$/ i host pc${i} { hardware ethernet #{MACPREFIX}:${i}; fixed-address #{NETPREFIX}.${i}; }" /etc/dhcp/dhcpd.conf +done +service isc-dhcp-server restart +# Set language. +export LANG="#{LANGUAGE}.UTF-8" +echo "LANG=\\\"$LANG\\\"" > /etc/default/locale +echo "LANG=\\\"$LANG\\\"" >> /etc/environment +locale-gen --lang #{LANGUAGE} +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\\\"${LANG%_*}\\\"/" /etc/default/keyboard +dpkg-reconfigure -fnoninteractive console-setup +# Comment out next lines for automatic data insertion. +#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, ntp, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" +#for ((i=11; i<=#{NCLIENTS+10}; i++)); do +# SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," +#done +#mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" +#/opt/opengnsys/bin/setclientmode ogLiveAdmin pc11 PERM +#for ((i=12; i<=#{NCLIENTS+10}; i++)); do +# /opt/opengnsys/bin/setclientmode ogLive pc$i PERM +#done +echo "Notes:" +echo "- OpenGnsys Server URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +exit 0 +EOT + +# Client 1 OS provisioning script. +OGAGENTPKG = "ogagent_1.1.0_all.deb" +MODELSCRIPT = <<EOT +# Comment out next lines to install and configure OGAgent for Ubuntu. +#apt-get update -y +#apt-get install -y curl +#curl -ks https://#{SERVERIP}/opengnsys/descargas/#{OGAGENTPKG} -o /tmp/#{OGAGENTPKG} +#if [ -f /tmp/#{OGAGENTPKG} ]; then +# apt-get install -y /tmp/#{OGAGENTPKG} || exit $? +# sed -i "0,/remote=/ s,remote=.*,remote=https://#{SERVERIP}/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg +# rm -f /tmp/#{OGAGENTPKG} +#else +# echo "Warning: cannot install OGAgent package #{OGAGENTPKG}" +#fi +# Remove network configuration added by Vagrant. +sed -i "/enp0s3/ d" /etc/network/interfaces +echo "Notes:" +echo "- After now, use VirtualBox GUI to disable network interface 1 and restart this VM." +# Leave VM halted. +sleep 2 +poweroff & +EOT + +Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| + + # OpenGnsys Server VM definition. + config.vm.define "ogAdministrator", primary: true do |og| + # Specific VirtualBox configuration. + og.vm.provider "virtualbox" do |vb| + # VM name, memory and CPUs. + vb.name = "ogAdministrator" + vb.memory = SERVERMEM + vb.cpus = 1 + # 2nd virtual disk path (current dir on Windows, VM dir on other OSes) + if Vagrant::Util::Platform.windows? then + second_disk = File.join(".", REPODISK) + else + line = `VBoxManage list systemproperties`.match("Default machine folder.*")[0] + vb_machine_folder = line.split(':')[1].strip() + second_disk = File.join(vb_machine_folder, vb.name, REPODISK) + end + # Create repo virtual disk, if needed. + unless File.exist?(second_disk) + vb.customize ['createhd', '--filename', second_disk, '--size', REPOSIZE * 1024] + end + # Attach repo virtual disk. + vb.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', second_disk] + end + # VM base and host name. + og.vm.box = "bento/ubuntu-16.04" + og.vm.hostname = "ogAdministrator" + # Network configuration: forward web port and attach new interface to VMs private network. + og.vm.network "forwarded_port", guest: 443, host: LOCALWEBPORT, host_ip: "127.0.0.1" + og.vm.network "private_network", mac: "#{MACPREFIX}10".tr(":",""), ip: "#{SERVERIP}", virtualbox__intnet: true + # Comment out to disable synced folder. + #og.vm.synced_folder ".", "/vagrant", disabled: true + # Launch provisioning script. + og.vm.provision "shell", inline: OGSERVERSCRIPT + end + + # Client 1 VM definition. + config.vm.define "pc11", autostart: false do |v1| + v1.vm.box = "bento/ubuntu-16.04" + v1.vm.hostname = "pc11" + v1.vm.network "private_network", mac: "#{MACPREFIX}11".tr(":",""), type: "dhcp", virtualbox__intnet: true + v1.vm.provider "virtualbox" do |vb| + vb.name = "pc11" + vb.memory = CLIENTMEM + vb.cpus = 1 + vb.customize ['modifyvm', :id, '--boot1', 'net', '--boot2', 'disk'] + end + v1.vm.synced_folder ".", "/vagrant", disabled: true + v1.vm.provision "shell", inline: MODELSCRIPT + end + + # Clonable clients definition. + (2..NCLIENTS).each do |i| + config.vm.define "pc#{i+10}", autostart: false do |cl| + cl.vm.box = "clink15/pxe" + cl.ssh.insert_key = false + cl.vm.boot_timeout = 5 + cl.vm.network "private_network", mac: "#{MACPREFIX}#{i+10}".tr(":",""), type: "dhcp", virtualbox__intnet: true + cl.vm.provider "virtualbox" do |vb| + vb.name = "pc#{i+10}" + vb.memory = CLIENTMEM + vb.cpus = 1 + vb.customize ['modifyvm', :id, '--boot1', 'net', '--boot2', 'disk'] + vb.customize ["modifyvm", :id, "--nic1", "none"] + end + end + end + +end + diff --git a/installer/vagrant/Vagrantfile-1.0.6b-vbox b/installer/vagrant/Vagrantfile-1.1.1-vbox index 4317c654..7d4fb45c 100644 --- a/installer/vagrant/Vagrantfile-1.0.6b-vbox +++ b/installer/vagrant/Vagrantfile-1.1.1-vbox @@ -1,8 +1,10 @@ -# Vagrantfile to install old OpenGnSys 1.0.6b virtual environment using VirtualBox provider. +# Vagrantfile to install OpenGnsys virtual environment (production version) using VirtualBox provider. VAGRANTFILE_API_VERSION = "2" # VM provider: Oracle VM VirtualBox. ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" +# OpenGnsys version +OGVERSION="1.1.1" # Language (accepted values: es_ES, ca_ES, en_GB). LANGUAGE = "es_ES" ENV['LC_ALL'] = LANGUAGE + ".UTF-8" @@ -14,9 +16,11 @@ REPOSIZE = 50 # Amount of memory for server and clients (MB) SERVERMEM = 1024 # Minimum: 512 CLIENTMEM = 512 # Minimum: 256 -# Clients MAC address prefix. +# Prefixes for MAC and IP addresses. MACPREFIX = "08:00:27:0E:65" NETPREFIX = "192.168.2" +# OpenGnsys Server IP address. +SERVERIP = "#{NETPREFIX}.10" # Local port to access OpenGnsys Server. LOCALWEBPORT = 8443 @@ -26,10 +30,6 @@ OGSERVERSCRIPT = <<EOT [ -f /opt/opengnsys/doc/VERSION.txt ] && echo "Cannot provision, OpenGnsys is already installed." && exit 1 # Create repository disk using LVM, if necesary. if [ -z "$(blkid /dev/mapper/og-images | grep ext4)" ]; then - if ! which vgcreate &>/dev/null; then - apt-get update - apt-get install -y lvm2 - fi pvcreate /dev/sdb vgcreate og /dev/sdb vgchange -ay @@ -40,7 +40,13 @@ if [ -z "$(blkid /dev/mapper/og-images | grep ext4)" ]; then mount -a fi # Install OpenGnsys and change server address. -wget -q https://opengnsys.es/svn/tags/opengnsys-1.0.6b/installer/opengnsys_installer.sh -O - | bash || exit $? +if which curl &>/dev/null; then + DOWNLOAD="curl -s" +elif which wget &>/dev/null; then + DOWNLOAD="wget -q -O -" +fi +BRANCH="opengnsys-#{OGVERSION}" +$DOWNLOAD https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH/installer/opengnsys_installer.sh | bash || exit $? mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log echo y | /opt/opengnsys/bin/setserveraddr $(ip -o link show | tail -1 | cut -d: -f2) # Insert DHCP data. @@ -50,30 +56,44 @@ done service isc-dhcp-server restart # Set language. export LANG="#{LANGUAGE}.UTF-8" -echo "LANG=\"$LANG\"" > /etc/default/locale -echo "LANG=\"$LANG\"" >> /etc/environment +echo "LANG=\\\"$LANG\\\"" > /etc/default/locale +echo "LANG=\\\"$LANG\\\"" >> /etc/environment locale-gen --lang #{LANGUAGE} -sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\"${LANG%_*}\"/" /etc/default/keyboard +sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\\\"${LANG%_*}\\\"/" /etc/default/keyboard dpkg-reconfigure -fnoninteractive console-setup # Comment out next lines for automatic data insertion. -#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" +#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, ntp, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" #for ((i=11; i<=#{NCLIENTS+10}; i++)); do # SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," #done #mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" -#if ! grep -q "1\.0" /opt/opengnsys/doc/VERSION.txt; then AUX=1; fi -#/opt/opengnsys/bin/setclientmode ogAdmin pc11 $AUX +#/opt/opengnsys/bin/setclientmode ogLiveAdmin pc11 PERM #for ((i=12; i<=#{NCLIENTS+10}; i++)); do -# /opt/opengnsys/bin/setclientmode ogClient pc$i $AUX +# /opt/opengnsys/bin/setclientmode ogLive pc$i PERM #done -echo "New OpenGnsys local URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +echo "Notes:" +echo "- OpenGnsys Server URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" +exit 0 EOT # Client 1 OS provisioning script. MODELSCRIPT = <<EOT +# Comment out next lines to install and configure OGAgent for Ubuntu. +#OGAGENTPKG="ogagent_#{OGVERSION}_all.deb" +#apt-get update -y +#apt-get install -y curl +#curl -ks https://#{SERVERIP}/opengnsys/descargas/$OGAGENTPKG -o /tmp/$OGAGENTPKG +#if [ -f /tmp/$OGAGENTPKG ]; then +# apt-get install -y /tmp/$OGAGENTPKG || exit $? +# sed -i "0,/remote=/ s,remote=.*,remote=https://#{SERVERIP}/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg +# rm -f /tmp/$OGAGENTPKG +#else +# echo "Warning: cannot install OGAgent package $OGAGENTPKG" +#fi # Remove network configuration added by Vagrant. -sed -i "/VAGRANT/,$ d" /etc/network/interfaces -echo "After now, use VirtualBox GUI to disable network interface 1 and work with this VM." +sed -i "/enp0s3/ d" /etc/network/interfaces +echo "Notes:" +echo "- After now, use VirtualBox GUI to disable network interface 1 and restart this VM." # Leave VM halted. sleep 2 poweroff & @@ -102,14 +122,14 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| vb.customize ['createhd', '--filename', second_disk, '--size', REPOSIZE * 1024] end # Attach repo virtual disk. - vb.customize ['storageattach', :id, '--storagectl', 'SATAController', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', second_disk] + vb.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', second_disk] end # VM base and host name. - og.vm.box = "ubuntu/trusty64" + og.vm.box = "bento/ubuntu-18.04" og.vm.hostname = "ogAdministrator" # Network configuration: forward web port and attach new interface to VMs private network. og.vm.network "forwarded_port", guest: 443, host: LOCALWEBPORT, host_ip: "127.0.0.1" - og.vm.network "private_network", mac: "#{MACPREFIX}10".tr(":",""), ip: "#{NETPREFIX}.10", virtualbox__intnet: true + og.vm.network "private_network", mac: "#{MACPREFIX}10".tr(":",""), ip: "#{SERVERIP}", virtualbox__intnet: true # Comment out to disable synced folder. #og.vm.synced_folder ".", "/vagrant", disabled: true # Launch provisioning script. @@ -118,7 +138,7 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Client 1 VM definition. config.vm.define "pc11", autostart: false do |v1| - v1.vm.box = "ubuntu/trusty64" + v1.vm.box = "bento/ubuntu-18.04" v1.vm.hostname = "pc11" v1.vm.network "private_network", mac: "#{MACPREFIX}11".tr(":",""), type: "dhcp", virtualbox__intnet: true v1.vm.provider "virtualbox" do |vb| @@ -137,7 +157,7 @@ Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| cl.vm.box = "clink15/pxe" cl.ssh.insert_key = false cl.vm.boot_timeout = 5 - cl.vm.network "private_network", mac: "#{MACPREFIX}${i+10}".tr(":",""), type: "dhcp", virtualbox__intnet: true + cl.vm.network "private_network", mac: "#{MACPREFIX}#{i+10}".tr(":",""), type: "dhcp", virtualbox__intnet: true cl.vm.provider "virtualbox" do |vb| vb.name = "pc#{i+10}" vb.memory = CLIENTMEM diff --git a/installer/vagrant/Vagrantfile-boottools-vbox b/installer/vagrant/Vagrantfile-boottools-vbox index 14306402..82cae850 100644 --- a/installer/vagrant/Vagrantfile-boottools-vbox +++ b/installer/vagrant/Vagrantfile-boottools-vbox @@ -24,7 +24,8 @@ apt-get install -y jq subversion syslinux syslinux-efi syslinux-utils groupadd opengnsys mkdir -p /opt/opengnsys/client /tmp/opengnsys_installer/opengnsys ln -fs /var/lib/tftpboot /opt/opengnsys -svn export https://github.com/opengnsys/OpenGnsys/branches/devel/client /tmp/opengnsys_installer/opengnsys/client +BRANCH="master" +svn export https://github.com/opengnsys/OpenGnsys/branches/$BRANCH/client /tmp/opengnsys_installer/opengnsys/client echo "Connect to this VM, launch boot-tools generation script and follow instructions:" echo " sudo /tmp/opengnsys_installer/opengnsys/client/boot-tools/boottoolsgenerator.sh" echo "Warning: this process may take a long time." diff --git a/installer/vagrant/Vagrantfile-browser-vbox b/installer/vagrant/Vagrantfile-browser-vbox index 8e3abebf..d723abbd 100644 --- a/installer/vagrant/Vagrantfile-browser-vbox +++ b/installer/vagrant/Vagrantfile-browser-vbox @@ -29,7 +29,7 @@ echo "yes" | ./configure -opensource -embedded x86 -webkit -openssl -qt-gfx-vnc make make install # Compile the Browser. -BRANCH="devel" +BRANCH="master" svn export "https://github.com/opengnsys/OpenGnsys/branches/$BRANCH/client/browser" ../browser cd ../browser qmake browser.pro diff --git a/installer/vagrant/Vagrantfile-devel-vbox b/installer/vagrant/Vagrantfile-devel-vbox index c558227a..70bad3ac 100644 --- a/installer/vagrant/Vagrantfile-devel-vbox +++ b/installer/vagrant/Vagrantfile-devel-vbox @@ -43,7 +43,7 @@ if which curl &>/dev/null; then elif which wget &>/dev/null; then DOWNLOAD="wget -q -O -" fi -BRANCH="devel" +BRANCH="master" $DOWNLOAD "https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH/installer/opengnsys_installer.sh" | bash || exit $? mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log echo y | /opt/opengnsys/bin/setserveraddr $(ip -o link show | tail -1 | cut -d: -f2) diff --git a/installer/vagrant/Vagrantfile-ogagent-vbox b/installer/vagrant/Vagrantfile-ogagent-vbox index 1bf48faa..7b7753db 100644 --- a/installer/vagrant/Vagrantfile-ogagent-vbox +++ b/installer/vagrant/Vagrantfile-ogagent-vbox @@ -33,7 +33,7 @@ wget -q https://atom.io/download/rpm -O /tmp/atom.rpm && dnf install -y /tmp/ato # Comment out next line if you prefer to install Eclipse IDE for Python (it needs more disk space). #dnf install -y eclipse-pydev eclipse-nls-${LANG%_*} # Download OGAgent environment installer. -BRANCH="devel" +BRANCH="master" wget -qc --unlink https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH/installer/ogagent-devel-installer.sh -O /home/vagrant/ogagent-devel-installer.sh chmod +x /home/vagrant/ogagent-devel-installer.sh # Instructions. diff --git a/installer/vagrant/Vagrantfile-prod-vbox b/installer/vagrant/Vagrantfile-prod-vbox index 5cfc94d5..f14479e7 100644..120000 --- a/installer/vagrant/Vagrantfile-prod-vbox +++ b/installer/vagrant/Vagrantfile-prod-vbox @@ -1,169 +1 @@ -# Vagrantfile to install OpenGnsys virtual environment (production version) using VirtualBox provider. - -VAGRANTFILE_API_VERSION = "2" -# VM provider: Oracle VM VirtualBox. -ENV['VAGRANT_DEFAULT_PROVIDER'] = "virtualbox" -# Language (accepted values: es_ES, ca_ES, en_GB). -LANGUAGE = "es_ES" -ENV['LC_ALL'] = LANGUAGE + ".UTF-8" -# Number of OpenGnsys clients (accepted values: from 2 to 9). -NCLIENTS = 4 -# Repository virtual disk: file and size (GB). -REPODISK = "ogRepo.vdi" -REPOSIZE = 50 -# Amount of memory for server and clients (MB) -SERVERMEM = 1024 # Minimum: 512 -CLIENTMEM = 512 # Minimum: 256 -# Prefixes for MAC and IP addresses. -MACPREFIX = "08:00:27:0E:65" -NETPREFIX = "192.168.2" -# OpenGnsys Server IP address. -SERVERIP = "#{NETPREFIX}.10" -# Local port to access OpenGnsys Server. -LOCALWEBPORT = 8443 - -# OpenGnsys Server provisioning script: prepare repo disk, install OpenGnsys, change default interface, configure DHCP server. -OGSERVERSCRIPT = <<EOT -# Exit if OpenGnsys is installed. -[ -f /opt/opengnsys/doc/VERSION.txt ] && echo "Cannot provision, OpenGnsys is already installed." && exit 1 -# Create repository disk using LVM, if necesary. -if [ -z "$(blkid /dev/mapper/og-images | grep ext4)" ]; then - pvcreate /dev/sdb - vgcreate og /dev/sdb - vgchange -ay - lvcreate -ay -n images -l 100%VG og - mkfs -t ext4 /dev/mapper/og-images - mkdir -p /opt/opengnsys/images - echo "/dev/mapper/og-images /opt/opengnsys/images ext4 defaults 0 0" >> /etc/fstab - mount -a -fi -# Install OpenGnsys and change server address. -if which curl &>/dev/null; then - DOWNLOAD="curl -s" -elif which wget &>/dev/null; then - DOWNLOAD="wget -q -O -" -fi -$DOWNLOAD -s https://raw.githubusercontent.com/opengnsys/OpenGnsys/master/installer/opengnsys_installer.sh | bash || exit $? -mv /opt/opengnsys/log/bash.log /opt/opengnsys/log/opengnsys_installer.log -echo y | /opt/opengnsys/bin/setserveraddr $(ip -o link show | tail -1 | cut -d: -f2) -# Insert DHCP data. -for ((i=#{NCLIENTS+10}; i>10; i--)); do - sed -i "/^}$/ i host pc${i} { hardware ethernet #{MACPREFIX}:${i}; fixed-address #{NETPREFIX}.${i}; }" /etc/dhcp/dhcpd.conf -done -service isc-dhcp-server restart -# Set language. -export LANG="#{LANGUAGE}.UTF-8" -echo "LANG=\\\"$LANG\\\"" > /etc/default/locale -echo "LANG=\\\"$LANG\\\"" >> /etc/environment -locale-gen --lang #{LANGUAGE} -sed -i "s/XKBLAYOUT=.*/XKBLAYOUT=\\\"${LANG%_*}\\\"/" /etc/default/keyboard -dpkg-reconfigure -fnoninteractive console-setup -# Comment out next lines for automatic data insertion. -#SQL="INSERT INTO aulas (nombreaula, idcentro, urlfoto, grupoid, ubicacion, puestos, modomul, ipmul, pormul, velmul, router, netmask, ntp, dns, proxy, modp2p, timep2p) VALUES ('Aula virtual', 1, 'aula.jpg', 0, 'Despliegue virtual con Vagrant.', 5, 2, '239.194.2.11', 9000, 70, '#{NETPREFIX}.1', '255.255.255.0', '', '', '', 'peer', 30); INSERT INTO ordenadores (nombreordenador, ip, mac, idaula, idrepositorio, idperfilhard, idmenu, idproautoexec, grupoid, router, mascara, arranque, netiface, netdriver, fotoord) VALUES" -#for ((i=11; i<=#{NCLIENTS+10}; i++)); do -# SQL="$SQL ('pc$i', '#{NETPREFIX}.$i', REPLACE('#{MACPREFIX}$i',':',''), 1, 1, 0, 0, 0, 0, '#{NETPREFIX}.1', '255.255.255.0', '00unknown', 'eth0', 'generic', 'fotoordenador.gif')," -#done -#mysql -u usuog -ppassusuog -D ogAdmBD -e "${SQL%,}" -#/opt/opengnsys/bin/setclientmode ogLiveAdmin pc11 PERM -#for ((i=12; i<=#{NCLIENTS+10}; i++)); do -# /opt/opengnsys/bin/setclientmode ogLive pc$i PERM -#done -echo "Notes:" -echo "- OpenGnsys Server URL: https://localhost:#{LOCALWEBPORT}/opengnsys/" -exit 0 -EOT - -# Client 1 OS provisioning script. -OGAGENTPKG = "ogagent_1.1.0_all.deb" -MODELSCRIPT = <<EOT -# Comment out next lines to install and configure OGAgent for Ubuntu. -#apt-get update -y -#apt-get install -y curl -#curl -ks https://#{SERVERIP}/opengnsys/descargas/#{OGAGENTPKG} -o /tmp/#{OGAGENTPKG} -#if [ -f /tmp/#{OGAGENTPKG} ]; then -# apt-get install -y /tmp/#{OGAGENTPKG} || exit $? -# sed -i "0,/remote=/ s,remote=.*,remote=https://#{SERVERIP}/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg -# rm -f /tmp/#{OGAGENTPKG} -#else -# echo "Warning: cannot install OGAgent package #{OGAGENTPKG}" -#fi -# Remove network configuration added by Vagrant. -sed -i "/enp0s3/ d" /etc/network/interfaces -echo "Notes:" -echo "- After now, use VirtualBox GUI to disable network interface 1 and restart this VM." -# Leave VM halted. -sleep 2 -poweroff & -EOT - -Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| - - # OpenGnsys Server VM definition. - config.vm.define "ogAdministrator", primary: true do |og| - # Specific VirtualBox configuration. - og.vm.provider "virtualbox" do |vb| - # VM name, memory and CPUs. - vb.name = "ogAdministrator" - vb.memory = SERVERMEM - vb.cpus = 1 - # 2nd virtual disk path (current dir on Windows, VM dir on other OSes) - if Vagrant::Util::Platform.windows? then - second_disk = File.join(".", REPODISK) - else - line = `VBoxManage list systemproperties`.match("Default machine folder.*")[0] - vb_machine_folder = line.split(':')[1].strip() - second_disk = File.join(vb_machine_folder, vb.name, REPODISK) - end - # Create repo virtual disk, if needed. - unless File.exist?(second_disk) - vb.customize ['createhd', '--filename', second_disk, '--size', REPOSIZE * 1024] - end - # Attach repo virtual disk. - vb.customize ['storageattach', :id, '--storagectl', 'SATA Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', second_disk] - end - # VM base and host name. - og.vm.box = "bento/ubuntu-16.04" - og.vm.hostname = "ogAdministrator" - # Network configuration: forward web port and attach new interface to VMs private network. - og.vm.network "forwarded_port", guest: 443, host: LOCALWEBPORT, host_ip: "127.0.0.1" - og.vm.network "private_network", mac: "#{MACPREFIX}10".tr(":",""), ip: "#{SERVERIP}", virtualbox__intnet: true - # Comment out to disable synced folder. - #og.vm.synced_folder ".", "/vagrant", disabled: true - # Launch provisioning script. - og.vm.provision "shell", inline: OGSERVERSCRIPT - end - - # Client 1 VM definition. - config.vm.define "pc11", autostart: false do |v1| - v1.vm.box = "bento/ubuntu-16.04" - v1.vm.hostname = "pc11" - v1.vm.network "private_network", mac: "#{MACPREFIX}11".tr(":",""), type: "dhcp", virtualbox__intnet: true - v1.vm.provider "virtualbox" do |vb| - vb.name = "pc11" - vb.memory = CLIENTMEM - vb.cpus = 1 - vb.customize ['modifyvm', :id, '--boot1', 'net', '--boot2', 'disk'] - end - v1.vm.synced_folder ".", "/vagrant", disabled: true - v1.vm.provision "shell", inline: MODELSCRIPT - end - - # Clonable clients definition. - (2..NCLIENTS).each do |i| - config.vm.define "pc#{i+10}", autostart: false do |cl| - cl.vm.box = "clink15/pxe" - cl.ssh.insert_key = false - cl.vm.boot_timeout = 5 - cl.vm.network "private_network", mac: "#{MACPREFIX}#{i+10}".tr(":",""), type: "dhcp", virtualbox__intnet: true - cl.vm.provider "virtualbox" do |vb| - vb.name = "pc#{i+10}" - vb.memory = CLIENTMEM - vb.cpus = 1 - vb.customize ['modifyvm', :id, '--boot1', 'net', '--boot2', 'disk'] - vb.customize ["modifyvm", :id, "--nic1", "none"] - end - end - end - -end - +Vagrantfile-1.1.1-vbox
\ No newline at end of file diff --git a/repoman/INSTALL b/repoman/INSTALL deleted file mode 100644 index e69de29b..00000000 --- a/repoman/INSTALL +++ /dev/null diff --git a/repoman/bin/sendFileMcast b/repoman/bin/sendFileMcast index 9f6479c9..7a238d53 100755 --- a/repoman/bin/sendFileMcast +++ b/repoman/bin/sendFileMcast @@ -41,7 +41,7 @@ PARAMS=$(echo "$2" | \ awk -F: '$1~/^[0-9]+$/ {v1=$1} tolower($2)~/^half(-duplex)?$/ {v2="--half-duplex"} tolower($2)~/^full(-duplex)?$/ {v2="--full-duplex"} - $3~/^[0-9]+(\.[0-9]+){3}$/ {v3=$3} + $3~/^[0-9]{1,3}(\.[0-9]{1,3}){3}$/ {v3=$3} $4~/^[0-9]+[mM]$/ {v4=tolower($4)} $5~/^[0-9]+$/ {v5=$5} $6~/^[0-9]+$/ {v6=$6} diff --git a/server/bin/checkperms b/server/bin/checkperms index 3f79e2d3..b7559e84 100755 --- a/server/bin/checkperms +++ b/server/bin/checkperms @@ -48,10 +48,10 @@ chown -R $OPENGNSYS_USER:$OPENGNSYS_USER $OPENGNSYS_DIR/client/etc/ssl/private chmod -R go-rwx $OPENGNSYS_DIR/client/etc/ssl/private chown $OPENGNSYS_USER:$OPENGNSYS_USER $OPENGNSYS_DIR/client/interfaceAdm/CambiarAcceso chmod 700 $OPENGNSYS_DIR/client/interfaceAdm/CambiarAcceso -chown root:root $OPENGNSYS_DIR/etc/{ogAdmServer,ogAdmAgent}*.cfg -chmod 600 $OPENGNSYS_DIR/etc/{ogAdmServer,ogAdmAgent}*.cfg -chown root:$APACHE_GROUP $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg} -chmod 640 $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg} +chown root:root $OPENGNSYS_DIR/etc/ogAdmAgent*.cfg +chmod 600 $OPENGNSYS_DIR/etc/ogAdmAgent*.cfg +chown root:$APACHE_GROUP $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg,etc/ogAdmServer*.cfg} +chmod 640 $OPENGNSYS_DIR/{www/controlacceso*.php,etc/ogAdmRepo*.cfg,etc/ogAdmServer*.cfg} chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/images/{fotos,iconos} mkdir -p $OPENGNSYS_DIR/www/{api,tmp} chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/www/{api,tmp} diff --git a/server/bin/setclientmode b/server/bin/setclientmode index 4004e932..4a37f9cc 100755 --- a/server/bin/setclientmode +++ b/server/bin/setclientmode @@ -1,13 +1,13 @@ #!/bin/bash #/** -# setclientmode NombrePlatilla { NombrePC | NombreAula } Modo_trabajo -#@file setclientmode +#@file setclientmode #@brief Configura el archivo de arranque de PXE para los clientes, ya sea un equipo o un aula, generando enlaces a archivos usados como plantilla. +#@usage setclientmode Plantilla Ambito Modo #@warning El archivo PXE por defecto "default" se deja en modo de ejecución "user" y se eliminan los enlaces para equipos con la plantilla por defecto. -#@param $1 NombrePlatilla -#@param $2 Ámbito { NombrePC | NombreAula } -#@param $3 Modo_trabajo = { 0, TEMP, 1, PERM } - 0 si es temporal y 1 si es permanente. +#@param Plantilla: nombre de plantilla PXE +#@param Ambito: nombre de cliente o aula +#@param Modo: "TEMP" (temporal) o "PERM" (permanente) #@version 1.0 - Versión inicial. #@author Irina Gomez y Ramon Gomez - Univ. Sevilla, noviembre 2010 #@version 1.0.1 - Identificacion de la plantilla por nombre en consola = en primera linea de la plantilla @@ -36,42 +36,29 @@ PXEDIR[1]=$OPENGNSYS/tftpboot/grub LOGFILE=$OPENGNSYS/log/opengnsys.log MYCNF=/tmp/.my.cnf.$$ +source $OPENGNSYS/lib/ogfunctions.sh +# Mostrar ayuda. +[ "$*" == "help" ] && help # Control básico de errores. -if [ $# -ne 3 ]; then - echo "$PROG: Error de ejecución" - echo "Formato: $PROG PLANTILLA [NOMBRE_PC|NOMBRE_AULA] MODO" - exit 1 -fi - +[ $# -ne 3 ] && raiseError usage # Comprobar si el usuario es "root" o el del servicio web. WEBUSER=$(ps axho user,comm|awk '!/root/ && /httpd|apache/ {print $1; exit;}') -if [ "$USER" != "root" -a "$USER" != "$WEBUSER" ]; then - echo "$PROG: Need to be root. (The console can also call the script)." >&2 - exit 1 -fi - +CALLER=$(getCaller) +[ "$USER" != "root" -a "$USER" != "$WEBUSER" -a "$CALLER" != "ogAdmServerAux" ] && raiseError access "Need to be root (or webserver user)" # El acceso a mysql por las variables pasadas o por el fichero de configuarción. if [ -z "$USUARIO" ] || [ -z "$PASSWORD" ] || [ -z "$CATALOG" ]; then - if [ -r "$SERVERCONF" ]; then - source $SERVERCONF - else - echo "$PROG: Sin acceso a fichero de configuración" - exit 2 - fi -fi -TEMPLATE[0]=$(grep -l "^#.* $1 *$" ${PXEDIR[0]}/templates/*) -TEMPLATE[1]=$(grep -l "^#.* $1 *$" ${PXEDIR[1]}/templates/*) -if [ -z "${TEMPLATE[0]}" -a -z "${TEMPLATE[1]}" ]; then - echo "No existe archivo platilla: $1" - exit + [ ! -r "$SERVERCONF" ] && raiseError access "Cannot read access configuration file" + source $SERVERCONF fi +TEMPLATE[0]=$(grep -l "^#.* $1 *$" ${PXEDIR[0]}/templates/* 2>/dev/null) +TEMPLATE[1]=$(grep -l "^#.* $1 *$" ${PXEDIR[1]}/templates/* 2>/dev/null) +[ -z "${TEMPLATE[0]}${TEMPLATE[1]}" ] && raiseError notfound "PXE template file \"$1\"" case "${3^^}" in 0|TEMP) MODE="TEMP" ;; 1|PERM) MODE="PERM" ;; - *) echo "$PROG: Modo desconodido: 0, TEMP (temporal), 1, PERM (permanente)" - exit 1 ;; + *) raiseError notfound "Unknown mode \"$3\"" ;; esac # Sustituir caracteres ' por \' para evitar inyección SQL. @@ -94,8 +81,8 @@ ETHERNET=$(mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -s -N -e \ WHERE aulas.nombreaula='$RESOURCE' OR nombreordenador='$RESOURCE';") if [ -z "$ETHERNET" ]; then - date +"%b %d %T $PROG: No existe aula o equipo con el nombre \"$2\"" | tee -a $LOGFILE - exit 1 + date +"%b %d %T $PROG: No existe aula o equipo con el nombre \"$2\"" >> $LOGFILE + raiseError notfound "Client or lab name \"$2\"" fi # Copiar fichero de configuración y actualizar base de datos. @@ -107,6 +94,10 @@ for MAC in $ETHERNET; do PXEFILE[0]=01-${MACFILE:0:2}-${MACFILE:2:2}-${MACFILE:4:2}-${MACFILE:6:2}-${MACFILE:8:2}-${MACFILE:10:2} MACFILE="${MAC,,}" PXEFILE[1]=01-${MACFILE:0:2}:${MACFILE:2:2}:${MACFILE:4:2}:${MACFILE:6:2}:${MACFILE:8:2}:${MACFILE:10:2} + # Renombra el fichero PXE original + [ -e ${PXEDIR[0]}/${PXEFILE[0]} ] && mv ${PXEDIR[0]}/${PXEFILE[0]} ${PXEDIR[0]}/${PXEFILE[0]}.netboot + [ -e ${PXEDIR[1]}/${PXEFILE[1]} ] && mv ${PXEDIR[1]}/${PXEFILE[1]} ${PXEDIR[1]}/${PXEFILE[1]}.netboot + if [ "$1" != "default" ]; then # Si no está definida la variable LANG, usar idioma inglés por defecto. [ -z "$LANG" -o "$LANG" == "C" ] && LANG="en" @@ -114,15 +105,16 @@ for MAC in $ETHERNET; do DATOS=$(mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -s -N -e \ "SELECT ' LANG=$LANG', ' ip=', CONCAT_WS(':', ordenadores.ip, - (SELECT (@serverip:=ipserveradm) FROM entornos LIMIT 1), - aulas.router, aulas.netmask, - ordenadores.nombreordenador, ordenadores.netiface, 'none'), + (SELECT (@serverip:=ipserveradm) FROM entornos LIMIT 1), + aulas.router, aulas.netmask, + ordenadores.nombreordenador, ordenadores.netiface, 'none'), ' group=', REPLACE(TRIM(aulas.nombreaula), ' ', '_'), ' ogrepo=', (@repoip:=IFNULL(repositorios.ip, '')), ' oglive=', @serverip, ' oglog=', @serverip, ' ogshare=', @serverip, ' oglivedir=', ordenadores.oglivedir, + ' ogprof=', IF(ordenadores.idordenador=aulas.idordprofesor, 'true', 'false'), IF(perfileshard.descripcion<>'', CONCAT(' hardprofile=', REPLACE(TRIM(perfileshard.descripcion), ' ', '_')), ''), IF(aulas.ntp<>'', CONCAT(' ogntp=', aulas.ntp), ''), IF(aulas.dns<>'', CONCAT(' ogdns=', aulas.dns), ''), diff --git a/server/bin/setserveraddr b/server/bin/setserveraddr index cca279b8..fc5efc5d 100755 --- a/server/bin/setserveraddr +++ b/server/bin/setserveraddr @@ -1,18 +1,18 @@ #!/bin/bash #/** -# setserveraddr {str_ipaddress | str_netiface} #@file setserveraddr -#@brief Command the modifies configuration files to assign the default network interface. +#@brief Assign default IP address to OpenGnsys services. +#@usage setserveraddr {str_ipaddress | str_netiface} #@param str_ipaddress IP address assigned to a network interface -#@param str_netiface network interface name defined by the operating system. +#@param str_netiface network interface name defined by the operating system #@version Initial version. #@author Ramón M. Gómez - ETSII Univ. Sevilla #@date 2011-01-25 #@version 1.0.5 - Regenerate configuration files. #@author Ramón M. Gómez - ETSII Univ. Sevilla #@date 2014-06-06 -#@version 1.1.1 - Updating menu URLs, PXE files, and repository API key. +#@version 1.1.1 - Updating menu URLs and PXE files. #@author Ramón M. Gómez - ETSII Univ. Sevilla #@date 2018-11-15 #*/ ## @@ -21,25 +21,21 @@ # Variables. PROG="$(basename "$0")" OPENGNSYS=/opt/opengnsys -PXEDIR=$OPENGNSYS/tftpboot/menu.lst +PXEDIRS="$OPENGNSYS/tftpboot/menu.lst $OPENGNSYS/tftpboot/grub" DEFAULTFILE=/etc/default/opengnsys -# Checking parameters. -if [ $# -ne 1 ]; then - echo "$PROG: Incorrect operand. Format: $PROG ipaddress|netiface" >&2 - exit 1 -fi -if [ "$USER" != "root" ]; then - echo "$PROG: Need to be root." >&2 - exit 1 -fi +# Functions. +source $OPENGNSYS/lib/ogfunctions.sh -# Showing warning to inform that initiated clients may hang. -read -rp "WARNING: initiated clients can hang. Continue? (y/n): " ANSWER -if [ "${ANSWER,,}" != "y" ]; then - echo "Operation canceled." - exit 0 -fi +# Checking parameters. +[ "$USER" != "root" ] && raiseError access "Need to be root" +[ $# -ne 1 ] && raiseError usage +[ -r $DEFAULTFILE ] || raiseError access "Cannot read default configuration file" +for f in $OPENGNSYS/{etc/{ogAdmServer,ogAdmRepo,ogAdmAgent}.cfg,www/controlacceso.php,client/etc/ogAdmClient.cfg}; do + [ -w $f ] || raiseError access "Cannot write to file: $f" +done +# Show help message. +[ "$1" == "help" ] && help # Detecting network interfaces. DEVICES=$(ip -o link show up | awk -F: '$2!~/lo/ {print $2}') @@ -54,6 +50,9 @@ done # Checking if IP address has been detected. if [ -n "$SERVERIP" ]; then + # Showing warning to inform that initiated clients may hang. + read -rp "WARNING: initiated clients can hang. Continue? (y/n): " ANSWER + [ "${ANSWER,,}" != "y" ] && raiseError cancel "Do nothing" # Temporary files. tmpfile=$(mktemp /tmp/og.XXXXX) MYCNF=$(mktemp /tmp/.my.cnf.XXXXX) @@ -86,20 +85,13 @@ if [ -n "$SERVERIP" ]; then fi # Saving old IP address. - source $OPENGNSYS/etc/ogAdmRepo.cfg - OLDSERVERIP=$IPlocal - + source $OPENGNSYS/etc/ogAdmServer.cfg + OLDSERVERIP=$ServidorAdm # Checking if configuration files need to be modified. CHANGE=0 for f in $OPENGNSYS/{etc/{ogAdmServer,ogAdmRepo,ogAdmAgent}.cfg,www/controlacceso.php,client/etc/ogAdmClient.cfg}; do - # Error if configuration file cannot be found. - if [ ! -f $f ]; then - echo "$PROG: File $file does not exist." >&2 - exit 2 - fi - # Updating configuration variables (if URLs does not contain "localhost"). - sed -e "s,ServidorAdm=.*,ServidorAdm=$SERVERIP," \ - -e "s,IPlocal=.*,IPlocal=$SERVERIP," \ + # Updating configuration variables (if URL does not contain "localhost"). + sed -e "s,\(ServidorAdm\|IPlocal\)=.*,\1=$SERVERIP," \ -e "s,UrlMenu=https?://\([^/]*\)/\(.*\),UrlMenu=https://$SERVERIP/\2," \ -e '/localhost/!s,https\?://[^/]*/\(.*\),https://'$SERVERIP'/\1,' $f >$tmpfile file="${f/./-$SERVERDEV.}" @@ -115,42 +107,29 @@ if [ -n "$SERVERIP" ]; then if [ $CHANGE == 1 ]; then # Restart OpenGnsys services. /etc/init.d/opengnsys restart - # If Repository is active, generating a new API token. source $DEFAULTFILE - if [ "$RUN_OGADMREPO" == "yes" ]; then - REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));') - sed -i -e "s/ApiToken=.*/ApiToken=$REPOKEY/" $OPENGNSYS/etc/ogAdmRepo.cfg - sed -i -e "s/APITOKEN=.*/APITOKEN=$REPOKEY/" $OPENGNSYS/etc/ogAdmServer.cfg - fi # If OpenGnsys Server is active, updating the database. if [ "$RUN_OGADMSERVER" == "yes" ]; then - source $OPENGNSYS/etc/ogAdmServer.cfg # Creating credentials file. cat << EOT > $MYCNF [client] user=$USUARIO password=$PASSWORD EOT - # Updating OpenGnsys Server IP address. - mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \ - "UPDATE entornos - SET ipserveradm='$SERVERIP' - WHERE identorno=1" - # If OpenGnsys Repository is active, updating IP address and API token. - if [ "$RUN_OGADMREPO" == "yes" ]; then - mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \ - "UPDATE repositorios - SET ip='$SERVERIP', apikey='$REPOKEY' - WHERE ip='$OLDSERVERIP'" - unset REPOKEY - fi - # Updating all menu URLs. - mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \ - "UPDATE menus - SET htmlmenupub = REPLACE(htmlmenupub, '$OLDSERVERIP', '$SERVERIP'), - htmlmenupri = REPLACE(htmlmenupri, '$OLDSERVERIP', '$SERVERIP');" + # Updating IP addresses and menu URLs. + mysql --defaults-extra-file=$MYCNF -D "$CATALOG" << EOT +UPDATE entornos + SET ipserveradm='$SERVERIP' + WHERE identorno=1; +UPDATE repositorios + SET ip='$SERVERIP' + WHERE ip='$OLDSERVERIP'; +UPDATE menus + SET htmlmenupub = REPLACE(htmlmenupub, '$OLDSERVERIP', '$SERVERIP'), + htmlmenupri = REPLACE(htmlmenupri, '$OLDSERVERIP', '$SERVERIP'); +EOT # Updating all PXE files. - find $PXEDIR -name "01-*" -exec sed -i -e "s/$OLDSERVERIP/$SERVERIP/g" {} \; + find $PXEDIRS -name "01-*" -exec sed -i -e "s/$OLDSERVERIP/$SERVERIP/g" {} \; fi # Showing manual task to do after execution. @@ -162,7 +141,7 @@ Manual tasks: - Check PXE files. - Log-in as Web Console user: - Check menu URLs. -${REPOKEY:+" - Update repository API token"} +- Note: Run "settoken" script to update authentication tokens. EOT else # Showing message if nothing changes. @@ -170,8 +149,7 @@ EOT fi else # Error if network interface is not found. - echo "$PROG: Network device not found. Format: $PROG ipaddress|netiface" >&2 - exit 1 + raiseError notfound "Network device" fi # Removing temporary files. diff --git a/server/bin/settoken b/server/bin/settoken index dd98f06a..018168c9 100755 --- a/server/bin/settoken +++ b/server/bin/settoken @@ -2,12 +2,13 @@ #/** #@file settoken -#@brief Generate a new security token for the specified service. -#@usage settoken [-f] [Service] +#@brief Generate a new security token for the specified service or user. +#@usage settoken [[-f] [Service]] | User #@param -f: force server restart without prompting (ask by default) -#@param Service: may be "server", "repo" or "both" (by default) +#@param Service: may be "server", "repo" or "services" (for all services, by default) +#@param User: OpenGnsys-defined username #@warning This script uses "php" command. -#@version 1.1.2 - Initial version. +#@version 1.1.1 - Initial version. #@author Ramón M. Gómez - ETSII Univ. Sevilla #@date 2019-09-25 #*/ ## @@ -19,10 +20,14 @@ SERVERCFG=$OPENGNSYS/etc/ogAdmServer.cfg # Configuration files. REPOCFG=$OPENGNSYS/etc/ogAdmRepo.cfg # Functions. -source $OPENGNSYS/lib/ogfunctions.sh +source $OPENGNSYS/lib/ogfunctions.sh || exit 1 + +function new_token() { + php -r 'echo md5(uniqid(rand(), true));' +} # Error control. -[ "$USER" != "root" ] && raiseError access "Need to by root" +[ "$USER" != "root" ] && raiseError access "Need to be root" if [ "$1" == "-f" ]; then FORCE=1 shift @@ -31,16 +36,29 @@ fi case "${1,,}" in help) help ;; - server) + server) # Generate server token. SERVER=1 ;; - repo) + repo) # Generate repository token. REPO=1 ;; - ""|both) + ""|services) # Generate server and repo tokens. SERVER=1; REPO=1 ;; - *) - raiseError notfound "Unknown service" + *) # Generate user token. + OGUSER="$1" ;; esac [ -w $SERVERCFG ] || raiseError access "Server configuration file" +source $SERVERCFG + +# Update user token. +if [ "$OGUSER" ]; then + APIKEY="$(new_token)" + DATA=" +UPDATE usuarios + SET apikey='$APIKEY', idusuario=LAST_INSERT_ID(idusuario) + WHERE usuario='$OGUSER'; +SELECT LAST_INSERT_ID(); +" + [ "$(dbexec "$DATA")" == "0" ] && raiseError notfound "User \"$OGUSER\"" +fi # Update server token. if [ "$SERVER" ]; then @@ -49,30 +67,21 @@ if [ "$SERVER" ]; then read -rp "It will be necessary to restart ogAdmServer service. Continue? [y/N]: " ANSWER [ "${ANSWER,,}" != "y" ] && raiseError cancel "API tokens not updated" fi - APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') - sed -i "s/^APITOKEN=.*/APITOKEN=$APIKEY/" $SERVERCFG || raiseError access "Cannot update server file" + APIKEY="$(new_token)" + sed -i -n -e "/^APITOKEN=/!p" -e "$ a\APITOKEN=$APIKEY" $SERVERCFG || raiseError access "Cannot update server file" fi # Update repository token. if [ "$REPO" ]; then [ -w $REPOCFG ] || raiseError access "Repository configuration file" - APIKEY=$(php -r 'echo md5(uniqid(rand(), true));') - sed -i "s/^ApiToken=.*/ApiToken=$APIKEY/" $REPOCFG || raiseError access "Cannot update repository file" + APIKEY="$(new_token)" + sed -i -n -e "/^ApiToken=/!p" -e "$ a\ApiToken=$APIKEY" $REPOCFG || raiseError access "Cannot update repository file" # If database is local, update it. - source $SERVERCFG source $REPOCFG if [ "$ServidorAdm" == "$IPlocal" ]; then - MYCNF=$(mktemp) - trap "rm -f $MYCNF" 0 1 2 3 6 9 15 - chmod 600 $MYCNF - cat << EOT > $MYCNF -[client] -user=$USUARIO -password=$PASSWORD -host=$datasource -EOT - mysql --defaults-extra-file="$MYCNF" --default-character-set=utf8 -D "$CATALOG" -e \ - "UPDATE repositorios SET apikey='$APIKEY' WHERE ip='$IPlocal';" || raiseError access "Database error" + dbexec "UPDATE repositorios SET apikey='$APIKEY' WHERE ip='$IPlocal';" + else + echo "Please, don't forget to update the authentication token for this repository on the web server (check the file ogAdmRepo.cfg)." fi fi diff --git a/server/lib/checkrest b/server/lib/checkrest new file mode 100755 index 00000000..3db161f5 --- /dev/null +++ b/server/lib/checkrest @@ -0,0 +1,136 @@ +#!/bin/bash + +#/** +#@file checktest +#@brief Run tests to check the OpenGnsys Server REST functions. +#@usage checktest [help] +#@warning This script inserts test data into the database and deletes it before finishing. +#@version 1.1.1 - Initial version. +#@author Ramón M. Gómez - ETSII Univ. Sevilla +#@date 2019-10-07 +#*/ ## + +PROG=$(basename "$0") +OPENGNSYS=/opt/opengnsys +CONFIGFILE=$OPENGNSYS/etc/ogAdmServer.cfg +RESTURL="https://localhost/opengnsys/rest" +source $OPENGNSYS/lib/ogfunctions.sh || exit 1 + +# Test a REST ROUTE. Parameters: Route Headers Data Agent +function route () { + local ROUTE PARAM METHOD HEADER DATA AGENT RET STATUS + ROUTE="$1" + PARAM="$2" + HEADER="$3" + DATA="$4" + AGENT="$5" + METHOD="${DATA:+POST}" + METHOD="${METHOD:-GET}" + RESP=$(curl -4ks -w "%{http_code}" ${HEADER:+-H "$HEADER"} ${DATA:+-d "$DATA"} ${AGENT:+-A "$AGENT"} "$RESTURL$ROUTE") + RET=$? + CODE="${RESP: -3}" + RESP="${RESP::-3}" + [ "$PARAM" ] && PARAM="($PARAM: $(jq -r ".$PARAM // \"not found\"" <<<"$RESP"))" + case "$CODE" in + 200) let OK=OK+1 + STATUS="OK $PARAM" ;; + 404) let FAIL=FAIL+1 + STATUS="FAIL ($CODE: $(echo $RESP))" ;; + 000) let FAIL=FAIL+1 + STATUS="FAIL (Connection error: $RET)" ;; + *) let FAIL=FAIL+1 + STATUS="FAIL ($CODE: $(jq -r '.message|gsub(":.*";"")' <<<"$RESP"))" ;; + esac + printf "%-40s: %s\n" "- $METHOD $ROUTE" "$STATUS" +} + +# Delete test data from the database. +function deletedata () { + # Delete test data, if exists. + DATA=" +DELETE FROM centros, administradores_centros USING centros INNER JOIN administradores_centros + WHERE centros.idcentro=administradores_centros.idcentro AND centros.nombrecentro='TestOU'; +DELETE FROM repositorios WHERE nombrerepositorio='TestRepo'; +DELETE FROM aulas WHERE nombreaula='TestLab'; +DELETE FROM ordenadores WHERE nombreordenador='TestClnt'; +" + dbexec "$DATA" +} + +# Load test data into the database. +function loaddata () { + # Insert test data. + DATA=" +INSERT INTO centros (nombrecentro, identidad, comentarios) + VALUES ('TestOU', 1, 'Tests'); +SET @ou_id := LAST_INSERT_ID(); +INSERT INTO administradores_centros (idusuario, idcentro) + VALUES (1, @ou_id); +INSERT INTO repositorios (nombrerepositorio, idcentro, ip) + VALUES ('TestRepo', @ou_id, '127.0.0.1'); +SET @repo_id := LAST_INSERT_ID(); +INSERT INTO aulas (nombreaula, idcentro, inremotepc) + VALUES ('TestLab', @ou_id, 0); +SET @lab_id := LAST_INSERT_ID(); +INSERT INTO ordenadores (nombreordenador, idrepositorio, idaula, ip, mac) + VALUES ('TestClnt', @id_repo, @lab_id, '127.0.0.1', '001122334455'); +SET @clnt_id := LAST_INSERT_ID(); +" + dbexec "$DATA" +} + +function runtests () { + local OK FAIL + + let OK=FAIL=0 + echo "Running tests..." + route "/info" "release" + route "/status" "cpu.usage" + DATA='{"username":"'$USUARIO'","password":"'$PASSWORD'"}' + route /login "" "" "$DATA" + HEADERS="Authorization: $(jq -r '.apikey' <<<"$RESP")" + route /ous + OU=$(jq -r '.[] | select(.name=="TestOU").id' <<<"$RESP") + route "/ous/$OU" "name" "$HEADERS" + route "/ous/$OU/repos" "" "$HEADERS" + REPO=$(jq -r '.[] | select(.name=="TestRepo").id' <<<"$RESP") + route "/ous/$OU/repos/$REPO" "name" "$HEADERS" + route "/ous/$OU/labs" "" "$HEADERS" + LAB=$(jq -r '.[] | select(.name=="TestLab").id' <<<"$RESP") + route "/ous/$OU/labs/$LAB" "name" "$HEADERS" + route "/ous/$OU/labs/$LAB/clients" "" "$HEADERS" + CLNT=$(jq -r '.[] | select(.name=="TestClnt").id' <<<"$RESP") + route "/ous/$OU/labs/$LAB/clients/$CLNT" "name" "$HEADERS" + read -r IP MAC <<<$(jq -r '.ip+" "+([.mac[0:2],.mac[2:4],.mac[4:6],.mac[6:8],.mac[8:10],.mac[10:12]] | join(":"))' <<<"$RESP") + route "/ous/$OU/labs/$LAB/clients/$CLNT/status" "status" "$HEADERS" + route "/ous/$OU/images" "" "$HEADERS" + AGENT="python-requests/test" + DATA='{"ip":"'$IP'","mac":"'$MAC'","ostype":"Windows","osversion":"Windows Test","secret":"'$(printf "%.sX" {1..32})'"}' + route "/ogagent/started" "" "" "$DATA" "$AGENT" + DATA='{"ip":"'$IP'","user":"test","language":"en","ostype":"Windows","osversion":"Windows 10 Test"}' + route "/ogagent/loggedin" "" "" "$DATA" "$AGENT" + route "/ogagent/loggedout" "" "" "$DATA" "$AGENT" + DATA='{"ip":"'$IP'","mac":"'$MAC'","ostype":"Windows","osversion":"Windows Test"}' + route "/ogagent/stopped" "" "" "$DATA" "$AGENT" + echo "Tests OK: $OK" + echo "Tests failed: $FAIL" +} + + +# Main program. + +# Show help. +[ "$*" == "help" ] && help +[ "$*" ] && raiseError usage +# Access control. +[ "$USER" == "root" ] || raiseError access "Need to be root." +[ -r $CONFIGFILE ] || raiseError access "Configuration file." +# Check dependencies. +which jq &>/dev/null || raiseError notfound "Need to install \"jq\"." + +source $CONFIGFILE +deletedata +loaddata +runtests +deletedata + diff --git a/server/lib/ogfunctions.sh b/server/lib/ogfunctions.sh index 34b2ab7b..4b61166b 100755 --- a/server/lib/ogfunctions.sh +++ b/server/lib/ogfunctions.sh @@ -68,6 +68,22 @@ function stop() { _service stop "$1" } +# Execute database operation. +function dbexec () { + MYCNF=$(mktemp) + trap "rm -f $MYCNF" 0 1 2 3 6 9 15 + touch $MYCNF + chmod 600 $MYCNF + cat << EOT > $MYCNF +[client] +user=$USUARIO +password=$PASSWORD +EOT + mysql --defaults-extra-file="$MYCNF" -D "$CATALOG" -s -N -e "$1" || \ + raiseError access "Cannot access the databse" + rm -f "$MYCNF" +} + ### Meta-functions and private functions. @@ -94,3 +110,4 @@ function _service() { raiseError notfound "Service $SERVICE" fi } + diff --git a/server/lib/security-config b/server/lib/security-config index 6d53d198..c5f11a98 100755 --- a/server/lib/security-config +++ b/server/lib/security-config @@ -32,7 +32,7 @@ if which ufw &>/dev/null; then ufw allow 2008,2009,2011/tcp # OpenGnsys services ufw allow 6881:6999/udp # BitTorrent ufw allow 9000/tcp # PHP-FPM - ufw allow 9000:9101/udp # Multicast + ufw allow 9000:9099/udp # Multicast # Applying configuration. ufw enable # FirewallD configuration. diff --git a/server/tftpboot/grub/default b/server/tftpboot/grub/default index 6c505de6..30253e26 100644 --- a/server/tftpboot/grub/default +++ b/server/tftpboot/grub/default @@ -1,14 +1,23 @@ -# Busca cargadores existentes por orden de prioridad e -# inicia el primero que encuentra. +# Busca cargadores existentes por orden de prioridad y +# muestra menú con las opciones. # Si no existe ningún cargador de arranque muestre mensaje de error. -set timeout=5 +set timeout=30 set detectado='no' # Compruebo si existen distintos cargadores. +echo "Searching Grub" +search --file --set rootGrub /EFI/grub/Boot/grubx64.efi +if [ "$rootGrub" != "" ]; then + set detectado='si' + menuentry "Grub" { + root="$rootGrub" + chainloader /EFI/grub/Boot/grubx64.efi +} +fi + echo "Searching rEFInd" search --file --set rootRefind /EFI/refind/shimx64.efi.signed if [ "$rootRefind" != "" ]; then - set detectado='si' menuentry "rEFInd" { root="$rootRefind" chainloader /EFI/refind/shimx64.efi.signed @@ -56,7 +65,7 @@ if [ "$rootUb" != "" ]; then fi -# Si no hay ningún sistam operativo muestro mensaje. +# Si no hay ningún sistema operativo muestro mensaje. if [ $detectado == 'no' ]; then menuentry "OpenGnsys no ha detectado ningún sistema operativo" { # para evitar mensajes de error. diff --git a/server/tftpboot/grub/examples/refind b/server/tftpboot/grub/examples/refind new file mode 100644 index 00000000..77e40c7a --- /dev/null +++ b/server/tftpboot/grub/examples/refind @@ -0,0 +1,4 @@ +##NO-TOCAR-ESTA-LINEA refind +search --file --set root /EFI/refind/shimx64.efi.signed +chainloader /EFI/refind/shimx64.efi.signed +boot diff --git a/server/tftpboot/grub/templates/00unknown b/server/tftpboot/grub/templates/00unknown index 3352a965..efd70778 100644 --- a/server/tftpboot/grub/templates/00unknown +++ b/server/tftpboot/grub/templates/00unknown @@ -1,30 +1,77 @@ ##NO-TOCAR-ESTA-LINEA Sin-designar -set default="0" -set timeout="30" - -menuentry 'ogLive' { -set ISODIR=ogLive -linux (tftp)/$ISODIR/ogvmlinuz ro boot=oginit quiet splash vga=788 irqpoll acpi=on og2nd=sqfs ogprotocol=smb ogactiveadmin=false ogdebug=false ogtmpfs=15 oglivedir=$ISODIR INFOHOST -initrd (tftp)/$ISODIR/oginitrd.img -boot -} -menuentry 'ReFind' { - root='hd0,gpt1' - chainloader /EFI/refind/shimx64.efi - boot -} -menuentry 'Part-01-02' { - root='hd0,gpt1' - chainloader /EFI/Part-01-02/Boot/ogloader.efi - boot -} -menuentry 'Windows' { - root='hd0,gpt1' - chainloader /EFI/Microsoft/Boot/bootmgfw.efi - boot +# +# Arranque por defecto en OpenGnsys +# Busca cargadores existentes por orden de prioridad y +# muestra menú con las opciones +# Si no existe ningún cargador de arranque muestra mensaje de error. +set timeout=30 + +set detectado='no' +# Compruebo si existen distintos cargadores. +echo "Searching Grub" +search --file --set rootGrub /EFI/grub/Boot/grubx64.efi +if [ "$rootGrub" != "" ]; then + set detectado='si' + menuentry "Grub" { + root="$rootGrub" + chainloader /EFI/grub/Boot/grubx64.efi } -menuentry 'Ubuntu' { - root='hd0,gpt1' - chainloader /EFI/ubuntu/grubx64.efi - boot +fi + +echo "Searching rEFInd" +search --file --set rootRefind /EFI/refind/shimx64.efi.signed +if [ "$rootRefind" != "" ]; then + menuentry "rEFInd" { + root="$rootRefind" + chainloader /EFI/refind/shimx64.efi.signed } +fi + +echo "Searching Part-01-02" +search --file --set rootP2 /EFI/Part-01-02/Boot/ogloader.efi +if [ "$rootP2" != "" ]; then + set detectado='si' + menuentry "Part-01-02" { + root="$rootP2" + chainloader /EFI/Part-01-02/Boot/ogloader.efi + } +fi + +echo "Searching Part-01-03" +search --file --set rootP3 /EFI/Part-01-03/Boot/ogloader.efi +if [ "$rootP3" != "" ]; then + set detectado='si' + menuentry "Part-01-03" { + root="$rootP3" + chainloader /EFI/Part-01-03/Boot/ogloader.efi + } +fi + +echo "Searching Microsoft" +search --file --set rootMS /EFI/Microsoft/Boot/bootmgfw.efi +if [ "$rootMS" != "" ]; then + set detectado='si' + menuentry "Microsoft" { + root="$rootMS" + chainloader /EFI/Microsoft/Boot/bootmgfw.efi + } +fi + +echo "Searching Ubuntu" +search --file --set rootUb /EFI/ubuntu/grubx64.efi +if [ "$rootUb" != "" ]; then + set detectado='si' + menuentry "Ubuntu" + root="$rootUb" + chainloader /EFI/ubuntu/grubx64.efi + } +fi + + +# Si no hay ningún sistema operativo muestro mensaje. +if [ $detectado == 'no' ]; then + menuentry "OpenGnsys no ha detectado ningún sistema operativo" { + # para evitar mensajes de error. + set root="(hd0,gpt1)" + } +fi diff --git a/server/tftpboot/grub/templates/10 b/server/tftpboot/grub/templates/10 index 82c44464..22e57bfe 100644 --- a/server/tftpboot/grub/templates/10 +++ b/server/tftpboot/grub/templates/10 @@ -1,6 +1,4 @@ ##NO-TOCAR-ESTA-LINEA 1hd -echo "rEFInd" - -root='hd0,gpt1' -chainloader /EFI/refind/shimx64.efi.signed +search --file --set root /EFI/grub/Boot/grubx64.efi +chainloader /EFI/grub/Boot/grubx64.efi boot diff --git a/server/tftpboot/grub/templates/11 b/server/tftpboot/grub/templates/11 index 06b34088..e17d387b 100644 --- a/server/tftpboot/grub/templates/11 +++ b/server/tftpboot/grub/templates/11 @@ -1,4 +1,4 @@ -##NO-TOCAR-ESTA-LINEA 1hd-1os -root='hd0,gpt1' -chainloader /EFI/Part-01-02/Boot/ogloader.efi +##NO-TOCAR-ESTA-LINEA 1hd-1partition +search --file --set root /EFI/Part-01-01/Boot/ogloader.efi +chainloader /EFI/Part-01-01/Boot/ogloader.efi boot diff --git a/server/tftpboot/grub/templates/12 b/server/tftpboot/grub/templates/12 index 6f22fc30..2bcf108d 100644 --- a/server/tftpboot/grub/templates/12 +++ b/server/tftpboot/grub/templates/12 @@ -1,4 +1,4 @@ -##NO-TOCAR-ESTA-LINEA 1hd-2os -root='hd0,gpt1' -chainloader /EFI/Part-01-03/Boot/ogloader.efi +##NO-TOCAR-ESTA-LINEA 1hd-2partition +search --file --set root /EFI/Part-01-02/Boot/ogloader.efi +chainloader /EFI/Part-01-02/Boot/ogloader.efi boot diff --git a/server/tftpboot/grub/templates/13 b/server/tftpboot/grub/templates/13 new file mode 100644 index 00000000..4c9d26a0 --- /dev/null +++ b/server/tftpboot/grub/templates/13 @@ -0,0 +1,4 @@ +##NO-TOCAR-ESTA-LINEA 1hd-3partition +search --file --set root /EFI/Part-01-03/Boot/ogloader.efi +chainloader /EFI/Part-01-03/Boot/ogloader.efi +boot diff --git a/server/tftpboot/menu.lst/templates/11 b/server/tftpboot/menu.lst/templates/11 index c1492b57..6635b495 100644 --- a/server/tftpboot/menu.lst/templates/11 +++ b/server/tftpboot/menu.lst/templates/11 @@ -1,6 +1,6 @@ -##NO-TOCAR-ESTA-LINEA 1hd-1os +##NO-TOCAR-ESTA-LINEA 1hd-1partition timeout 1 -title FirstDisk-FirstOperatingSystem +title FirstDisk-FirstPartition root (hd0,0) chainloader (hd0,0)+1 boot diff --git a/server/tftpboot/menu.lst/templates/12 b/server/tftpboot/menu.lst/templates/12 index 0db966b7..0843c3b1 100644 --- a/server/tftpboot/menu.lst/templates/12 +++ b/server/tftpboot/menu.lst/templates/12 @@ -1,6 +1,6 @@ -##NO-TOCAR-ESTA-LINEA 1hd-2os +##NO-TOCAR-ESTA-LINEA 1hd-2partition timeout 1 -title FirstHardDisk-SecondOperatingSystem +title FirstHardDisk-SecondPartition root (hd0,1) chainloader (hd0,1)+1 boot diff --git a/server/tftpboot/menu.lst/templates/13 b/server/tftpboot/menu.lst/templates/13 new file mode 100644 index 00000000..fedf8ebf --- /dev/null +++ b/server/tftpboot/menu.lst/templates/13 @@ -0,0 +1,8 @@ +##NO-TOCAR-ESTA-LINEA 1hd-3partition +timeout 1 +title FirstDisk-ThirdPartition +root (hd0,2) +chainloader (hd0,2)+1 +boot + + diff --git a/server/tftpboot/menu.lst/templates/pxe b/server/tftpboot/menu.lst/templates/pxe index bdf0fc54..5cd3fa16 100644 --- a/server/tftpboot/menu.lst/templates/pxe +++ b/server/tftpboot/menu.lst/templates/pxe @@ -8,14 +8,14 @@ set ISODIR=ogLive title firsboot -find --set-root --ignore-floppies --ignore-cd /ogboot.me +find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul cmp /ogboot.me /ogboot.firstboot || ls FALLBACK write /ogboot.firstboot iniciado chainloader +1 boot title secondboot -find --set-root --ignore-floppies --ignore-cd /ogboot.me +find --set-root --ignore-floppies --ignore-cd /ogboot.me checkrange 0x07 parttype > nul cmp /ogboot.me /ogboot.secondboot || ls FALLBACK write /ogboot.secondboot iniciado chainloader +1 |