source: admin/Sources/Services/ogAdmServer/sources/ogAdmServer.cpp @ 8b1c92b

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 8b1c92b was 2385710e, checked in by OpenGnSys Support Team <soporte-og@…>, 6 years ago

#915 Add POST "image/setup" command to REST API in ogAdmServer

This patch implements the command "image/setup" that provides partitioning and
formatting functionality.

Request:

POST /image/setup
{ "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"}]}

Reply:

200 OK

  • Property mode set to 100644
File size: 136.6 KB
RevLine 
[f679cf0]1// *******************************************************************************************************
[3ec149c]2// Servicio: ogAdmServer
3// Autor: José Manuel Alonso (E.T.S.I.I.) Universidad de Sevilla
4// Fecha Creación: Marzo-2010
5// Fecha Última modificación: Marzo-2010
6// Nombre del fichero: ogAdmServer.cpp
7// Descripción :Este fichero implementa el servicio de administración general del sistema
[f679cf0]8// *******************************************************************************************************
[3ec149c]9#include "ogAdmServer.h"
10#include "ogAdmLib.c"
[9baecf8]11#include <ev.h>
[13e48b4]12#include <syslog.h>
[332487d]13#include <sys/ioctl.h>
14#include <ifaddrs.h>
[165cea3]15#include <sys/types.h>
16#include <sys/stat.h>
17#include <fcntl.h>
[1a08c06]18#include <jansson.h>
[7cd0b13]19
20static char usuario[LONPRM]; // Usuario de acceso a la base de datos
21static char pasguor[LONPRM]; // Password del usuario
22static char datasource[LONPRM]; // Dirección IP del gestor de base de datos
23static char catalog[LONPRM]; // Nombre de la base de datos
[332487d]24static char interface[LONPRM]; // Interface name
[2ccec278]25static char auth_token[LONPRM]; // API token
[7cd0b13]26
[3ec149c]27//________________________________________________________________________________________________________
28//      Función: tomaConfiguracion
29//
30//      Descripción:
31//              Lee el fichero de configuración del servicio
32//      Parámetros:
33//              filecfg : Ruta completa al fichero de configuración
34//      Devuelve:
[5759db40]35//              true: Si el proceso es correcto
36//              false: En caso de ocurrir algún error
[3ec149c]37//________________________________________________________________________________________________________
[d647d81]38static bool tomaConfiguracion(const char *filecfg)
39{
[353da2d]40        char buf[1024], *line;
41        char *key, *value;
42        FILE *fcfg;
[3ec149c]43
44        if (filecfg == NULL || strlen(filecfg) == 0) {
[8c04716]45                syslog(LOG_ERR, "No configuration file has been specified\n");
[5759db40]46                return false;
[3ec149c]47        }
48
49        fcfg = fopen(filecfg, "rt");
50        if (fcfg == NULL) {
[8c04716]51                syslog(LOG_ERR, "Cannot open configuration file `%s'\n",
52                       filecfg);
[5759db40]53                return false;
[3ec149c]54        }
55
56        servidoradm[0] = (char) NULL; //inicializar variables globales
57
[353da2d]58        line = fgets(buf, sizeof(buf), fcfg);
59        while (line != NULL) {
60                const char *delim = "=";
61
62                line[strlen(line) - 1] = '\0';
63
64                key = strtok(line, delim);
65                value = strtok(NULL, delim);
66
67                if (!strcmp(StrToUpper(key), "SERVIDORADM"))
68                        snprintf(servidoradm, sizeof(servidoradm), "%s", value);
69                else if (!strcmp(StrToUpper(key), "PUERTO"))
70                        snprintf(puerto, sizeof(puerto), "%s", value);
71                else if (!strcmp(StrToUpper(key), "USUARIO"))
72                        snprintf(usuario, sizeof(usuario), "%s", value);
73                else if (!strcmp(StrToUpper(key), "PASSWORD"))
74                        snprintf(pasguor, sizeof(pasguor), "%s", value);
75                else if (!strcmp(StrToUpper(key), "DATASOURCE"))
76                        snprintf(datasource, sizeof(datasource), "%s", value);
77                else if (!strcmp(StrToUpper(key), "CATALOG"))
78                        snprintf(catalog, sizeof(catalog), "%s", value);
[332487d]79                else if (!strcmp(StrToUpper(key), "INTERFACE"))
80                        snprintf(interface, sizeof(interface), "%s", value);
[2ccec278]81                else if (!strcmp(StrToUpper(key), "APITOKEN"))
82                        snprintf(auth_token, sizeof(auth_token), "%s", value);
[353da2d]83
84                line = fgets(buf, sizeof(buf), fcfg);
[3ec149c]85        }
[353da2d]86
[bf17dde]87        fclose(fcfg);
88
[f613fb2]89        if (!servidoradm[0]) {
[8c04716]90                syslog(LOG_ERR, "Missing SERVIDORADM in configuration file\n");
[5759db40]91                return false;
[3ec149c]92        }
[f613fb2]93        if (!puerto[0]) {
[8c04716]94                syslog(LOG_ERR, "Missing PUERTO in configuration file\n");
[5759db40]95                return false;
[3ec149c]96        }
[f613fb2]97        if (!usuario[0]) {
[8c04716]98                syslog(LOG_ERR, "Missing USUARIO in configuration file\n");
[5759db40]99                return false;
[3ec149c]100        }
[f613fb2]101        if (!pasguor[0]) {
[8c04716]102                syslog(LOG_ERR, "Missing PASSWORD in configuration file\n");
[5759db40]103                return false;
[3ec149c]104        }
[f613fb2]105        if (!datasource[0]) {
[8c04716]106                syslog(LOG_ERR, "Missing DATASOURCE in configuration file\n");
[5759db40]107                return false;
[3ec149c]108        }
[f613fb2]109        if (!catalog[0]) {
[8c04716]110                syslog(LOG_ERR, "Missing CATALOG in configuration file\n");
[5759db40]111                return false;
[3ec149c]112        }
[332487d]113        if (!interface[0])
114                syslog(LOG_ERR, "Missing INTERFACE in configuration file\n");
[0a73ecf7]115
[5759db40]116        return true;
[3ec149c]117}
[0a73ecf7]118
[9baecf8]119enum og_client_state {
120        OG_CLIENT_RECEIVING_HEADER      = 0,
121        OG_CLIENT_RECEIVING_PAYLOAD,
122        OG_CLIENT_PROCESSING_REQUEST,
123};
124
[d8a2d5f]125#define OG_MSG_REQUEST_MAXLEN   4096
126
[9baecf8]127/* Shut down connection if there is no complete message after 10 seconds. */
128#define OG_CLIENT_TIMEOUT       10
129
130struct og_client {
131        struct ev_io            io;
132        struct ev_timer         timer;
[13e48b4]133        struct sockaddr_in      addr;
[9baecf8]134        enum og_client_state    state;
[d8a2d5f]135        char                    buf[OG_MSG_REQUEST_MAXLEN];
[9baecf8]136        unsigned int            buf_len;
137        unsigned int            msg_len;
[2e0c063]138        int                     keepalive_idx;
[1a08c06]139        bool                    rest;
[8793b71]140        int                     content_length;
[2ccec278]141        char                    auth_token[64];
[9baecf8]142};
143
144static inline int og_client_socket(const struct og_client *cli)
145{
146        return cli->io.fd;
147}
148
[3ec149c]149// ________________________________________________________________________________________________________
150// Función: clienteDisponible
151//
152//      Descripción:
153//              Comprueba la disponibilidad del cliente para recibir comandos interactivos
154//      Parametros:
155//              - ip : La ip del cliente a buscar
156//              - idx: (Salida)  Indice que ocupa el cliente, de estar ya registrado
157//      Devuelve:
[5759db40]158//              true: Si el cliente está disponible
159//              false: En caso contrario
[3ec149c]160// ________________________________________________________________________________________________________
[d647d81]161bool clienteDisponible(char *ip, int* idx)
162{
[3ec149c]163        int estado;
164
165        if (clienteExistente(ip, idx)) {
166                estado = strcmp(tbsockets[*idx].estado, CLIENTE_OCUPADO); // Cliente ocupado
167                if (estado == 0)
[5759db40]168                        return false;
[3ec149c]169
170                estado = strcmp(tbsockets[*idx].estado, CLIENTE_APAGADO); // Cliente apagado
171                if (estado == 0)
[5759db40]172                        return false;
[3ec149c]173
174                estado = strcmp(tbsockets[*idx].estado, CLIENTE_INICIANDO); // Cliente en proceso de inclusión
175                if (estado == 0)
[5759db40]176                        return false;
[3ec149c]177
[5759db40]178                return true; // En caso contrario el cliente está disponible
[3ec149c]179        }
[5759db40]180        return false; // Cliente no está registrado en el sistema
[3ec149c]181}
182// ________________________________________________________________________________________________________
183// Función: clienteExistente
184//
185//      Descripción:
186//              Comprueba si el cliente está registrado en la tabla de socket del sistema
187//      Parametros:
188//              - ip : La ip del cliente a buscar
189//              - idx:(Salida)  Indice que ocupa el cliente, de estar ya registrado
190//      Devuelve:
[5759db40]191//              true: Si el cliente está registrado
192//              false: En caso contrario
[3ec149c]193// ________________________________________________________________________________________________________
[d647d81]194bool clienteExistente(char *ip, int* idx)
195{
[3ec149c]196        int i;
197        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
198                if (contieneIP(ip, tbsockets[i].ip)) { // Si existe la IP en la cadena
199                        *idx = i;
[5759db40]200                        return true;
[3ec149c]201                }
202        }
[5759db40]203        return false;
[3ec149c]204}
205// ________________________________________________________________________________________________________
206// Función: hayHueco
207//
208//      Descripción:
[5759db40]209//              Esta función devuelve true o false dependiendo de que haya hueco en la tabla de sockets para un nuevo cliente.
[3ec149c]210//      Parametros:
211//              - idx:   Primer indice libre que se podrn utilizar
212//      Devuelve:
[5759db40]213//              true: Si el proceso es correcto
214//              false: En caso de ocurrir algún error
[3ec149c]215// ________________________________________________________________________________________________________
[d647d81]216static bool hayHueco(int *idx)
217{
[3ec149c]218        int i;
219
220        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
221                if (strncmp(tbsockets[i].ip, "\0", 1) == 0) { // Hay un hueco
222                        *idx = i;
[5759db40]223                        return true;
[3ec149c]224                }
225        }
[5759db40]226        return false;
[3ec149c]227}
228// ________________________________________________________________________________________________________
[f679cf0]229// Función: InclusionClienteWin
230//
231//      Descripción:
232//              Esta función incorpora el socket de un nuevo cliente Windows o Linux a la tabla de clientes
233//      Parámetros:
234//              - socket_c: Socket del cliente que envió el mensaje
235//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
236//      Devuelve:
[5759db40]237//              true: Si el proceso es correcto
238//              false: En caso de ocurrir algún error
[f679cf0]239// ________________________________________________________________________________________________________
[9baecf8]240static bool InclusionClienteWinLnx(TRAMA *ptrTrama, struct og_client *cli)
[d647d81]241{
[9baecf8]242        int socket_c = og_client_socket(cli);
[f679cf0]243        int res,idordenador,lon;
244        char nombreordenador[LONFIL];
[9baecf8]245
246        res = procesoInclusionClienteWinLnx(socket_c, ptrTrama, &idordenador,
247                                            nombreordenador);
248
[f679cf0]249        // Prepara la trama de respuesta
250
251        initParametros(ptrTrama,0);
252        ptrTrama->tipo=MSG_RESPUESTA;
253        lon = sprintf(ptrTrama->parametros, "nfn=RESPUESTA_InclusionClienteWinLnx\r");
254        lon += sprintf(ptrTrama->parametros + lon, "ido=%d\r", idordenador);
255        lon += sprintf(ptrTrama->parametros + lon, "npc=%s\r", nombreordenador);       
256        lon += sprintf(ptrTrama->parametros + lon, "res=%d\r", res);   
[8c04716]257
[ba03878]258        if (!mandaTrama(&socket_c, ptrTrama)) {
[8c04716]259                syslog(LOG_ERR, "failed to send response to %s:%hu reason=%s\n",
260                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
261                       strerror(errno));
[5759db40]262                return false;
[f679cf0]263        }
[5759db40]264        return true;
[f679cf0]265}
266// ________________________________________________________________________________________________________
267// Función: procesoInclusionClienteWinLnx
268//
269//      Descripción:
270//              Implementa el proceso de inclusión en el sistema del Cliente Windows o Linux
271//      Parámetros de entrada:
272//              - socket_c: Socket del cliente que envió el mensaje
273//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
274//      Parámetros de salida:
275//              - ido: Identificador del ordenador
276//              - nombreordenador: Nombre del ordenador
277//      Devuelve:
278//              Código del error producido en caso de ocurrir algún error, 0 si el proceso es correcto
279// ________________________________________________________________________________________________________
[d647d81]280bool procesoInclusionClienteWinLnx(int socket_c, TRAMA *ptrTrama, int *idordenador, char *nombreordenador)
[f679cf0]281 {
282        char msglog[LONSTD], sqlstr[LONSQL];
283        Database db;
284        Table tbl;
285        char *iph;
[35cc972]286
[f679cf0]287        // Toma parámetros
288        iph = copiaParametro("iph",ptrTrama); // Toma ip
289
[8c04716]290        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[21bfeb0]291                liberaMemoria(iph);
[f679cf0]292                db.GetErrorErrStr(msglog);
[8c04716]293                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
294                       __func__, __LINE__, msglog);
[71f5b7d]295                return false;
[f679cf0]296        }
297
298        // Recupera los datos del cliente
299        sprintf(sqlstr,
300                        "SELECT idordenador,nombreordenador FROM ordenadores "
301                                " WHERE ordenadores.ip = '%s'", iph);
302
[8c04716]303        if (!db.Execute(sqlstr, tbl)) {
[21bfeb0]304                liberaMemoria(iph);
[f679cf0]305                db.GetErrorErrStr(msglog);
[8c04716]306                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
307                       __func__, __LINE__, msglog);
[21bfeb0]308                db.Close();
[71f5b7d]309                return false;
[f679cf0]310        }
311
[8c04716]312        if (tbl.ISEOF()) {
[21bfeb0]313                liberaMemoria(iph);
[8c04716]314                syslog(LOG_ERR, "client does not exist in database (%s:%d)\n",
315                       __func__, __LINE__);
[21bfeb0]316                db.liberaResult(tbl);
317                db.Close();
[71f5b7d]318                return false;
[f679cf0]319        }
320
[8c04716]321        syslog(LOG_DEBUG, "Client %s requesting inclusion\n", iph);
322
[f679cf0]323        if (!tbl.Get("idordenador", *idordenador)) {
[21bfeb0]324                liberaMemoria(iph);
325                db.liberaResult(tbl);
[f679cf0]326                tbl.GetErrorErrStr(msglog);
[35cc972]327                og_info(msglog);
[21bfeb0]328                db.Close();
[5759db40]329                return false;
[f679cf0]330        }
331        if (!tbl.Get("nombreordenador", nombreordenador)) {
[21bfeb0]332                liberaMemoria(iph);
333                db.liberaResult(tbl);
[f679cf0]334                tbl.GetErrorErrStr(msglog);
[35cc972]335                og_info(msglog);
[21bfeb0]336                db.Close();
[5759db40]337                return false;
[f679cf0]338        }
[21bfeb0]339        db.liberaResult(tbl);
[f679cf0]340        db.Close();
[71f5b7d]341
[f679cf0]342        if (!registraCliente(iph)) { // Incluyendo al cliente en la tabla de sokets
[0a73ecf7]343                liberaMemoria(iph);
[8c04716]344                syslog(LOG_ERR, "client table is full\n");
[71f5b7d]345                return false;
[f679cf0]346        }
[0a73ecf7]347        liberaMemoria(iph);
[71f5b7d]348        return true;
[f679cf0]349}
350// ________________________________________________________________________________________________________
[3ec149c]351// Función: InclusionCliente
352//
353//      Descripción:
354//              Esta función incorpora el socket de un nuevo cliente a la tabla de clientes y le devuelve alguna de sus propiedades:
355//              nombre, identificador, tamaño de la caché , etc ...
356//      Parámetros:
357//              - socket_c: Socket del cliente que envió el mensaje
358//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
359//      Devuelve:
[5759db40]360//              true: Si el proceso es correcto
361//              false: En caso de ocurrir algún error
[3ec149c]362// ________________________________________________________________________________________________________
[9baecf8]363static bool InclusionCliente(TRAMA *ptrTrama, struct og_client *cli)
[d647d81]364{
[9baecf8]365        int socket_c = og_client_socket(cli);
366
[8c04716]367        if (!procesoInclusionCliente(cli, ptrTrama)) {
[3ec149c]368                initParametros(ptrTrama,0);
369                strcpy(ptrTrama->parametros, "nfn=RESPUESTA_InclusionCliente\rres=0\r");
[ba03878]370                if (!mandaTrama(&socket_c, ptrTrama)) {
[8c04716]371                        syslog(LOG_ERR, "failed to send response to %s:%hu reason=%s\n",
372                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
373                               strerror(errno));
[5759db40]374                        return false;
[3ec149c]375                }
376        }
[5759db40]377        return true;
[d647d81]378}
[3ec149c]379// ________________________________________________________________________________________________________
380// Función: procesoInclusionCliente
381//
382//      Descripción:
383//              Implementa el proceso de inclusión en el sistema del Cliente
384//      Parámetros:
385//              - socket_c: Socket del cliente que envió el mensaje
386//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
387//      Devuelve:
[5759db40]388//              true: Si el proceso es correcto
389//              false: En caso de ocurrir algún error
[3ec149c]390// ________________________________________________________________________________________________________
[8c04716]391bool procesoInclusionCliente(struct og_client *cli, TRAMA *ptrTrama)
[d647d81]392{
[8c04716]393        int socket_c = og_client_socket(cli);
[3ec149c]394        char msglog[LONSTD], sqlstr[LONSQL];
395        Database db;
396        Table tbl;
397
398        char *iph, *cfg;
399        char nombreordenador[LONFIL];
400        int lon, resul, idordenador, idmenu, cache, idproautoexec, idaula, idcentro;
401
402        // Toma parámetros
403        iph = copiaParametro("iph",ptrTrama); // Toma ip
404        cfg = copiaParametro("cfg",ptrTrama); // Toma configuracion
405
[8c04716]406        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[21bfeb0]407                liberaMemoria(iph);
408                liberaMemoria(cfg);
[3ec149c]409                db.GetErrorErrStr(msglog);
[8c04716]410                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
411                       __func__, __LINE__, msglog);
[5759db40]412                return false;
[3ec149c]413        }
414
415        // Recupera los datos del cliente
416        sprintf(sqlstr,
417                        "SELECT ordenadores.*,aulas.idaula,centros.idcentro FROM ordenadores "
418                                " INNER JOIN aulas ON aulas.idaula=ordenadores.idaula"
419                                " INNER JOIN centros ON centros.idcentro=aulas.idcentro"
420                                " WHERE ordenadores.ip = '%s'", iph);
421
[8c04716]422        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]423                db.GetErrorErrStr(msglog);
[8c04716]424                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
425                       __func__, __LINE__, msglog);
[5759db40]426                return false;
[3ec149c]427        }
428
[8c04716]429        if (tbl.ISEOF()) {
430                syslog(LOG_ERR, "client does not exist in database (%s:%d)\n",
431                       __func__, __LINE__);
[5759db40]432                return false;
[3ec149c]433        }
434
[8c04716]435        syslog(LOG_DEBUG, "Client %s requesting inclusion\n", iph);
436
[3ec149c]437        if (!tbl.Get("idordenador", idordenador)) {
438                tbl.GetErrorErrStr(msglog);
[35cc972]439                og_info(msglog);
[5759db40]440                return false;
[3ec149c]441        }
442        if (!tbl.Get("nombreordenador", nombreordenador)) {
443                tbl.GetErrorErrStr(msglog);
[35cc972]444                og_info(msglog);
[5759db40]445                return false;
[3ec149c]446        }
447        if (!tbl.Get("idmenu", idmenu)) {
448                tbl.GetErrorErrStr(msglog);
[35cc972]449                og_info(msglog);
[5759db40]450                return false;
[3ec149c]451        }
452        if (!tbl.Get("cache", cache)) {
453                tbl.GetErrorErrStr(msglog);
[35cc972]454                og_info(msglog);
[5759db40]455                return false;
[3ec149c]456        }
457        if (!tbl.Get("idproautoexec", idproautoexec)) {
458                tbl.GetErrorErrStr(msglog);
[35cc972]459                og_info(msglog);
[5759db40]460                return false;
[3ec149c]461        }
462        if (!tbl.Get("idaula", idaula)) {
463                tbl.GetErrorErrStr(msglog);
[35cc972]464                og_info(msglog);
[5759db40]465                return false;
[3ec149c]466        }
467        if (!tbl.Get("idcentro", idcentro)) {
468                tbl.GetErrorErrStr(msglog);
[35cc972]469                og_info(msglog);
[5759db40]470                return false;
[3ec149c]471        }
472
473        resul = actualizaConfiguracion(db, tbl, cfg, idordenador); // Actualiza la configuración del ordenador
[0a73ecf7]474        liberaMemoria(cfg);
[3ec149c]475        db.Close();
476
477        if (!resul) {
[0a73ecf7]478                liberaMemoria(iph);
[8c04716]479                syslog(LOG_ERR, "Cannot add client to database\n");
[5759db40]480                return false;
[3ec149c]481        }
482
483        if (!registraCliente(iph)) { // Incluyendo al cliente en la tabla de sokets
[0a73ecf7]484                liberaMemoria(iph);
[8c04716]485                syslog(LOG_ERR, "client table is full\n");
[5759db40]486                return false;
[3ec149c]487        }
488
489        /*------------------------------------------------------------------------------------------------------------------------------
490         Prepara la trama de respuesta
491         -------------------------------------------------------------------------------------------------------------------------------*/
492        initParametros(ptrTrama,0);
493        ptrTrama->tipo=MSG_RESPUESTA;
494        lon = sprintf(ptrTrama->parametros, "nfn=RESPUESTA_InclusionCliente\r");
495        lon += sprintf(ptrTrama->parametros + lon, "ido=%d\r", idordenador);
496        lon += sprintf(ptrTrama->parametros + lon, "npc=%s\r", nombreordenador);
497        lon += sprintf(ptrTrama->parametros + lon, "che=%d\r", cache);
498        lon += sprintf(ptrTrama->parametros + lon, "exe=%d\r", idproautoexec);
499        lon += sprintf(ptrTrama->parametros + lon, "ida=%d\r", idaula);
500        lon += sprintf(ptrTrama->parametros + lon, "idc=%d\r", idcentro);
501        lon += sprintf(ptrTrama->parametros + lon, "res=%d\r", 1); // Confirmación proceso correcto
502
[ba03878]503        if (!mandaTrama(&socket_c, ptrTrama)) {
[8c04716]504                syslog(LOG_ERR, "failed to send response to %s:%hu reason=%s\n",
505                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
506                       strerror(errno));
[5759db40]507                return false;
[3ec149c]508        }
[0a73ecf7]509        liberaMemoria(iph);
[5759db40]510        return true;
[3ec149c]511}
512// ________________________________________________________________________________________________________
513// Función: actualizaConfiguracion
514//
515//      Descripción:
516//              Esta función actualiza la base de datos con la configuracion de particiones de un cliente
517//      Parámetros:
518//              - db: Objeto base de datos (ya operativo)
519//              - tbl: Objeto tabla
520//              - cfg: cadena con una Configuración
521//              - ido: Identificador del ordenador cliente
522//      Devuelve:
[5759db40]523//              true: Si el proceso es correcto
524//              false: En caso de ocurrir algún error
[3ec149c]525//      Especificaciones:
526//              Los parametros de la configuración son:
527//                      par= Número de partición
528//                      cpt= Codigo o tipo de partición
529//                      sfi= Sistema de ficheros que está implementado en la partición
530//                      soi= Nombre del sistema de ficheros instalado en la partición
531//                      tam= Tamaño de la partición
532// ________________________________________________________________________________________________________
[d647d81]533bool actualizaConfiguracion(Database db, Table tbl, char *cfg, int ido)
[3ec149c]534{
535        char msglog[LONSTD], sqlstr[LONSQL];
[7224a0a]536        int lon, p, c,i, dato, swu, idsoi, idsfi,k;
[0f1e5ad]537        char *ptrPar[MAXPAR], *ptrCfg[7], *ptrDual[2], tbPar[LONSTD];
[db4d467]538        char *ser, *disk, *par, *cpt, *sfi, *soi, *tam, *uso; // Parametros de configuración.
[3ec149c]539
[0d6ed7ac]540        lon = 0;
[3ec149c]541        p = splitCadena(ptrPar, cfg, '\n');
542        for (i = 0; i < p; i++) {
543                c = splitCadena(ptrCfg, ptrPar[i], '\t');
[db4d467]544
545                // Si la 1ª línea solo incluye el número de serie del equipo; actualizar BD.
546                if (i == 0 && c == 1) {
547                        splitCadena(ptrDual, ptrCfg[0], '=');
548                        ser = ptrDual[1];
549                        if (strlen(ser) > 0) {
550                                // Solo actualizar si número de serie no existía.
551                                sprintf(sqlstr, "UPDATE ordenadores SET numserie='%s'"
[ac933ca]552                                                " WHERE idordenador=%d AND numserie IS NULL",
[db4d467]553                                                ser, ido);
554                                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
555                                        db.GetErrorErrStr(msglog);
[35cc972]556                                        og_info(msglog);
[5759db40]557                                        return false;
[db4d467]558                                }
559                        }
560                        continue;
561                }
562
563                // Distribución de particionado.
[b0c9683]564                disk = par = cpt = sfi = soi = tam = uso = NULL;
[db4d467]565
[3ec149c]566                splitCadena(ptrDual, ptrCfg[0], '=');
[ba98026]567                disk = ptrDual[1]; // Número de disco
[3ec149c]568
569                splitCadena(ptrDual, ptrCfg[1], '=');
[ba98026]570                par = ptrDual[1]; // Número de partición
571
[5f9eca0]572                k=splitCadena(ptrDual, ptrCfg[2], '=');
573                if(k==2){
574                        cpt = ptrDual[1]; // Código de partición
575                }else{
[db4d467]576                        cpt = (char*)"0";
[5f9eca0]577                }
[3ec149c]578
[ba98026]579                k=splitCadena(ptrDual, ptrCfg[3], '=');
[3ec149c]580                if(k==2){
581                        sfi = ptrDual[1]; // Sistema de ficheros
[0a73ecf7]582                        /* Comprueba existencia del s0xistema de ficheros instalado */
[3ec149c]583                        idsfi = checkDato(db, tbl, sfi, "sistemasficheros", "descripcion","idsistemafichero");
584                }
585                else
586                        idsfi=0;
587
[ba98026]588                k=splitCadena(ptrDual, ptrCfg[4], '=');
[3ec149c]589                if(k==2){ // Sistema operativo detecdtado
590                        soi = ptrDual[1]; // Nombre del S.O. instalado
591                        /* Comprueba existencia del sistema operativo instalado */
592                        idsoi = checkDato(db, tbl, soi, "nombresos", "nombreso", "idnombreso");
593                }
594                else
595                        idsoi=0;
596
[ba98026]597                splitCadena(ptrDual, ptrCfg[5], '=');
[3ec149c]598                tam = ptrDual[1]; // Tamaño de la partición
599
[b0c9683]600                splitCadena(ptrDual, ptrCfg[6], '=');
601                uso = ptrDual[1]; // Porcentaje de uso del S.F.
602
[0d6ed7ac]603                lon += sprintf(tbPar + lon, "(%s, %s),", disk, par);
[3ec149c]604
[b0c9683]605                sprintf(sqlstr, "SELECT numdisk, numpar, codpar, tamano, uso, idsistemafichero, idnombreso"
606                                "  FROM ordenadores_particiones"
607                                " WHERE idordenador=%d AND numdisk=%s AND numpar=%s",
[ba98026]608                                ido, disk, par);
[6e235cd]609
610
[8c04716]611                if (!db.Execute(sqlstr, tbl)) {
[3ec149c]612                        db.GetErrorErrStr(msglog);
[8c04716]613                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
614                               __func__, __LINE__, msglog);
[5759db40]615                        return false;
[3ec149c]616                }
617                if (tbl.ISEOF()) { // Si no existe el registro
[b0c9683]618                        sprintf(sqlstr, "INSERT INTO ordenadores_particiones(idordenador,numdisk,numpar,codpar,tamano,uso,idsistemafichero,idnombreso,idimagen)"
619                                        " VALUES(%d,%s,%s,0x%s,%s,%s,%d,%d,0)",
620                                        ido, disk, par, cpt, tam, uso, idsfi, idsoi);
[6e235cd]621
622
[3ec149c]623                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
624                                db.GetErrorErrStr(msglog);
[35cc972]625                                og_info(msglog);
[5759db40]626                                return false;
[3ec149c]627                        }
628                } else { // Existe el registro
[5759db40]629                        swu = true; // Se supone que algún dato ha cambiado
[3ec149c]630                        if (!tbl.Get("codpar", dato)) { // Toma dato
631                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]632                                og_info(msglog);
[5759db40]633                                return false;
[3ec149c]634                        }
[e66ce87]635                        if (strtol(cpt, NULL, 16) == dato) {// Parámetro tipo de partición (hexadecimal) igual al almacenado (decimal)
[3ec149c]636                                if (!tbl.Get("tamano", dato)) { // Toma dato
637                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]638                                        og_info(msglog);
[5759db40]639                                        return false;
[3ec149c]640                                }
641                                if (atoi(tam) == dato) {// Parámetro tamaño igual al almacenado
[bbd1290]642                                        if (!tbl.Get("idsistemafichero", dato)) { // Toma dato
[3ec149c]643                                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]644                                                og_info(msglog);
[5759db40]645                                                return false;
[3ec149c]646                                        }
[bbd1290]647                                        if (idsfi == dato) {// Parámetro sistema de fichero igual al almacenado
648                                                if (!tbl.Get("idnombreso", dato)) { // Toma dato
[3ec149c]649                                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]650                                                        og_info(msglog);
[5759db40]651                                                        return false;
[3ec149c]652                                                }
[bbd1290]653                                                if (idsoi == dato) {// Parámetro sistema de fichero distinto al almacenado
[5759db40]654                                                        swu = false; // Todos los parámetros de la partición son iguales, no se actualiza
[3ec149c]655                                                }
656                                        }
657                                }
658                        }
659                        if (swu) { // Hay que actualizar los parámetros de la partición
660                                sprintf(sqlstr, "UPDATE ordenadores_particiones SET "
661                                        " codpar=0x%s,"
662                                        " tamano=%s,"
[b0c9683]663                                        " uso=%s,"
[3ec149c]664                                        " idsistemafichero=%d,"
665                                        " idnombreso=%d,"
[c916af9]666                                        " idimagen=0,"
667                                        " idperfilsoft=0,"
668                                        " fechadespliegue=NULL"
[ba98026]669                                        " WHERE idordenador=%d AND numdisk=%s AND numpar=%s",
[b0c9683]670                                        cpt, tam, uso, idsfi, idsoi, ido, disk, par);
[bbd1290]671                        } else {  // Actualizar porcentaje de uso.
672                                sprintf(sqlstr, "UPDATE ordenadores_particiones SET "
673                                        " uso=%s"
674                                        " WHERE idordenador=%d AND numdisk=%s AND numpar=%s",
675                                        uso, ido, disk, par);
676                        }
[8c04716]677                        if (!db.Execute(sqlstr, tbl)) {
[bbd1290]678                                db.GetErrorErrStr(msglog);
[8c04716]679                                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
680                                       __func__, __LINE__, msglog);
[5759db40]681                                return false;
[3ec149c]682                        }
683                }
684        }
[0d6ed7ac]685        lon += sprintf(tbPar + lon, "(0,0)");
[3ec149c]686        // Eliminar particiones almacenadas que ya no existen
[0d6ed7ac]687        sprintf(sqlstr, "DELETE FROM ordenadores_particiones WHERE idordenador=%d AND (numdisk, numpar) NOT IN (%s)",
688                        ido, tbPar);
[8c04716]689        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]690                db.GetErrorErrStr(msglog);
[8c04716]691                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
692                       __func__, __LINE__, msglog);
[5759db40]693                return false;
[3ec149c]694        }
[5759db40]695        return true;
[3ec149c]696}
697// ________________________________________________________________________________________________________
698// Función: checkDato
699//
700//      Descripción:
701//               Esta función comprueba si existe un dato en una tabla y si no es así lo incluye. devuelve en
702//              cualquier caso el identificador del registro existenet o del insertado
703//      Parámetros:
704//              - db: Objeto base de datos (ya operativo)
705//              - tbl: Objeto tabla
706//              - dato: Dato
707//              - tabla: Nombre de la tabla
708//              - nomdato: Nombre del dato en la tabla
709//              - nomidentificador: Nombre del identificador en la tabla
710//      Devuelve:
711//              El identificador del registro existente o el del insertado
712//
713//      Especificaciones:
714//              En caso de producirse algún error se devuelve el valor 0
715// ________________________________________________________________________________________________________
716
[d647d81]717int checkDato(Database db, Table tbl, char *dato, const char *tabla,
718                     const char *nomdato, const char *nomidentificador)
719{
[3ec149c]720        char msglog[LONSTD], sqlstr[LONSQL];
721        int identificador;
722
723        if (strlen(dato) == 0)
724                return (0); // EL dato no tiene valor
725        sprintf(sqlstr, "SELECT %s FROM %s WHERE %s ='%s'", nomidentificador,
726                        tabla, nomdato, dato);
727
728        // Ejecuta consulta
[8c04716]729        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]730                db.GetErrorErrStr(msglog);
[8c04716]731                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
732                       __func__, __LINE__, msglog);
[3ec149c]733                return (0);
734        }
735        if (tbl.ISEOF()) { //  Software NO existente
[df052e1]736                sprintf(sqlstr, "INSERT INTO %s (%s) VALUES('%s')", tabla, nomdato, dato);
[3ec149c]737                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
738                        db.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]739                        og_info(msglog);
[3ec149c]740                        return (0);
741                }
742                // Recupera el identificador del software
743                sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
744                if (!db.Execute(sqlstr, tbl)) { // Error al leer
745                        db.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]746                        og_info(msglog);
[3ec149c]747                        return (0);
748                }
749                if (!tbl.ISEOF()) { // Si existe registro
750                        if (!tbl.Get("identificador", identificador)) {
751                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]752                                og_info(msglog);
[3ec149c]753                                return (0);
754                        }
755                }
756        } else {
757                if (!tbl.Get(nomidentificador, identificador)) { // Toma dato
758                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]759                        og_info(msglog);
[3ec149c]760                        return (0);
761                }
762        }
763        return (identificador);
764}
765// ________________________________________________________________________________________________________
766// Función: registraCliente
767//
768//      Descripción:
769//               Incluye al cliente en la tabla de sokets
770//      Parámetros:
771//              - iph: Dirección ip del cliente
772//      Devuelve:
[5759db40]773//              true: Si el proceso es correcto
774//              false: En caso de ocurrir algún error
[3ec149c]775// ________________________________________________________________________________________________________
[d647d81]776bool registraCliente(char *iph)
777{
[3ec149c]778        int idx;
779
780        if (!clienteExistente(iph, &idx)) { // Si no existe la IP ...
781                if (!hayHueco(&idx)) { // Busca hueco para el nuevo cliente
[5759db40]782                        return false; // No hay huecos
[3ec149c]783                }
784        }
785        strcpy(tbsockets[idx].ip, iph); // Copia IP
786        strcpy(tbsockets[idx].estado, CLIENTE_INICIANDO); // Actualiza el estado del cliente
[5759db40]787        return true;
[3ec149c]788}
789// ________________________________________________________________________________________________________
790// Función: AutoexecCliente
791//
792//      Descripción:
793//              Envía archivo de autoexec al cliente
794//      Parámetros:
795//              - socket_c: Socket del cliente que envió el mensaje
796//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
797//      Devuelve:
[5759db40]798//              true: Si el proceso es correcto
799//              false: En caso de ocurrir algún error
[3ec149c]800// ________________________________________________________________________________________________________
[9baecf8]801static bool AutoexecCliente(TRAMA *ptrTrama, struct og_client *cli)
[d647d81]802{
[9baecf8]803        int socket_c = og_client_socket(cli);
[3ec149c]804        int lon;
805        char *iph, *exe, msglog[LONSTD];
806        Database db;
807        FILE *fileexe;
808        char fileautoexec[LONPRM];
809        char parametros[LONGITUD_PARAMETROS];
810
811        iph = copiaParametro("iph",ptrTrama); // Toma dirección IP del cliente
812        exe = copiaParametro("exe",ptrTrama); // Toma identificador del procedimiento inicial
813
814        sprintf(fileautoexec, "/tmp/Sautoexec-%s", iph);
[0a73ecf7]815        liberaMemoria(iph);
[3ec149c]816        fileexe = fopen(fileautoexec, "wb"); // Abre fichero de script
817        if (fileexe == NULL) {
[8c04716]818                syslog(LOG_ERR, "cannot create temporary file\n");
[5759db40]819                return false;
[3ec149c]820        }
821
[8c04716]822        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]823                db.GetErrorErrStr(msglog);
[8c04716]824                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
825                       __func__, __LINE__, msglog);
[5759db40]826                return false;
[3ec149c]827        }
828        initParametros(ptrTrama,0);
829        if (recorreProcedimientos(db, parametros, fileexe, exe)) {
830                lon = sprintf(ptrTrama->parametros, "nfn=RESPUESTA_AutoexecCliente\r");
831                lon += sprintf(ptrTrama->parametros + lon, "nfl=%s\r", fileautoexec);
832                lon += sprintf(ptrTrama->parametros + lon, "res=1\r");
833        } else {
834                lon = sprintf(ptrTrama->parametros, "nfn=RESPUESTA_AutoexecCliente\r");
835                lon += sprintf(ptrTrama->parametros + lon, "res=0\r");
836        }
837
[4d2cdae]838        db.Close();
[3ec149c]839        fclose(fileexe);
840
[ba03878]841        if (!mandaTrama(&socket_c, ptrTrama)) {
[0a73ecf7]842                liberaMemoria(exe);
[8c04716]843                syslog(LOG_ERR, "failed to send response to %s:%hu reason=%s\n",
844                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
845                       strerror(errno));
[5759db40]846                return false;
[3ec149c]847        }
[0a73ecf7]848        liberaMemoria(exe);
[5759db40]849        return true;
[3ec149c]850}
851// ________________________________________________________________________________________________________
852// Función: recorreProcedimientos
853//
854//      Descripción:
855//              Crea un archivo con el código de un procedimiento separando cada comando  por un salto de linea
856//      Parámetros:
857//              Database db,char* parametros,FILE* fileexe,char* idp
858//      Devuelve:
[5759db40]859//              true: Si el proceso es correcto
860//              false: En caso de ocurrir algún error
[3ec149c]861// ________________________________________________________________________________________________________
[d647d81]862bool recorreProcedimientos(Database db, char *parametros, FILE *fileexe, char *idp)
863{
[3ec149c]864        int procedimientoid, lsize;
865        char idprocedimiento[LONPRM], msglog[LONSTD], sqlstr[LONSQL];
866        Table tbl;
867
868        /* Busca procedimiento */
869        sprintf(sqlstr,
870                        "SELECT procedimientoid,parametros FROM procedimientos_acciones"
871                                " WHERE idprocedimiento=%s ORDER BY orden", idp);
872        // Ejecuta consulta
[8c04716]873        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]874                db.GetErrorErrStr(msglog);
[8c04716]875                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
876                       __func__, __LINE__, msglog);
[5759db40]877                return false;
[3ec149c]878        }
879        while (!tbl.ISEOF()) { // Recorre procedimientos
880                if (!tbl.Get("procedimientoid", procedimientoid)) { // Toma dato
881                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]882                        og_info(msglog);
[5759db40]883                        return false;
[3ec149c]884                }
885                if (procedimientoid > 0) { // Procedimiento recursivo
886                        sprintf(idprocedimiento, "%d", procedimientoid);
887                        if (!recorreProcedimientos(db, parametros, fileexe, idprocedimiento)) {
[5759db40]888                                return false;
[3ec149c]889                        }
890                } else {
891                        if (!tbl.Get("parametros", parametros)) { // Toma dato
892                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]893                                og_info(msglog);
[5759db40]894                                return false;
[3ec149c]895                        }
896                        strcat(parametros, "@");
897                        lsize = strlen(parametros);
898                        fwrite(parametros, 1, lsize, fileexe); // Escribe el código a ejecutar
899                }
900                tbl.MoveNext();
901        }
[5759db40]902        return true;
[3ec149c]903}
904// ________________________________________________________________________________________________________
905// Función: ComandosPendientes
906//
907//      Descripción:
908//              Esta función busca en la base de datos,comandos pendientes de ejecutar por un  ordenador  concreto
909//      Parámetros:
910//              - socket_c: Socket del cliente que envió el mensaje
911//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
912//      Devuelve:
[5759db40]913//              true: Si el proceso es correcto
914//              false: En caso de ocurrir algún error
[3ec149c]915// ________________________________________________________________________________________________________
[9baecf8]916static bool ComandosPendientes(TRAMA *ptrTrama, struct og_client *cli)
[0a73ecf7]917{
[9baecf8]918        int socket_c = og_client_socket(cli);
[0a73ecf7]919        char *ido,*iph,pids[LONPRM];
[3ec149c]920        int ids, idx;
921
[0a73ecf7]922        iph = copiaParametro("iph",ptrTrama); // Toma dirección IP
[3ec149c]923        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
924
925        if (!clienteExistente(iph, &idx)) { // Busca índice del cliente
[0a73ecf7]926                liberaMemoria(iph);
927                liberaMemoria(ido);
[8c04716]928                syslog(LOG_ERR, "client does not exist\n");
[5759db40]929                return false;
[3ec149c]930        }
931        if (buscaComandos(ido, ptrTrama, &ids)) { // Existen comandos pendientes
932                ptrTrama->tipo = MSG_COMANDO;
933                sprintf(pids, "\rids=%d\r", ids);
934                strcat(ptrTrama->parametros, pids);
935                strcpy(tbsockets[idx].estado, CLIENTE_OCUPADO);
936        } else {
937                initParametros(ptrTrama,0);
938                strcpy(ptrTrama->parametros, "nfn=NoComandosPtes\r");
939        }
[ba03878]940        if (!mandaTrama(&socket_c, ptrTrama)) {
[0a73ecf7]941                liberaMemoria(iph);
[8c04716]942                liberaMemoria(ido);
943                syslog(LOG_ERR, "failed to send response to %s:%hu reason=%s\n",
944                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
945                       strerror(errno));
[5759db40]946                return false;
[3ec149c]947        }
[0a73ecf7]948        liberaMemoria(iph);
949        liberaMemoria(ido);     
[5759db40]950        return true;
[3ec149c]951}
952// ________________________________________________________________________________________________________
953// Función: buscaComandos
954//
955//      Descripción:
956//              Busca en la base de datos,comandos pendientes de ejecutar por el cliente
957//      Parámetros:
958//              - ido: Identificador del ordenador
959//              - cmd: Parámetros del comando (Salida)
[0a73ecf7]960//              - ids: Identificador de la sesion(Salida)
[3ec149c]961//      Devuelve:
[5759db40]962//              true: Si el proceso es correcto
963//              false: En caso de ocurrir algún error
[3ec149c]964// ________________________________________________________________________________________________________
[c0a46e2]965bool buscaComandos(char *ido, TRAMA *ptrTrama, int *ids)
[3ec149c]966{
967        char msglog[LONSTD], sqlstr[LONSQL];
968        Database db;
969        Table tbl;
970        int lonprm;
971
[8c04716]972        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]973                db.GetErrorErrStr(msglog);
[8c04716]974                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
975                       __func__, __LINE__, msglog);
[5759db40]976                return false;
[3ec149c]977        }
[0a73ecf7]978        sprintf(sqlstr,"SELECT sesion,parametros,length( parametros) as lonprm"\
[3ec149c]979                        " FROM acciones WHERE idordenador=%s AND estado='%d' ORDER BY idaccion", ido, ACCION_INICIADA);
[8c04716]980        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]981                db.GetErrorErrStr(msglog);
[8c04716]982                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
983                       __func__, __LINE__, msglog);
[5759db40]984                return false;
[3ec149c]985        }
986        if (tbl.ISEOF()) {
987                db.Close();
[5759db40]988                return false; // No hay comandos pendientes
[3ec149c]989        } else { // Busca entre todas las acciones de diversos ambitos
[0a73ecf7]990                if (!tbl.Get("sesion", *ids)) { // Toma identificador de la sesion
[3ec149c]991                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]992                        og_info(msglog);
[5759db40]993                        return false;
[3ec149c]994                }
995                if (!tbl.Get("lonprm", lonprm)) { // Toma parámetros del comando
996                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]997                        og_info(msglog);
[5759db40]998                        return false;
[3ec149c]999                }
1000                if(!initParametros(ptrTrama,lonprm+LONGITUD_PARAMETROS)){
1001                        db.Close();
[8c04716]1002                        syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]1003                        return false;
[3ec149c]1004                }
1005                if (!tbl.Get("parametros", ptrTrama->parametros)) { // Toma parámetros del comando
1006                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]1007                        og_info(msglog);
[5759db40]1008                        return false;
[3ec149c]1009                }
1010        }
1011        db.Close();
[5759db40]1012        return true; // Hay comandos pendientes, se toma el primero de la cola
[3ec149c]1013}
1014// ________________________________________________________________________________________________________
1015// Función: DisponibilidadComandos
1016//
1017//      Descripción:
1018//              Esta función habilita a un cliente para recibir comandos desde la consola
1019//      Parámetros:
1020//              - socket_c: Socket del cliente que envió el mensaje
1021//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1022//      Devuelve:
[5759db40]1023//              true: Si el proceso es correcto
1024//              false: En caso de ocurrir algún error
[3ec149c]1025// ________________________________________________________________________________________________________
[0a73ecf7]1026//
[9baecf8]1027static bool DisponibilidadComandos(TRAMA *ptrTrama, struct og_client *cli)
[0a73ecf7]1028{
1029        char *iph, *tpc;
[2e0c063]1030        int idx;
[3ec149c]1031
[0a73ecf7]1032        iph = copiaParametro("iph",ptrTrama); // Toma ip
[3ec149c]1033        if (!clienteExistente(iph, &idx)) { // Busca índice del cliente
[0a73ecf7]1034                liberaMemoria(iph);
[8c04716]1035                syslog(LOG_ERR, "client does not exist\n");
[5759db40]1036                return false;
[3ec149c]1037        }
[0a73ecf7]1038        tpc = copiaParametro("tpc",ptrTrama); // Tipo de cliente (Plataforma y S.O.)
[3ec149c]1039        strcpy(tbsockets[idx].estado, tpc);
[2e0c063]1040        cli->keepalive_idx = idx;
[0a73ecf7]1041        liberaMemoria(iph);
1042        liberaMemoria(tpc);             
[5759db40]1043        return true;
[3ec149c]1044}
1045// ________________________________________________________________________________________________________
1046// Función: respuestaEstandar
1047//
1048//      Descripción:
1049//              Esta función actualiza la base de datos con el resultado de la ejecución de un comando con seguimiento
1050//      Parámetros:
1051//              - res: resultado de la ejecución del comando
1052//              - der: Descripción del error si hubiese habido
1053//              - iph: Dirección IP
[0a73ecf7]1054//              - ids: identificador de la sesión
[3ec149c]1055//              - ido: Identificador del ordenador que notifica
1056//              - db: Objeto base de datos (operativo)
1057//              - tbl: Objeto tabla
1058//      Devuelve:
[5759db40]1059//              true: Si el proceso es correcto
1060//              false: En caso de ocurrir algún error
[3ec149c]1061// ________________________________________________________________________________________________________
[d647d81]1062static bool respuestaEstandar(TRAMA *ptrTrama, char *iph, char *ido, Database db,
1063                Table tbl)
1064{
[3ec149c]1065        char msglog[LONSTD], sqlstr[LONSQL];
1066        char *res, *ids, *der;
1067        char fechafin[LONPRM];
1068        struct tm* st;
[0a73ecf7]1069        int idaccion;
[3ec149c]1070
1071        ids = copiaParametro("ids",ptrTrama); // Toma identificador de la sesión
1072
1073        if (ids == NULL) // No existe seguimiento de la acción
[5759db40]1074                return true;
1075
[0a73ecf7]1076        if (atoi(ids) == 0){ // No existe seguimiento de la acción
1077                liberaMemoria(ids);
[5759db40]1078                return true;
[0a73ecf7]1079        }
[3ec149c]1080
1081        sprintf(sqlstr,
[0a73ecf7]1082                        "SELECT * FROM acciones WHERE idordenador=%s"
1083                        " AND sesion=%s ORDER BY idaccion", ido,ids);
1084
1085        liberaMemoria(ids);
1086
[8c04716]1087        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]1088                db.GetErrorErrStr(msglog);
[8c04716]1089                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1090                       __func__, __LINE__, msglog);
[5759db40]1091                return false;
[3ec149c]1092        }
[8c04716]1093        if (tbl.ISEOF()) {
1094                syslog(LOG_ERR, "no actions available\n");
[5759db40]1095                return true;
[3ec149c]1096        }
[0a73ecf7]1097        if (!tbl.Get("idaccion", idaccion)) { // Toma identificador de la accion
1098                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]1099                og_info(msglog);
[5759db40]1100                return false;
[0a73ecf7]1101        }
[3ec149c]1102        st = tomaHora();
1103        sprintf(fechafin, "%d/%d/%d %d:%d:%d", st->tm_year + 1900, st->tm_mon + 1,
1104                        st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec);
1105
[0a73ecf7]1106        res = copiaParametro("res",ptrTrama); // Toma resultado
1107        der = copiaParametro("der",ptrTrama); // Toma descripción del error (si hubiera habido)
1108       
[f55923d]1109        sprintf(sqlstr,
1110                        "UPDATE acciones"\
1111                        "   SET resultado='%s',estado='%d',fechahorafin='%s',descrinotificacion='%s'"\
[0a73ecf7]1112                        " WHERE idordenador=%s AND idaccion=%d",
1113                        res, ACCION_FINALIZADA, fechafin, der, ido, idaccion);
1114                       
[3ec149c]1115        if (!db.Execute(sqlstr, tbl)) { // Error al actualizar
[0a73ecf7]1116                liberaMemoria(res);
1117                liberaMemoria(der);
[3ec149c]1118                db.GetErrorErrStr(msglog);
[35cc972]1119                og_info(msglog);
[5759db40]1120                return false;
[3ec149c]1121        }
[0a73ecf7]1122       
1123        liberaMemoria(der);
1124       
[f55923d]1125        if (atoi(res) == ACCION_FALLIDA) {
1126                liberaMemoria(res);
[5759db40]1127                return false; // Error en la ejecución del comando
[f55923d]1128        }
[3ec149c]1129
[f55923d]1130        liberaMemoria(res);
[5759db40]1131        return true;
[3ec149c]1132}
[c8e415b]1133
1134static bool og_send_cmd(char *ips_array[], int ips_array_len,
1135                        const char *state, TRAMA *ptrTrama)
1136{
1137        int i, idx;
1138
1139        for (i = 0; i < ips_array_len; i++) {
1140                if (clienteDisponible(ips_array[i], &idx)) { // Si el cliente puede recibir comandos
1141                        int sock = tbsockets[idx].cli ? tbsockets[idx].cli->io.fd : -1;
1142
1143                        strcpy(tbsockets[idx].estado, state); // Actualiza el estado del cliente
[0deba63]1144                        if (sock >= 0 && !mandaTrama(&sock, ptrTrama)) {
[c8e415b]1145                                syslog(LOG_ERR, "failed to send response to %s:%s\n",
1146                                       ips_array[i], strerror(errno));
1147                        }
1148                }
1149        }
1150        return true;
1151}
1152
[3ec149c]1153// ________________________________________________________________________________________________________
1154// Función: enviaComando
1155//
1156//      Descripción:
1157//              Envía un comando a los clientes
1158//      Parámetros:
1159//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1160//              - estado: Estado en el se deja al cliente mientras se ejecuta el comando
1161//      Devuelve:
[5759db40]1162//              true: Si el proceso es correcto
1163//              false: En caso de ocurrir algún error
[3ec149c]1164// ________________________________________________________________________________________________________
[c0a46e2]1165bool enviaComando(TRAMA* ptrTrama, const char *estado)
[d647d81]1166{
[3ec149c]1167        char *iph, *Ipes, *ptrIpes[MAXIMOS_CLIENTES];
[c8e415b]1168        int lon;
[3ec149c]1169
1170        iph = copiaParametro("iph",ptrTrama); // Toma dirección/es IP
1171        lon = strlen(iph); // Calcula longitud de la cadena de direccion/es IPE/S
1172        Ipes = (char*) reservaMemoria(lon + 1);
1173        if (Ipes == NULL) {
[8c04716]1174                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]1175                return false;
[3ec149c]1176        }
[0a73ecf7]1177       
[3ec149c]1178        strcpy(Ipes, iph); // Copia cadena de IPES
[0a73ecf7]1179        liberaMemoria(iph);
1180
[3ec149c]1181        lon = splitCadena(ptrIpes, Ipes, ';');
1182        FINCADaINTRO(ptrTrama);
[2e0c063]1183
[c8e415b]1184        if (!og_send_cmd(ptrIpes, lon, estado, ptrTrama))
1185                return false;
1186
[fc480f2]1187        liberaMemoria(Ipes);
[5759db40]1188        return true;
[3ec149c]1189}
1190//______________________________________________________________________________________________________
1191// Función: respuestaConsola
1192//
1193//      Descripción:
1194//              Envia una respuesta a la consola sobre el resultado de la ejecución de un comando
1195//      Parámetros:
1196//              - socket_c: (Salida) Socket utilizado para el envío
1197//              - res: Resultado del envío del comando
1198//      Devuelve:
[5759db40]1199//              true: Si el proceso es correcto
1200//              false: En caso de ocurrir algún error
[3ec149c]1201// ________________________________________________________________________________________________________
[d647d81]1202bool respuestaConsola(int socket_c, TRAMA *ptrTrama, int res)
1203{
[3ec149c]1204        initParametros(ptrTrama,0);
1205        sprintf(ptrTrama->parametros, "res=%d\r", res);
[ba03878]1206        if (!mandaTrama(&socket_c, ptrTrama)) {
[8c04716]1207                syslog(LOG_ERR, "%s:%d failed to send response: %s\n",
1208                       __func__, __LINE__, strerror(errno));
[5759db40]1209                return false;
[3ec149c]1210        }
[5759db40]1211        return true;
[3ec149c]1212}
1213// ________________________________________________________________________________________________________
1214// Función: Levanta
1215//
1216//      Descripción:
1217//              Enciende ordenadores a través de la red cuyas macs se pasan como parámetro
1218//      Parámetros:
[4329e85]1219//              - iph: Cadena de direcciones ip separadas por ";"
[3ec149c]1220//              - mac: Cadena de direcciones mac separadas por ";"
[4329e85]1221//              - mar: Método de arranque (1=Broadcast, 2=Unicast)
[3ec149c]1222//      Devuelve:
[5759db40]1223//              true: Si el proceso es correcto
1224//              false: En caso de ocurrir algún error
[3ec149c]1225// ________________________________________________________________________________________________________
[62c0560]1226
1227bool Levanta(char *ptrIP[], char *ptrMacs[], int lon, char *mar)
[4329e85]1228{
[a52f983]1229        unsigned int on = 1;
1230        sockaddr_in local;
[62c0560]1231        int i, res;
[aaa2c57]1232        int s;
[3ec149c]1233
1234        /* Creación de socket para envío de magig packet */
1235        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
[70f6f10]1236        if (s < 0) {
[8c04716]1237                syslog(LOG_ERR, "cannot create socket for magic packet\n");
[5759db40]1238                return false;
[3ec149c]1239        }
[a52f983]1240        res = setsockopt(s, SOL_SOCKET, SO_BROADCAST, (unsigned int *) &on,
1241                         sizeof(on));
[70f6f10]1242        if (res < 0) {
[8c04716]1243                syslog(LOG_ERR, "cannot set broadcast socket\n");
[5759db40]1244                return false;
[3ec149c]1245        }
[a52f983]1246        memset(&local, 0, sizeof(local));
[3ec149c]1247        local.sin_family = AF_INET;
[a52f983]1248        local.sin_port = htons(PUERTO_WAKEUP);
1249        local.sin_addr.s_addr = htonl(INADDR_ANY);
1250
[3ec149c]1251        for (i = 0; i < lon; i++) {
[aaa2c57]1252                if (!WakeUp(s, ptrIP[i], ptrMacs[i], mar)) {
[8c04716]1253                        syslog(LOG_ERR, "problem sending magic packet\n");
[3ec149c]1254                        close(s);
[5759db40]1255                        return false;
[3ec149c]1256                }
1257        }
1258        close(s);
[5759db40]1259        return true;
[3ec149c]1260}
[332487d]1261
1262#define OG_WOL_SEQUENCE         6
1263#define OG_WOL_MACADDR_LEN      6
1264#define OG_WOL_REPEAT           16
1265
1266struct wol_msg {
1267        char secuencia_FF[OG_WOL_SEQUENCE];
1268        char macbin[OG_WOL_REPEAT][OG_WOL_MACADDR_LEN];
1269};
1270
1271static bool wake_up_broadcast(int sd, struct sockaddr_in *client,
1272                              const struct wol_msg *msg)
1273{
1274        struct sockaddr_in *broadcast_addr;
1275        struct ifaddrs *ifaddr, *ifa;
1276        int ret;
1277
1278        if (getifaddrs(&ifaddr) < 0) {
1279                syslog(LOG_ERR, "cannot get list of addresses\n");
1280                return false;
1281        }
1282
1283        client->sin_addr.s_addr = htonl(INADDR_BROADCAST);
1284
1285        for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
1286                if (ifa->ifa_addr == NULL ||
1287                    ifa->ifa_addr->sa_family != AF_INET ||
1288                    strcmp(ifa->ifa_name, interface) != 0)
1289                        continue;
1290
1291                broadcast_addr =
1292                        (struct sockaddr_in *)ifa->ifa_ifu.ifu_broadaddr;
1293                client->sin_addr.s_addr = broadcast_addr->sin_addr.s_addr;
1294                break;
1295        }
[d2a9dd8]1296        freeifaddrs(ifaddr);
[332487d]1297
1298        ret = sendto(sd, msg, sizeof(*msg), 0,
1299                     (sockaddr *)client, sizeof(*client));
1300        if (ret < 0) {
1301                syslog(LOG_ERR, "failed to send broadcast wol\n");
1302                return false;
1303        }
1304
1305        return true;
1306}
1307
1308static bool wake_up_unicast(int sd, struct sockaddr_in *client,
1309                            const struct wol_msg *msg,
1310                            const struct in_addr *addr)
1311{
1312        int ret;
1313
1314        client->sin_addr.s_addr = addr->s_addr;
1315
1316        ret = sendto(sd, msg, sizeof(*msg), 0,
1317                     (sockaddr *)client, sizeof(*client));
1318        if (ret < 0) {
1319                syslog(LOG_ERR, "failed to send unicast wol\n");
1320                return false;
1321        }
1322
1323        return true;
1324}
1325
1326enum wol_delivery_type {
1327        OG_WOL_BROADCAST = 1,
1328        OG_WOL_UNICAST = 2
1329};
1330
[3ec149c]1331//_____________________________________________________________________________________________________________
1332// Función: WakeUp
1333//
1334//       Descripción:
1335//              Enciende el ordenador cuya MAC se pasa como parámetro
1336//      Parámetros:
1337//              - s : Socket para enviar trama magic packet
[4329e85]1338//              - iph : Cadena con la dirección ip
[3ec149c]1339//              - mac : Cadena con la dirección mac en formato XXXXXXXXXXXX
[4329e85]1340//              - mar: Método de arranque (1=Broadcast, 2=Unicast)
[3ec149c]1341//      Devuelve:
[5759db40]1342//              true: Si el proceso es correcto
1343//              false: En caso de ocurrir algún error
[3ec149c]1344//_____________________________________________________________________________________________________________
[4329e85]1345//
[aaa2c57]1346bool WakeUp(int s, char* iph, char *mac, char *mar)
[4329e85]1347{
[43763e4]1348        unsigned int macaddr[OG_WOL_MACADDR_LEN];
[332487d]1349        char HDaddress_bin[OG_WOL_MACADDR_LEN];
1350        struct sockaddr_in WakeUpCliente;
1351        struct wol_msg Trama_WakeUp;
1352        struct in_addr addr;
1353        bool ret;
1354        int i;
[3ec149c]1355
1356        for (i = 0; i < 6; i++) // Primera secuencia de la trama Wake Up (0xFFFFFFFFFFFF)
1357                Trama_WakeUp.secuencia_FF[i] = 0xFF;
1358
[a52f983]1359        sscanf(mac, "%02x%02x%02x%02x%02x%02x",
[43763e4]1360               &macaddr[0], &macaddr[1], &macaddr[2],
1361               &macaddr[3], &macaddr[4], &macaddr[5]);
1362
1363        for (i = 0; i < 6; i++)
1364                HDaddress_bin[i] = (uint8_t)macaddr[i];
[3ec149c]1365
1366        for (i = 0; i < 16; i++) // Segunda secuencia de la trama Wake Up , repetir 16 veces su la MAC
1367                memcpy(&Trama_WakeUp.macbin[i][0], &HDaddress_bin, 6);
1368
1369        /* Creación de socket del cliente que recibe la trama magic packet */
1370        WakeUpCliente.sin_family = AF_INET;
1371        WakeUpCliente.sin_port = htons((short) PUERTO_WAKEUP);
1372
[332487d]1373        switch (atoi(mar)) {
1374        case OG_WOL_BROADCAST:
[aaa2c57]1375                ret = wake_up_broadcast(s, &WakeUpCliente, &Trama_WakeUp);
[332487d]1376                break;
1377        case OG_WOL_UNICAST:
1378                if (inet_aton(iph, &addr) < 0) {
1379                        syslog(LOG_ERR, "bad IP address for unicast wol\n");
1380                        ret = false;
1381                        break;
1382                }
[aaa2c57]1383                ret = wake_up_unicast(s, &WakeUpCliente, &Trama_WakeUp, &addr);
[332487d]1384                break;
1385        default:
1386                syslog(LOG_ERR, "unknown wol type\n");
1387                ret = false;
1388                break;
1389        }
1390        return ret;
[3ec149c]1391}
1392// ________________________________________________________________________________________________________
1393// Función: RESPUESTA_Arrancar
1394//
1395//      Descripción:
[f55923d]1396//              Respuesta del cliente al comando Arrancar
[3ec149c]1397//      Parámetros:
1398//              - socket_c: Socket del cliente que envió el mensaje
1399//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1400//      Devuelve:
[5759db40]1401//              true: Si el proceso es correcto
1402//              false: En caso de ocurrir algún error
[3ec149c]1403// ________________________________________________________________________________________________________
[9baecf8]1404static bool RESPUESTA_Arrancar(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1405{
[3ec149c]1406        char msglog[LONSTD];
1407        Database db;
1408        Table tbl;
1409        int i;
1410        char *iph, *ido;
1411        char *tpc;
1412
[8c04716]1413        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1414                db.GetErrorErrStr(msglog);
[8c04716]1415                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1416                       __func__, __LINE__, msglog);
[5759db40]1417                return false;
[3ec149c]1418        }
1419
1420        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1421        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1422
1423        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1424                liberaMemoria(iph);
1425                liberaMemoria(ido);
[8c04716]1426                syslog(LOG_ERR, "failed to register notification\n");
1427                return false;
[3ec149c]1428        }
1429
1430        tpc = copiaParametro("tpc",ptrTrama); // Tipo de cliente (Plataforma y S.O.)
1431        if (clienteExistente(iph, &i)) // Actualiza estado
1432                strcpy(tbsockets[i].estado, tpc);
[0a73ecf7]1433               
1434        liberaMemoria(iph);
1435        liberaMemoria(ido);
1436        liberaMemoria(tpc);
1437       
[3ec149c]1438        db.Close(); // Cierra conexión
[5759db40]1439        return true;
[3ec149c]1440}
1441// ________________________________________________________________________________________________________
1442// Función: RESPUESTA_Apagar
1443//
1444//      Descripción:
1445//              Respuesta del cliente al comando Apagar
1446//      Parámetros:
1447//              - socket_c: Socket del cliente que envió el mensaje
1448//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1449//      Devuelve:
[5759db40]1450//              true: Si el proceso es correcto
1451//              false: En caso de ocurrir algún error
[3ec149c]1452// ________________________________________________________________________________________________________
[9baecf8]1453static bool RESPUESTA_Apagar(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1454{
[3ec149c]1455        char msglog[LONSTD];
1456        Database db;
1457        Table tbl;
1458        int i;
1459        char *iph, *ido;
1460
[8c04716]1461        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1462                db.GetErrorErrStr(msglog);
[8c04716]1463                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1464                       __func__, __LINE__, msglog);
[5759db40]1465                return false;
[3ec149c]1466        }
1467
1468        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1469        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1470
1471        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1472                liberaMemoria(iph);
1473                liberaMemoria(ido);
[8c04716]1474                syslog(LOG_ERR, "failed to register notification\n");
[5759db40]1475                return false; // Error al registrar notificacion
[3ec149c]1476        }
1477
1478        if (clienteExistente(iph, &i)) // Actualiza estado
1479                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
[0a73ecf7]1480       
1481        liberaMemoria(iph);
1482        liberaMemoria(ido);
1483       
[3ec149c]1484        db.Close(); // Cierra conexión
[5759db40]1485        return true;
[3ec149c]1486}
1487// ________________________________________________________________________________________________________
1488// Función: RESPUESTA_Reiniciar
1489//
1490//      Descripción:
1491//              Respuesta del cliente al comando Reiniciar
1492//      Parámetros:
1493//              - socket_c: Socket del cliente que envió el mensaje
1494//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1495//      Devuelve:
[5759db40]1496//              true: Si el proceso es correcto
1497//              false: En caso de ocurrir algún error
[3ec149c]1498// ________________________________________________________________________________________________________
[9baecf8]1499static bool RESPUESTA_Reiniciar(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1500{
[3ec149c]1501        char msglog[LONSTD];
1502        Database db;
1503        Table tbl;
1504        int i;
1505        char *iph, *ido;
1506
[8c04716]1507        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1508                db.GetErrorErrStr(msglog);
[8c04716]1509                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1510                       __func__, __LINE__, msglog);
[5759db40]1511                return false;
[3ec149c]1512        }
1513
1514        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1515        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1516
1517        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1518                liberaMemoria(iph);
1519                liberaMemoria(ido);
[8c04716]1520                syslog(LOG_ERR, "failed to register notification\n");
[5759db40]1521                return false; // Error al registrar notificacion
[3ec149c]1522        }
1523
1524        if (clienteExistente(iph, &i)) // Actualiza estado
1525                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
[0a73ecf7]1526       
1527        liberaMemoria(iph);
1528        liberaMemoria(ido);
[3ec149c]1529
1530        db.Close(); // Cierra conexión
[5759db40]1531        return true;
[3ec149c]1532}
1533// ________________________________________________________________________________________________________
1534// Función: RESPUESTA_IniciarSesion
1535//
1536//      Descripción:
1537//              Respuesta del cliente al comando Iniciar Sesión
1538//      Parámetros:
1539//              - socket_c: Socket del cliente que envió el mensaje
1540//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1541//      Devuelve:
[5759db40]1542//              true: Si el proceso es correcto
1543//              false: En caso de ocurrir algún error
[3ec149c]1544// ________________________________________________________________________________________________________
[9baecf8]1545static bool RESPUESTA_IniciarSesion(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1546{
[3ec149c]1547        char msglog[LONSTD];
1548        Database db;
1549        Table tbl;
1550        int i;
1551        char *iph, *ido;
1552
[8c04716]1553        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1554                db.GetErrorErrStr(msglog);
[8c04716]1555                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1556                       __func__, __LINE__, msglog);
[5759db40]1557                return false;
[3ec149c]1558        }
1559
1560        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1561        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1562
1563        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1564                liberaMemoria(iph);
1565                liberaMemoria(ido);
[8c04716]1566                syslog(LOG_ERR, "failed to register notification\n");
[5759db40]1567                return false; // Error al registrar notificacion
[3ec149c]1568        }
1569
1570        if (clienteExistente(iph, &i)) // Actualiza estado
1571                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
[0a73ecf7]1572               
1573        liberaMemoria(iph);
1574        liberaMemoria(ido);
1575               
[3ec149c]1576        db.Close(); // Cierra conexión
[5759db40]1577        return true;
[3ec149c]1578}
1579// ________________________________________________________________________________________________________
1580// Función: RESPUESTA_CrearImagen
1581//
1582//      Descripción:
1583//              Respuesta del cliente al comando CrearImagen
1584//      Parámetros:
1585//              - socket_c: Socket del cliente que envió el mensaje
1586//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1587//      Devuelve:
[5759db40]1588//              true: Si el proceso es correcto
1589//              false: En caso de ocurrir algún error
[3ec149c]1590// ________________________________________________________________________________________________________
[9baecf8]1591static bool RESPUESTA_CrearImagen(TRAMA* ptrTrama, struct og_client *cli)
[0a73ecf7]1592{
[3ec149c]1593        char msglog[LONSTD];
1594        Database db;
1595        Table tbl;
[c916af9]1596        char *iph, *dsk, *par, *cpt, *ipr, *ido;
[3ec149c]1597        char *idi;
[c0a46e2]1598        bool res;
[3ec149c]1599
[8c04716]1600        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1601                db.GetErrorErrStr(msglog);
[8c04716]1602                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1603                       __func__, __LINE__, msglog);
[5759db40]1604                return false;
[3ec149c]1605        }
1606
1607        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1608        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1609
1610        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1611                liberaMemoria(iph);
1612                liberaMemoria(ido);
[8c04716]1613                syslog(LOG_ERR, "failed to register notification\n");
[5759db40]1614                return false; // Error al registrar notificacion
[3ec149c]1615        }
1616
1617        // Acciones posteriores
1618        idi = copiaParametro("idi",ptrTrama);
[c916af9]1619        dsk = copiaParametro("dsk",ptrTrama);
[3ec149c]1620        par = copiaParametro("par",ptrTrama);
1621        cpt = copiaParametro("cpt",ptrTrama);
1622        ipr = copiaParametro("ipr",ptrTrama);
1623
[c916af9]1624        res=actualizaCreacionImagen(db, tbl, idi, dsk, par, cpt, ipr, ido);
[0a73ecf7]1625
1626        liberaMemoria(idi);
1627        liberaMemoria(par);
1628        liberaMemoria(cpt);
1629        liberaMemoria(ipr);
[8c04716]1630
[0a73ecf7]1631        if(!res){
[8c04716]1632                syslog(LOG_ERR, "Problem processing update\n");
1633                db.Close();
[5759db40]1634                return false;
[3ec149c]1635        }
1636
1637        db.Close(); // Cierra conexión
[5759db40]1638        return true;
[3ec149c]1639}
1640// ________________________________________________________________________________________________________
1641// Función: actualizaCreacionImagen
1642//
1643//      Descripción:
1644//              Esta función actualiza la base de datos con el resultado de la creación de una imagen
1645//      Parámetros:
1646//              - db: Objeto base de datos (ya operativo)
1647//              - tbl: Objeto tabla
1648//              - idi: Identificador de la imagen
[c916af9]1649//              - dsk: Disco de donde se creó
[3ec149c]1650//              - par: Partición de donde se creó
1651//              - cpt: Código de partición
1652//              - ipr: Ip del repositorio
1653//              - ido: Identificador del ordenador modelo
1654//      Devuelve:
[5759db40]1655//              true: Si el proceso es correcto
1656//              false: En caso de ocurrir algún error
[3ec149c]1657// ________________________________________________________________________________________________________
[d647d81]1658bool actualizaCreacionImagen(Database db, Table tbl, char *idi, char *dsk,
1659                             char *par, char *cpt, char *ipr, char *ido)
1660{
[3ec149c]1661        char msglog[LONSTD], sqlstr[LONSQL];
[f029b3b]1662        int idr,ifs;
[3ec149c]1663
[5a0e8ec]1664        /* Toma identificador del repositorio correspondiente al ordenador modelo */
[c916af9]1665        snprintf(sqlstr, LONSQL,
1666                        "SELECT repositorios.idrepositorio"
[5a0e8ec]1667                        "  FROM repositorios"
1668                        "  LEFT JOIN ordenadores USING (idrepositorio)"
1669                        " WHERE repositorios.ip='%s' AND ordenadores.idordenador=%s", ipr, ido);
[3ec149c]1670
[8c04716]1671        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]1672                db.GetErrorErrStr(msglog);
[8c04716]1673                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1674                       __func__, __LINE__, msglog);
[5759db40]1675                return false;
[3ec149c]1676        }
1677        if (!tbl.Get("idrepositorio", idr)) { // Toma dato
1678                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]1679                og_info(msglog);
[5759db40]1680                return false;
[3ec149c]1681        }
1682
1683        /* Toma identificador del perfilsoftware */
[c916af9]1684        snprintf(sqlstr, LONSQL,
1685                        "SELECT idperfilsoft"
1686                        "  FROM ordenadores_particiones"
1687                        " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", ido, dsk, par);
[3ec149c]1688
[8c04716]1689        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]1690                db.GetErrorErrStr(msglog);
[8c04716]1691                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1692                       __func__, __LINE__, msglog);
[5759db40]1693                return false;
[3ec149c]1694        }
1695        if (!tbl.Get("idperfilsoft", ifs)) { // Toma dato
1696                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]1697                og_info(msglog);
[5759db40]1698                return false;
[3ec149c]1699        }
1700
1701        /* Actualizar los datos de la imagen */
[c916af9]1702        snprintf(sqlstr, LONSQL,
[ab4ab39]1703                "UPDATE imagenes"
1704                "   SET idordenador=%s, numdisk=%s, numpar=%s, codpar=%s,"
1705                "       idperfilsoft=%d, idrepositorio=%d,"
1706                "       fechacreacion=NOW(), revision=revision+1"
1707                " WHERE idimagen=%s", ido, dsk, par, cpt, ifs, idr, idi);
[3ec149c]1708
[8c04716]1709        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]1710                db.GetErrorErrStr(msglog);
[8c04716]1711                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1712                       __func__, __LINE__, msglog);
[5759db40]1713                return false;
[3ec149c]1714        }
[ab4ab39]1715        /* Actualizar los datos en el cliente */
1716        snprintf(sqlstr, LONSQL,
1717                "UPDATE ordenadores_particiones"
[f029b3b]1718                "   SET idimagen=%s, revision=(SELECT revision FROM imagenes WHERE idimagen=%s),"
1719                "       fechadespliegue=NOW()"
[ab4ab39]1720                " WHERE idordenador=%s AND numdisk=%s AND numpar=%s",
[f029b3b]1721                idi, idi, ido, dsk, par);
[8c04716]1722        if (!db.Execute(sqlstr, tbl)) {
[ab4ab39]1723                db.GetErrorErrStr(msglog);
[8c04716]1724                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1725                       __func__, __LINE__, msglog);
[5759db40]1726                return false;
[ab4ab39]1727        }
[5759db40]1728        return true;
[3ec149c]1729}
1730// ________________________________________________________________________________________________________
[0a73ecf7]1731// Función: CrearImagenBasica
1732//
1733//      Descripción:
1734//              Crea una imagen basica usando sincronización
1735//      Parámetros:
1736//              - socket_c: Socket de la consola al envió el mensaje
1737//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1738//      Devuelve:
[5759db40]1739//              true: Si el proceso es correcto
1740//              false: En caso de ocurrir algún error
[0a73ecf7]1741// ________________________________________________________________________________________________________
[9baecf8]1742static bool CrearImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1743{
[0a73ecf7]1744        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]1745                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]1746                return false;
[0a73ecf7]1747        }
[9baecf8]1748        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]1749        return true;
[0a73ecf7]1750}
1751// ________________________________________________________________________________________________________
1752// Función: RESPUESTA_CrearImagenBasica
1753//
1754//      Descripción:
1755//              Respuesta del cliente al comando CrearImagenBasica
1756//      Parámetros:
1757//              - socket_c: Socket del cliente que envió el mensaje
1758//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1759//      Devuelve:
[5759db40]1760//              true: Si el proceso es correcto
1761//              false: En caso de ocurrir algún error
[0a73ecf7]1762// ________________________________________________________________________________________________________
[9baecf8]1763static bool RESPUESTA_CrearImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1764{
[9baecf8]1765        // La misma respuesta que la creación de imagen monolítica
1766        return RESPUESTA_CrearImagen(ptrTrama, cli);
[0a73ecf7]1767}
1768// ________________________________________________________________________________________________________
1769// Función: CrearSoftIncremental
1770//
1771//      Descripción:
1772//              Crea una imagen incremental entre una partición de un disco y una imagen ya creada guardandola en el
1773//              mismo repositorio y en la misma carpeta donde está la imagen básica
1774//      Parámetros:
1775//              - socket_c: Socket de la consola al envió el mensaje
1776//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1777//      Devuelve:
[5759db40]1778//              true: Si el proceso es correcto
1779//              false: En caso de ocurrir algún error
[0a73ecf7]1780// ________________________________________________________________________________________________________
[9baecf8]1781static bool CrearSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1782{
[0a73ecf7]1783        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]1784                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]1785                return false;
[0a73ecf7]1786        }
[9baecf8]1787        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]1788        return true;
[0a73ecf7]1789}
1790// ________________________________________________________________________________________________________
1791// Función: RESPUESTA_CrearSoftIncremental
1792//
1793//      Descripción:
1794//              Respuesta del cliente al comando crearImagenDiferencial
1795//      Parámetros:
1796//              - socket_c: Socket del cliente que envió el mensaje
1797//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1798//      Devuelve:
[5759db40]1799//              true: Si el proceso es correcto
1800//              false: En caso de ocurrir algún error
[0a73ecf7]1801// ________________________________________________________________________________________________________
[9baecf8]1802static bool RESPUESTA_CrearSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
[0a73ecf7]1803{
1804        Database db;
1805        Table tbl;
1806        char *iph,*par,*ido,*idf;
1807        int ifs;
1808        char msglog[LONSTD],sqlstr[LONSQL];
1809
[8c04716]1810        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[0a73ecf7]1811                db.GetErrorErrStr(msglog);
[8c04716]1812                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1813                       __func__, __LINE__, msglog);
[5759db40]1814                return false;
[0a73ecf7]1815        }
1816
1817        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1818        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1819
1820        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
1821                liberaMemoria(iph);
[8c04716]1822                liberaMemoria(ido);
1823                syslog(LOG_ERR, "failed to register notification\n");
1824                return false;
[0a73ecf7]1825        }
1826
1827        par = copiaParametro("par",ptrTrama);
1828
1829        /* Toma identificador del perfilsoftware creado por el inventario de software */
1830        sprintf(sqlstr,"SELECT idperfilsoft FROM ordenadores_particiones WHERE idordenador=%s AND numpar=%s",ido,par);
1831       
1832        liberaMemoria(iph);
1833        liberaMemoria(ido);     
1834        liberaMemoria(par);     
[8c04716]1835
1836        if (!db.Execute(sqlstr, tbl)) {
[0a73ecf7]1837                db.GetErrorErrStr(msglog);
[8c04716]1838                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1839                       __func__, __LINE__, msglog);
[5759db40]1840                return false;
[0a73ecf7]1841        }
1842        if (!tbl.Get("idperfilsoft", ifs)) { // Toma dato
1843                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]1844                og_info(msglog);
[5759db40]1845                return false;
[0a73ecf7]1846        }
1847
1848        /* Actualizar los datos de la imagen */
1849        idf = copiaParametro("idf",ptrTrama);
1850        sprintf(sqlstr,"UPDATE imagenes SET idperfilsoft=%d WHERE idimagen=%s",ifs,idf);
1851        liberaMemoria(idf);     
[8c04716]1852
1853        if (!db.Execute(sqlstr, tbl)) {
[0a73ecf7]1854                db.GetErrorErrStr(msglog);
[8c04716]1855                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1856                       __func__, __LINE__, msglog);
[5759db40]1857                return false;
[0a73ecf7]1858        }
1859        db.Close(); // Cierra conexión
[5759db40]1860        return true;
[0a73ecf7]1861}
1862// ________________________________________________________________________________________________________
1863// Función: RestaurarImagenBasica
1864//
1865//      Descripción:
1866//              Restaura una imagen básica en una partición
1867//      Parámetros:
1868//              - socket_c: Socket de la consola al envió el mensaje
1869//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1870//      Devuelve:
[5759db40]1871//              true: Si el proceso es correcto
1872//              false: En caso de ocurrir algún error
[0a73ecf7]1873// ________________________________________________________________________________________________________
[9baecf8]1874static bool RestaurarImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1875{
[0a73ecf7]1876        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]1877                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]1878                return false;
[0a73ecf7]1879        }
[9baecf8]1880        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]1881        return true;
[0a73ecf7]1882}
1883// ________________________________________________________________________________________________________
1884// Función: RestaurarSoftIncremental
1885//
1886//      Descripción:
1887//              Restaura una imagen básica junto con software incremental en una partición
1888//      Parámetros:
1889//              - socket_c: Socket de la consola al envió el mensaje
1890//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1891//      Devuelve:
[5759db40]1892//              true: Si el proceso es correcto
1893//              false: En caso de ocurrir algún error
[0a73ecf7]1894// ________________________________________________________________________________________________________
[9baecf8]1895static bool RestaurarSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1896{
[0a73ecf7]1897        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]1898                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]1899                return false;
[0a73ecf7]1900        }
[9baecf8]1901        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]1902        return true;
[0a73ecf7]1903}
1904// ________________________________________________________________________________________________________
[3ec149c]1905// Función: RESPUESTA_RestaurarImagen
1906//
1907//      Descripción:
1908//              Respuesta del cliente al comando RestaurarImagen
1909//      Parámetros:
1910//              - socket_c: Socket del cliente que envió el mensaje
1911//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1912//      Devuelve:
[5759db40]1913//              true: Si el proceso es correcto
1914//              false: En caso de ocurrir algún error
[3ec149c]1915// ________________________________________________________________________________________________________
[0a73ecf7]1916//
[9baecf8]1917static bool RESPUESTA_RestaurarImagen(TRAMA* ptrTrama, struct og_client *cli)
[0a73ecf7]1918{
[3ec149c]1919        char msglog[LONSTD];
1920        Database db;
1921        Table tbl;
[c0a46e2]1922        bool res;
[82e5b6c]1923        char *iph, *ido, *idi, *dsk, *par, *ifs, *cfg;
[3ec149c]1924
[8c04716]1925        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]1926                db.GetErrorErrStr(msglog);
[8c04716]1927                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1928                       __func__, __LINE__, msglog);
[5759db40]1929                return false;
[3ec149c]1930        }
1931
1932        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
1933        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
1934
1935        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]1936                liberaMemoria(iph);
[8c04716]1937                liberaMemoria(ido);
1938                syslog(LOG_ERR, "failed to register notification\n");
1939                return false;
[3ec149c]1940        }
1941
1942        // Acciones posteriores
1943        idi = copiaParametro("idi",ptrTrama); // Toma identificador de la imagen
[c916af9]1944        dsk = copiaParametro("dsk",ptrTrama); // Número de disco
[3ec149c]1945        par = copiaParametro("par",ptrTrama); // Número de partición
1946        ifs = copiaParametro("ifs",ptrTrama); // Identificador del perfil software contenido
[82e5b6c]1947        cfg = copiaParametro("cfg",ptrTrama); // Configuración de discos
1948        if(cfg){
1949                actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador
1950                liberaMemoria(cfg);     
1951        }
[c916af9]1952        res=actualizaRestauracionImagen(db, tbl, idi, dsk, par, ido, ifs);
[0a73ecf7]1953       
1954        liberaMemoria(iph);
[82e5b6c]1955        liberaMemoria(ido);
[0a73ecf7]1956        liberaMemoria(idi);
1957        liberaMemoria(par);
1958        liberaMemoria(ifs);
1959
1960        if(!res){
[8c04716]1961                syslog(LOG_ERR, "Problem after restoring image\n");
1962                db.Close();
[5759db40]1963                return false;
[3ec149c]1964        }
1965
1966        db.Close(); // Cierra conexión
[5759db40]1967        return true;
[3ec149c]1968}
1969// ________________________________________________________________________________________________________
[0a73ecf7]1970//
1971// Función: RESPUESTA_RestaurarImagenBasica
1972//
1973//      Descripción:
1974//              Respuesta del cliente al comando RestaurarImagen
1975//      Parámetros:
1976//              - socket_c: Socket del cliente que envió el mensaje
1977//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1978//      Devuelve:
[5759db40]1979//              true: Si el proceso es correcto
1980//              false: En caso de ocurrir algún error
[0a73ecf7]1981// ________________________________________________________________________________________________________
1982//
[9baecf8]1983static bool RESPUESTA_RestaurarImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]1984{
[9baecf8]1985        return RESPUESTA_RestaurarImagen(ptrTrama, cli);
[0a73ecf7]1986}
1987// ________________________________________________________________________________________________________
1988// Función: RESPUESTA_RestaurarSoftIncremental
1989//
1990//      Descripción:
1991//              Respuesta del cliente al comando RestaurarSoftIncremental
1992//      Parámetros:
1993//              - socket_c: Socket del cliente que envió el mensaje
1994//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
1995//      Devuelve:
[5759db40]1996//              true: Si el proceso es correcto
1997//              false: En caso de ocurrir algún error
[0a73ecf7]1998// ________________________________________________________________________________________________________
[9baecf8]1999static bool RESPUESTA_RestaurarSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]2000{
[9baecf8]2001        return RESPUESTA_RestaurarImagen(ptrTrama, cli);
[0a73ecf7]2002}
2003// ________________________________________________________________________________________________________
[3ec149c]2004// Función: actualizaRestauracionImagen
2005//
2006//      Descripción:
[0a73ecf7]2007//              Esta función actualiza la base de datos con el resultado de la restauración de una imagen
[3ec149c]2008//      Parámetros:
2009//              - db: Objeto base de datos (ya operativo)
2010//              - tbl: Objeto tabla
2011//              - idi: Identificador de la imagen
[c916af9]2012//              - dsk: Disco de donde se restauró
[3ec149c]2013//              - par: Partición de donde se restauró
2014//              - ido: Identificador del cliente donde se restauró
2015//              - ifs: Identificador del perfil software contenido      en la imagen
2016//      Devuelve:
[5759db40]2017//              true: Si el proceso es correcto
2018//              false: En caso de ocurrir algún error
[3ec149c]2019// ________________________________________________________________________________________________________
[d647d81]2020bool actualizaRestauracionImagen(Database db, Table tbl, char *idi,
2021                                 char *dsk, char *par, char *ido, char *ifs)
2022{
[3ec149c]2023        char msglog[LONSTD], sqlstr[LONSQL];
2024
2025        /* Actualizar los datos de la imagen */
[c916af9]2026        snprintf(sqlstr, LONSQL,
2027                        "UPDATE ordenadores_particiones"
[84fa8d6]2028                        "   SET idimagen=%s, idperfilsoft=%s, fechadespliegue=NOW(),"
[c870c84]2029                        "       revision=(SELECT revision FROM imagenes WHERE idimagen=%s),"
2030                        "       idnombreso=IFNULL((SELECT idnombreso FROM perfilessoft WHERE idperfilsoft=%s),0)"
[dbbe689]2031                        " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", idi, ifs, idi, ifs, ido, dsk, par);
[3ec149c]2032
[8c04716]2033        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2034                db.GetErrorErrStr(msglog);
[8c04716]2035                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2036                       __func__, __LINE__, msglog);
[5759db40]2037                return false;
[3ec149c]2038        }
[5759db40]2039        return true;
[3ec149c]2040}
2041// ________________________________________________________________________________________________________
2042// Función: Configurar
2043//
2044//      Descripción:
2045//              Configura la tabla de particiones
2046//      Parámetros:
2047//              - socket_c: Socket de la consola al envió el mensaje
2048//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2049//      Devuelve:
[5759db40]2050//              true: Si el proceso es correcto
2051//              false: En caso de ocurrir algún error
[3ec149c]2052// ________________________________________________________________________________________________________
[9baecf8]2053static bool Configurar(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]2054{
[3ec149c]2055        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]2056                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]2057                return false;
[3ec149c]2058        }
[9baecf8]2059        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]2060        return true;
[3ec149c]2061}
2062// ________________________________________________________________________________________________________
2063// Función: RESPUESTA_Configurar
2064//
2065//      Descripción:
2066//              Respuesta del cliente al comando Configurar
2067//      Parámetros:
2068//              - socket_c: Socket del cliente que envió el mensaje
2069//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2070//      Devuelve:
[5759db40]2071//              true: Si el proceso es correcto
2072//              false: En caso de ocurrir algún error
[3ec149c]2073// ________________________________________________________________________________________________________
[0a73ecf7]2074//
[9baecf8]2075static bool RESPUESTA_Configurar(TRAMA* ptrTrama, struct og_client *ci)
[0a73ecf7]2076{
[3ec149c]2077        char msglog[LONSTD];
2078        Database db;
2079        Table tbl;
[c0a46e2]2080        bool res;
[3ec149c]2081        char *iph, *ido,*cfg;
2082
[8c04716]2083        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]2084                db.GetErrorErrStr(msglog);
[8c04716]2085                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2086                       __func__, __LINE__, msglog);
[5759db40]2087                return false;
[3ec149c]2088        }
2089
2090        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
2091        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
2092
2093        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]2094                liberaMemoria(iph);
[8c04716]2095                liberaMemoria(ido);
2096                syslog(LOG_ERR, "failed to register notification\n");
2097                return false;
[3ec149c]2098        }
2099
2100        cfg = copiaParametro("cfg",ptrTrama); // Toma configuración de particiones
[0a73ecf7]2101        res=actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador
2102       
2103        liberaMemoria(iph);
2104        liberaMemoria(ido);     
2105        liberaMemoria(cfg);     
[8c04716]2106
2107        if(!res){
2108                syslog(LOG_ERR, "Problem updating client configuration\n");
2109                return false;
[3ec149c]2110        }
[8c04716]2111
[3ec149c]2112        db.Close(); // Cierra conexión
[5759db40]2113        return true;
[3ec149c]2114}
2115// ________________________________________________________________________________________________________
2116// Función: EjecutarScript
2117//
2118//      Descripción:
2119//              Ejecuta un script de código
2120//      Parámetros:
2121//              - socket_c: Socket de la consola al envió el mensaje
2122//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2123//      Devuelve:
[5759db40]2124//              true: Si el proceso es correcto
2125//              false: En caso de ocurrir algún error
[3ec149c]2126// ________________________________________________________________________________________________________
[9baecf8]2127static bool EjecutarScript(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]2128{
[3ec149c]2129        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
[9baecf8]2130                respuestaConsola(og_client_socket(cli), ptrTrama, false);
[5759db40]2131                return false;
[3ec149c]2132        }
[9baecf8]2133        respuestaConsola(og_client_socket(cli), ptrTrama, true);
[5759db40]2134        return true;
[3ec149c]2135}
2136// ________________________________________________________________________________________________________
2137// Función: RESPUESTA_EjecutarScript
2138//
2139//      Descripción:
2140//              Respuesta del cliente al comando EjecutarScript
2141//      Parámetros:
2142//              - socket_c: Socket del cliente que envió el mensaje
2143//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2144//      Devuelve:
[5759db40]2145//              true: Si el proceso es correcto
2146//              false: En caso de ocurrir algún error
[3ec149c]2147// ________________________________________________________________________________________________________
[9baecf8]2148static bool RESPUESTA_EjecutarScript(TRAMA* ptrTrama, struct og_client *cli)
[7224a0a]2149{
[3ec149c]2150        char msglog[LONSTD];
2151        Database db;
2152        Table tbl;
[7224a0a]2153        char *iph, *ido,*cfg;
[3ec149c]2154
[8c04716]2155        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]2156                db.GetErrorErrStr(msglog);
[8c04716]2157                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2158                       __func__, __LINE__, msglog);
[5759db40]2159                return false;
[3ec149c]2160        }
2161
2162        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
2163        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
2164
2165        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]2166                liberaMemoria(iph);
[8c04716]2167                liberaMemoria(ido);
2168                syslog(LOG_ERR, "failed to register notification\n");
2169                return false;
[3ec149c]2170        }
[0a73ecf7]2171       
[7224a0a]2172        cfg = copiaParametro("cfg",ptrTrama); // Toma configuración de particiones
[46f7d6f]2173        if(cfg){
[db4d467]2174                actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador
[46f7d6f]2175                liberaMemoria(cfg);     
2176        }
[7224a0a]2177
[0a73ecf7]2178        liberaMemoria(iph);
[7224a0a]2179        liberaMemoria(ido);
[46f7d6f]2180
[0a73ecf7]2181       
[3ec149c]2182        db.Close(); // Cierra conexión
[5759db40]2183        return true;
[3ec149c]2184}
2185// ________________________________________________________________________________________________________
2186// Función: RESPUESTA_InventarioHardware
2187//
2188//      Descripción:
2189//              Respuesta del cliente al comando InventarioHardware
2190//      Parámetros:
2191//              - socket_c: Socket del cliente que envió el mensaje
2192//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2193//      Devuelve:
[5759db40]2194//              true: Si el proceso es correcto
2195//              false: En caso de ocurrir algún error
[3ec149c]2196// ________________________________________________________________________________________________________
[9baecf8]2197static bool RESPUESTA_InventarioHardware(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]2198{
[3ec149c]2199        char msglog[LONSTD];
2200        Database db;
2201        Table tbl;
[c0a46e2]2202        bool res;
[3ec149c]2203        char *iph, *ido, *idc, *npc, *hrd, *buffer;
2204
[8c04716]2205        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]2206                db.GetErrorErrStr(msglog);
[8c04716]2207                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2208                       __func__, __LINE__, msglog);
[5759db40]2209                return false;
[3ec149c]2210        }
[0a73ecf7]2211
[3ec149c]2212        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip del cliente
2213        ido = copiaParametro("ido",ptrTrama); // Toma identificador del cliente
2214
2215        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]2216                liberaMemoria(iph);
[8c04716]2217                liberaMemoria(ido);
2218                syslog(LOG_ERR, "failed to register notification\n");
2219                return false;
[3ec149c]2220        }
2221        // Lee archivo de inventario enviado anteriormente
2222        hrd = copiaParametro("hrd",ptrTrama);
2223        buffer = rTrim(leeArchivo(hrd));
[0a73ecf7]2224       
2225        npc = copiaParametro("npc",ptrTrama);
2226        idc = copiaParametro("idc",ptrTrama); // Toma identificador del Centro
2227       
2228        if (buffer)
2229                res=actualizaHardware(db, tbl, buffer, ido, npc, idc);
2230       
2231        liberaMemoria(iph);
2232        liberaMemoria(ido);                     
2233        liberaMemoria(npc);                     
2234        liberaMemoria(idc);             
2235        liberaMemoria(buffer);         
2236       
2237        if(!res){
[8c04716]2238                syslog(LOG_ERR, "Problem updating client configuration\n");
[5759db40]2239                return false;
[3ec149c]2240        }
[0a73ecf7]2241               
[3ec149c]2242        db.Close(); // Cierra conexión
[5759db40]2243        return true;
[3ec149c]2244}
2245// ________________________________________________________________________________________________________
2246// Función: actualizaHardware
2247//
2248//              Descripción:
2249//                      Actualiza la base de datos con la configuracion hardware del cliente
2250//              Parámetros:
2251//                      - db: Objeto base de datos (ya operativo)
2252//                      - tbl: Objeto tabla
2253//                      - hrd: cadena con el inventario hardware
2254//                      - ido: Identificador del ordenador
2255//                      - npc: Nombre del ordenador
2256//                      - idc: Identificador del centro o Unidad organizativa
2257// ________________________________________________________________________________________________________
[0a73ecf7]2258//
[d647d81]2259bool actualizaHardware(Database db, Table tbl, char *hrd, char *ido, char *npc,
2260                       char *idc)
[0a73ecf7]2261{
[3ec149c]2262        char msglog[LONSTD], sqlstr[LONSQL];
2263        int idtipohardware, idperfilhard;
2264        int lon, i, j, aux;
[fc480f2]2265        bool retval;
[0a73ecf7]2266        char *whard;
[3ec149c]2267        int tbidhardware[MAXHARDWARE];
[0a73ecf7]2268        char *tbHardware[MAXHARDWARE],*dualHardware[2], descripcion[250], strInt[LONINT], *idhardwares;
[3ec149c]2269
2270        /* Toma Centro (Unidad Organizativa) */
2271        sprintf(sqlstr, "SELECT * FROM ordenadores WHERE idordenador=%s", ido);
2272
[8c04716]2273        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2274                db.GetErrorErrStr(msglog);
[8c04716]2275                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2276                       __func__, __LINE__, msglog);
[5759db40]2277                return false;
[3ec149c]2278        }
2279        if (!tbl.Get("idperfilhard", idperfilhard)) { // Toma dato
2280                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2281                og_info(msglog);
[5759db40]2282                return false;
[3ec149c]2283        }
[0a73ecf7]2284        whard=escaparCadena(hrd); // Codificar comillas simples
2285        if(!whard)
[5759db40]2286                return false;
[3ec149c]2287        /* Recorre componentes hardware*/
[0a73ecf7]2288        lon = splitCadena(tbHardware, whard, '\n');
[3ec149c]2289        if (lon > MAXHARDWARE)
2290                lon = MAXHARDWARE; // Limita el número de componentes hardware
2291        /*
2292         for (i=0;i<lon;i++){
2293         sprintf(msglog,"Linea de inventario: %s",tbHardware[i]);
[5759db40]2294         RegistraLog(msglog,false);
[3ec149c]2295         }
2296         */
2297        for (i = 0; i < lon; i++) {
2298                splitCadena(dualHardware, rTrim(tbHardware[i]), '=');
2299                //sprintf(msglog,"nemonico: %s",dualHardware[0]);
[5759db40]2300                //RegistraLog(msglog,false);
[3ec149c]2301                //sprintf(msglog,"valor: %s",dualHardware[1]);
[5759db40]2302                //RegistraLog(msglog,false);
[3ec149c]2303                sprintf(sqlstr, "SELECT idtipohardware,descripcion FROM tipohardwares "
2304                        " WHERE nemonico='%s'", dualHardware[0]);
[8c04716]2305                if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2306                        db.GetErrorErrStr(msglog);
[8c04716]2307                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2308                               __func__, __LINE__, msglog);
[5759db40]2309                        return false;
[3ec149c]2310                }
2311                if (tbl.ISEOF()) { //  Tipo de Hardware NO existente
2312                        sprintf(msglog, "%s: %s)", tbErrores[54], dualHardware[0]);
[35cc972]2313                        og_info(msglog);
[5759db40]2314                        return false;
[3ec149c]2315                } else { //  Tipo de Hardware Existe
2316                        if (!tbl.Get("idtipohardware", idtipohardware)) { // Toma dato
2317                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2318                                og_info(msglog);
[5759db40]2319                                return false;
[3ec149c]2320                        }
2321                        if (!tbl.Get("descripcion", descripcion)) { // Toma dato
2322                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2323                                og_info(msglog);
[5759db40]2324                                return false;
[3ec149c]2325                        }
2326
2327                        sprintf(sqlstr, "SELECT idhardware FROM hardwares "
2328                                " WHERE idtipohardware=%d AND descripcion='%s'",
2329                                        idtipohardware, dualHardware[1]);
2330
[8c04716]2331                        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2332                                db.GetErrorErrStr(msglog);
[8c04716]2333                                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2334                                       __func__, __LINE__, msglog);
[5759db40]2335                                return false;
[3ec149c]2336                        }
2337
2338                        if (tbl.ISEOF()) { //  Hardware NO existente
[df052e1]2339                                sprintf(sqlstr, "INSERT hardwares (idtipohardware,descripcion,idcentro,grupoid) "
[3ec149c]2340                                                        " VALUES(%d,'%s',%s,0)", idtipohardware,
2341                                                dualHardware[1], idc);
2342                                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2343                                        db.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2344                                        og_info(msglog);
[5759db40]2345                                        return false;
[3ec149c]2346                                }
2347                                // Recupera el identificador del hardware
2348                                sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
[8c04716]2349                                if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2350                                        db.GetErrorErrStr(msglog);
[8c04716]2351                                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2352                                               __func__, __LINE__, msglog);
[5759db40]2353                                        return false;
[3ec149c]2354                                }
2355                                if (!tbl.ISEOF()) { // Si existe registro
2356                                        if (!tbl.Get("identificador", tbidhardware[i])) {
2357                                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2358                                                og_info(msglog);
[5759db40]2359                                                return false;
[3ec149c]2360                                        }
2361                                }
2362                        } else {
2363                                if (!tbl.Get("idhardware", tbidhardware[i])) { // Toma dato
2364                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2365                                        og_info(msglog);
[5759db40]2366                                        return false;
[3ec149c]2367                                }
2368                        }
2369                }
2370        }
2371        // Ordena tabla de identificadores para cosultar si existe un pefil con esas especificaciones
2372
2373        for (i = 0; i < lon - 1; i++) {
2374                for (j = i + 1; j < lon; j++) {
2375                        if (tbidhardware[i] > tbidhardware[j]) {
2376                                aux = tbidhardware[i];
2377                                tbidhardware[i] = tbidhardware[j];
2378                                tbidhardware[j] = aux;
2379                        }
2380                }
2381        }
2382        /* Crea cadena de identificadores de componentes hardware separados por coma */
2383        sprintf(strInt, "%d", tbidhardware[lon - 1]); // Pasa a cadena el último identificador que es de mayor longitud
2384        aux = strlen(strInt); // Calcula longitud de cadena para reservar espacio a todos los perfiles
2385        idhardwares = reservaMemoria(sizeof(aux) * lon + lon);
2386        if (idhardwares == NULL) {
[8c04716]2387                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]2388                return false;
[3ec149c]2389        }
2390        aux = sprintf(idhardwares, "%d", tbidhardware[0]);
2391        for (i = 1; i < lon; i++)
2392                aux += sprintf(idhardwares + aux, ",%d", tbidhardware[i]);
2393
2394        if (!cuestionPerfilHardware(db, tbl, idc, ido, idperfilhard, idhardwares,
2395                        npc, tbidhardware, lon)) {
[8c04716]2396                syslog(LOG_ERR, "Problem updating client hardware\n");
[5759db40]2397                retval=false;
[3ec149c]2398        }
[fc480f2]2399        else {
[5759db40]2400                retval=true;
[fc480f2]2401        }
[0a73ecf7]2402        liberaMemoria(whard);
[fc480f2]2403        liberaMemoria(idhardwares);
2404        return (retval);
[3ec149c]2405}
2406// ________________________________________________________________________________________________________
2407// Función: cuestionPerfilHardware
2408//
2409//              Descripción:
2410//                      Comprueba existencia de perfil hardware y actualización de éste para el ordenador
2411//              Parámetros:
2412//                      - db: Objeto base de datos (ya operativo)
2413//                      - tbl: Objeto tabla
2414//                      - idc: Identificador de la Unidad organizativa donde se encuentra el cliente
2415//                      - ido: Identificador del ordenador
2416//                      - tbidhardware: Identificador del tipo de hardware
2417//                      - con: Número de componentes detectados para configurar un el perfil hardware
2418//                      - npc: Nombre del cliente
2419// ________________________________________________________________________________________________________
[d647d81]2420bool cuestionPerfilHardware(Database db, Table tbl, char *idc, char *ido,
2421                int idperfilhardware, char *idhardwares, char *npc, int *tbidhardware,
[3ec149c]2422                int lon)
2423{
2424        char msglog[LONSTD], *sqlstr;
2425        int i;
2426        int nwidperfilhard;
2427
2428        sqlstr = reservaMemoria(strlen(idhardwares)+LONSQL); // Reserva para escribir sentencia SQL
2429        if (sqlstr == NULL) {
[8c04716]2430                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]2431                return false;
[3ec149c]2432        }
2433        // Busca perfil hard del ordenador que contenga todos los componentes hardware encontrados
2434        sprintf(sqlstr, "SELECT idperfilhard FROM"
2435                " (SELECT perfileshard_hardwares.idperfilhard as idperfilhard,"
2436                "       group_concat(cast(perfileshard_hardwares.idhardware AS char( 11) )"
2437                "       ORDER BY perfileshard_hardwares.idhardware SEPARATOR ',' ) AS idhardwares"
2438                " FROM  perfileshard_hardwares"
2439                " GROUP BY perfileshard_hardwares.idperfilhard) AS temp"
2440                " WHERE idhardwares LIKE '%s'", idhardwares);
[8c04716]2441
2442        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2443                db.GetErrorErrStr(msglog);
[8c04716]2444                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2445                       __func__, __LINE__, msglog);
[fc480f2]2446                liberaMemoria(sqlstr);
[5759db40]2447                return false;
[3ec149c]2448        }
2449        if (tbl.ISEOF()) { // No existe un perfil hardware con esos componentes de componentes hardware, lo crea
2450                sprintf(sqlstr, "INSERT perfileshard  (descripcion,idcentro,grupoid)"
[df052e1]2451                                " VALUES('Perfil hardware (%s) ',%s,0)", npc, idc);
[3ec149c]2452                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2453                        db.GetErrorErrStr(msglog);
[35cc972]2454                        og_info(msglog);
[fc480f2]2455                        liberaMemoria(sqlstr);
[5759db40]2456                        return false;
[3ec149c]2457                }
2458                // Recupera el identificador del nuevo perfil hardware
2459                sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
2460                if (!db.Execute(sqlstr, tbl)) { // Error al leer
2461                        db.GetErrorErrStr(msglog);
[35cc972]2462                        og_info(msglog);
[fc480f2]2463                        liberaMemoria(sqlstr);
[5759db40]2464                        return false;
[3ec149c]2465                }
2466                if (!tbl.ISEOF()) { // Si existe registro
2467                        if (!tbl.Get("identificador", nwidperfilhard)) {
2468                                tbl.GetErrorErrStr(msglog);
[35cc972]2469                                og_info(msglog);
[fc480f2]2470                                liberaMemoria(sqlstr);
[5759db40]2471                                return false;
[3ec149c]2472                        }
2473                }
2474                // Crea la relación entre perfiles y componenetes hardware
2475                for (i = 0; i < lon; i++) {
[df052e1]2476                        sprintf(sqlstr, "INSERT perfileshard_hardwares  (idperfilhard,idhardware)"
[3ec149c]2477                                                " VALUES(%d,%d)", nwidperfilhard, tbidhardware[i]);
2478                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2479                                db.GetErrorErrStr(msglog);
[35cc972]2480                                og_info(msglog);
[fc480f2]2481                                liberaMemoria(sqlstr);
[5759db40]2482                                return false;
[3ec149c]2483                        }
2484                }
2485        } else { // Existe un perfil con todos esos componentes
2486                if (!tbl.Get("idperfilhard", nwidperfilhard)) {
2487                        tbl.GetErrorErrStr(msglog);
[35cc972]2488                        og_info(msglog);
[fc480f2]2489                        liberaMemoria(sqlstr);
[5759db40]2490                        return false;
[3ec149c]2491                }
2492        }
2493        if (idperfilhardware != nwidperfilhard) { // No coinciden los perfiles
2494                // Actualiza el identificador del perfil hardware del ordenador
2495                sprintf(sqlstr, "UPDATE ordenadores SET idperfilhard=%d"
2496                        " WHERE idordenador=%s", nwidperfilhard, ido);
2497                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2498                        db.GetErrorErrStr(msglog);
[35cc972]2499                        og_info(msglog);
[fc480f2]2500                        liberaMemoria(sqlstr);
[5759db40]2501                        return false;
[3ec149c]2502                }
2503        }
2504        /* Eliminar Relación de hardwares con Perfiles hardware que quedan húerfanos */
2505        sprintf(sqlstr, "DELETE FROM perfileshard_hardwares WHERE idperfilhard IN "
2506                " (SELECT idperfilhard FROM perfileshard WHERE idperfilhard NOT IN"
2507                " (SELECT DISTINCT idperfilhard from ordenadores))");
2508        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2509                db.GetErrorErrStr(msglog);
[35cc972]2510                og_info(msglog);
[fc480f2]2511                liberaMemoria(sqlstr);
[5759db40]2512                return false;
[3ec149c]2513        }
2514
2515        /* Eliminar Perfiles hardware que quedan húerfanos */
2516        sprintf(sqlstr, "DELETE FROM perfileshard WHERE idperfilhard NOT IN"
[fc480f2]2517                        " (SELECT DISTINCT idperfilhard FROM ordenadores)");
[3ec149c]2518        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2519                db.GetErrorErrStr(msglog);
[35cc972]2520                og_info(msglog);
[fc480f2]2521                liberaMemoria(sqlstr);
[5759db40]2522                return false;
[3ec149c]2523        }
2524        /* Eliminar Relación de hardwares con Perfiles hardware que quedan húerfanos */
[fc480f2]2525        sprintf(sqlstr, "DELETE FROM perfileshard_hardwares WHERE idperfilhard NOT IN"
2526                        " (SELECT idperfilhard FROM perfileshard)");
[3ec149c]2527        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2528                db.GetErrorErrStr(msglog);
[35cc972]2529                og_info(msglog);
[fc480f2]2530                liberaMemoria(sqlstr);
[5759db40]2531                return false;
[3ec149c]2532        }
[fc480f2]2533        liberaMemoria(sqlstr);
[5759db40]2534        return true;
[3ec149c]2535}
2536// ________________________________________________________________________________________________________
2537// Función: RESPUESTA_InventarioSoftware
2538//
2539//      Descripción:
2540//              Respuesta del cliente al comando InventarioSoftware
2541//      Parámetros:
2542//              - socket_c: Socket del cliente que envió el mensaje
2543//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2544//      Devuelve:
[5759db40]2545//              true: Si el proceso es correcto
2546//              false: En caso de ocurrir algún error
[3ec149c]2547// ________________________________________________________________________________________________________
[9baecf8]2548static bool RESPUESTA_InventarioSoftware(TRAMA* ptrTrama, struct og_client *cli)
[d647d81]2549{
[3ec149c]2550        char msglog[LONSTD];
2551        Database db;
2552        Table tbl;
[c0a46e2]2553        bool res;
[3ec149c]2554        char *iph, *ido, *npc, *idc, *par, *sft, *buffer;
2555
[8c04716]2556        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]2557                db.GetErrorErrStr(msglog);
[8c04716]2558                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2559                       __func__, __LINE__, msglog);
[5759db40]2560                return false;
[3ec149c]2561        }
2562
2563        iph = copiaParametro("iph",ptrTrama); // Toma dirección ip
2564        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
2565
2566        if (!respuestaEstandar(ptrTrama, iph, ido, db, tbl)) {
[0a73ecf7]2567                liberaMemoria(iph);
[8c04716]2568                liberaMemoria(ido);
2569                syslog(LOG_ERR, "failed to register notification\n");
2570                return false;
[3ec149c]2571        }
[8c04716]2572
[0a73ecf7]2573        npc = copiaParametro("npc",ptrTrama);
2574        idc = copiaParametro("idc",ptrTrama); // Toma identificador del Centro 
[3ec149c]2575        par = copiaParametro("par",ptrTrama);
2576        sft = copiaParametro("sft",ptrTrama);
2577
2578        buffer = rTrim(leeArchivo(sft));
[0a73ecf7]2579        if (buffer)
2580                res=actualizaSoftware(db, tbl, buffer, par, ido, npc, idc);
2581
2582        liberaMemoria(iph);
2583        liberaMemoria(ido);     
2584        liberaMemoria(npc);     
2585        liberaMemoria(idc);     
2586        liberaMemoria(par);     
2587        liberaMemoria(sft);     
2588
2589        if(!res){
[8c04716]2590                syslog(LOG_ERR, "cannot update software\n");
[5759db40]2591                return false;
[8c04716]2592        }
2593
[3ec149c]2594        db.Close(); // Cierra conexión
[5759db40]2595        return true;
[3ec149c]2596}
2597// ________________________________________________________________________________________________________
2598// Función: actualizaSoftware
2599//
2600//      Descripción:
2601//              Actualiza la base de datos con la configuración software del cliente
2602//      Parámetros:
2603//              - db: Objeto base de datos (ya operativo)
2604//              - tbl: Objeto tabla
2605//              - sft: cadena con el inventario software
2606//              - par: Número de la partición
2607//              - ido: Identificador del ordenador del cliente en la tabla
2608//              - npc: Nombre del ordenador
2609//              - idc: Identificador del centro o Unidad organizativa
2610//      Devuelve:
[5759db40]2611//              true: Si el proceso es correcto
2612//              false: En caso de ocurrir algún error
[38e2328]2613//
2614//      Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla
[3ec149c]2615// ________________________________________________________________________________________________________
[d647d81]2616bool actualizaSoftware(Database db, Table tbl, char *sft, char *par,char *ido,
2617                       char *npc, char *idc)
[0a73ecf7]2618{
[38e2328]2619        int i, j, lon, aux, idperfilsoft, idnombreso;
[fc480f2]2620        bool retval;
[0a73ecf7]2621        char *wsft;
[3ec149c]2622        int tbidsoftware[MAXSOFTWARE];
[0a73ecf7]2623        char *tbSoftware[MAXSOFTWARE],msglog[LONSTD], sqlstr[LONSQL], strInt[LONINT], *idsoftwares;
[3ec149c]2624
2625        /* Toma Centro (Unidad Organizativa) y perfil software */
2626        sprintf(sqlstr, "SELECT idperfilsoft,numpar"
2627                " FROM ordenadores_particiones"
2628                " WHERE idordenador=%s", ido);
2629
[8c04716]2630        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2631                db.GetErrorErrStr(msglog);
[8c04716]2632                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2633                       __func__, __LINE__, msglog);
[5759db40]2634                return false;
[3ec149c]2635        }
2636        idperfilsoft = 0; // Por defecto se supone que el ordenador no tiene aún detectado el perfil software
2637        while (!tbl.ISEOF()) { // Recorre particiones
2638                if (!tbl.Get("numpar", aux)) {
2639                        tbl.GetErrorErrStr(msglog);
[35cc972]2640                        og_info(msglog);
[5759db40]2641                        return false;
[3ec149c]2642                }
2643                if (aux == atoi(par)) { // Se encuentra la partición
2644                        if (!tbl.Get("idperfilsoft", idperfilsoft)) {
2645                                tbl.GetErrorErrStr(msglog);
[35cc972]2646                                og_info(msglog);
[5759db40]2647                                return false;
[3ec149c]2648                        }
2649                        break;
2650                }
2651                tbl.MoveNext();
2652        }
[0a73ecf7]2653        wsft=escaparCadena(sft); // Codificar comillas simples
2654        if(!wsft)
[5759db40]2655                return false;
[3ec149c]2656
2657        /* Recorre componentes software*/
[0a73ecf7]2658        lon = splitCadena(tbSoftware, wsft, '\n');
2659
[3ec149c]2660        if (lon == 0)
[5759db40]2661                return true; // No hay lineas que procesar
[3ec149c]2662        if (lon > MAXSOFTWARE)
2663                lon = MAXSOFTWARE; // Limita el número de componentes software
2664
2665        for (i = 0; i < lon; i++) {
[38e2328]2666                // Primera línea es el sistema operativo: se obtiene identificador
2667                if (i == 0) {
2668                        idnombreso = checkDato(db, tbl, rTrim(tbSoftware[i]), "nombresos", "nombreso", "idnombreso");
2669                        continue;
2670                }
2671
[3ec149c]2672                sprintf(sqlstr,
2673                                "SELECT idsoftware FROM softwares WHERE descripcion ='%s'",
2674                                rTrim(tbSoftware[i]));
2675
[8c04716]2676                if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2677                        db.GetErrorErrStr(msglog);
[8c04716]2678                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2679                               __func__, __LINE__, msglog);
[5759db40]2680                        return false;
[3ec149c]2681                }
2682
2683                if (tbl.ISEOF()) { //  Software NO existente
[df052e1]2684                        sprintf(sqlstr, "INSERT INTO softwares (idtiposoftware,descripcion,idcentro,grupoid)"
[3ec149c]2685                                                " VALUES(2,'%s',%s,0)", tbSoftware[i], idc);
2686
2687                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2688                                db.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2689                                og_info(msglog);
[5759db40]2690                                return false;
[3ec149c]2691                        }
2692                        // Recupera el identificador del software
2693                        sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
2694                        if (!db.Execute(sqlstr, tbl)) { // Error al leer
2695                                db.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2696                                og_info(msglog);
[5759db40]2697                                return false;
[3ec149c]2698                        }
2699                        if (!tbl.ISEOF()) { // Si existe registro
2700                                if (!tbl.Get("identificador", tbidsoftware[i])) {
2701                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2702                                        og_info(msglog);
[5759db40]2703                                        return false;
[3ec149c]2704                                }
2705                        }
2706                } else {
2707                        if (!tbl.Get("idsoftware", tbidsoftware[i])) { // Toma dato
2708                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
[35cc972]2709                                og_info(msglog);
[5759db40]2710                                return false;
[3ec149c]2711                        }
2712                }
2713        }
2714
2715        // Ordena tabla de identificadores para cosultar si existe un pefil con esas especificaciones
2716
2717        for (i = 0; i < lon - 1; i++) {
2718                for (j = i + 1; j < lon; j++) {
2719                        if (tbidsoftware[i] > tbidsoftware[j]) {
2720                                aux = tbidsoftware[i];
2721                                tbidsoftware[i] = tbidsoftware[j];
2722                                tbidsoftware[j] = aux;
2723                        }
2724                }
2725        }
2726        /* Crea cadena de identificadores de componentes software separados por coma */
2727        sprintf(strInt, "%d", tbidsoftware[lon - 1]); // Pasa a cadena el último identificador que es de mayor longitud
2728        aux = strlen(strInt); // Calcula longitud de cadena para reservar espacio a todos los perfiles
2729        idsoftwares = reservaMemoria((sizeof(aux)+1) * lon + lon);
2730        if (idsoftwares == NULL) {
[8c04716]2731                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]2732                return false;
[3ec149c]2733        }
2734        aux = sprintf(idsoftwares, "%d", tbidsoftware[0]);
2735        for (i = 1; i < lon; i++)
2736                aux += sprintf(idsoftwares + aux, ",%d", tbidsoftware[i]);
2737
2738        // Comprueba existencia de perfil software y actualización de éste para el ordenador
[38e2328]2739        if (!cuestionPerfilSoftware(db, tbl, idc, ido, idperfilsoft, idnombreso, idsoftwares,
[3ec149c]2740                        npc, par, tbidsoftware, lon)) {
[8c04716]2741                syslog(LOG_ERR, "cannot update software\n");
[35cc972]2742                og_info(msglog);
[5759db40]2743                retval=false;
[3ec149c]2744        }
[fc480f2]2745        else {
[5759db40]2746                retval=true;
[fc480f2]2747        }
[0a73ecf7]2748        liberaMemoria(wsft);
[fc480f2]2749        liberaMemoria(idsoftwares);
2750        return (retval);
[3ec149c]2751}
2752// ________________________________________________________________________________________________________
2753// Función: CuestionPerfilSoftware
2754//
2755//      Parámetros:
2756//              - db: Objeto base de datos (ya operativo)
2757//              - tbl: Objeto tabla
2758//              - idcentro: Identificador del centro en la tabla
2759//              - ido: Identificador del ordenador del cliente en la tabla
[38e2328]2760//              - idnombreso: Identificador del sistema operativo
[3ec149c]2761//              - idsoftwares: Cadena con los identificadores de componentes software separados por comas
2762//              - npc: Nombre del ordenador del cliente
2763//              - particion: Número de la partición
2764//              - tbidsoftware: Array con los identificadores de componentes software
2765//              - lon: Número de componentes
2766//      Devuelve:
[5759db40]2767//              true: Si el proceso es correcto
2768//              false: En caso de ocurrir algún error
[38e2328]2769//
2770//      Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla
2771//_________________________________________________________________________________________________________
[d647d81]2772bool cuestionPerfilSoftware(Database db, Table tbl, char *idc, char *ido,
2773                            int idperfilsoftware, int idnombreso,
2774                            char *idsoftwares, char *npc, char *par,
2775                            int *tbidsoftware, int lon)
2776{
[3ec149c]2777        char *sqlstr, msglog[LONSTD];
2778        int i, nwidperfilsoft;
2779
2780        sqlstr = reservaMemoria(strlen(idsoftwares)+LONSQL); // Reserva para escribir sentencia SQL
2781        if (sqlstr == NULL) {
[8c04716]2782                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
[5759db40]2783                return false;
[3ec149c]2784        }
2785        // Busca perfil soft del ordenador que contenga todos los componentes software encontrados
2786        sprintf(sqlstr, "SELECT idperfilsoft FROM"
2787                " (SELECT perfilessoft_softwares.idperfilsoft as idperfilsoft,"
2788                "       group_concat(cast(perfilessoft_softwares.idsoftware AS char( 11) )"
2789                "       ORDER BY perfilessoft_softwares.idsoftware SEPARATOR ',' ) AS idsoftwares"
2790                " FROM  perfilessoft_softwares"
2791                " GROUP BY perfilessoft_softwares.idperfilsoft) AS temp"
2792                " WHERE idsoftwares LIKE '%s'", idsoftwares);
[8c04716]2793
2794        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2795                db.GetErrorErrStr(msglog);
[8c04716]2796                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2797                       __func__, __LINE__, msglog);
[fc480f2]2798                liberaMemoria(sqlstr);
[5759db40]2799                return false;
[3ec149c]2800        }
2801        if (tbl.ISEOF()) { // No existe un perfil software con esos componentes de componentes software, lo crea
[38e2328]2802                sprintf(sqlstr, "INSERT perfilessoft  (descripcion, idcentro, grupoid, idnombreso)"
2803                                " VALUES('Perfil Software (%s, Part:%s) ',%s,0,%i)", npc, par, idc,idnombreso);
[3ec149c]2804                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2805                        db.GetErrorErrStr(msglog);
[35cc972]2806                        og_info(msglog);
[5759db40]2807                        return false;
[3ec149c]2808                }
2809                // Recupera el identificador del nuevo perfil software
2810                sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
2811                if (!db.Execute(sqlstr, tbl)) { // Error al leer
2812                        tbl.GetErrorErrStr(msglog);
[35cc972]2813                        og_info(msglog);
[fc480f2]2814                        liberaMemoria(sqlstr);
[5759db40]2815                        return false;
[3ec149c]2816                }
2817                if (!tbl.ISEOF()) { // Si existe registro
2818                        if (!tbl.Get("identificador", nwidperfilsoft)) {
2819                                tbl.GetErrorErrStr(msglog);
[35cc972]2820                                og_info(msglog);
[fc480f2]2821                                liberaMemoria(sqlstr);
[5759db40]2822                                return false;
[3ec149c]2823                        }
2824                }
2825                // Crea la relación entre perfiles y componenetes software
2826                for (i = 0; i < lon; i++) {
[fc480f2]2827                        sprintf(sqlstr, "INSERT perfilessoft_softwares (idperfilsoft,idsoftware)"
[3ec149c]2828                                                " VALUES(%d,%d)", nwidperfilsoft, tbidsoftware[i]);
2829                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2830                                db.GetErrorErrStr(msglog);
[35cc972]2831                                og_info(msglog);
[fc480f2]2832                                liberaMemoria(sqlstr);
[5759db40]2833                                return false;
[3ec149c]2834                        }
2835                }
2836        } else { // Existe un perfil con todos esos componentes
2837                if (!tbl.Get("idperfilsoft", nwidperfilsoft)) {
2838                        tbl.GetErrorErrStr(msglog);
[35cc972]2839                        og_info(msglog);
[fc480f2]2840                        liberaMemoria(sqlstr);
[5759db40]2841                        return false;
[3ec149c]2842                }
2843        }
2844
2845        if (idperfilsoftware != nwidperfilsoft) { // No coinciden los perfiles
2846                // Actualiza el identificador del perfil software del ordenador
[fc480f2]2847                sprintf(sqlstr, "UPDATE ordenadores_particiones SET idperfilsoft=%d,idimagen=0"
2848                                " WHERE idordenador=%s AND numpar=%s", nwidperfilsoft, ido, par);
[3ec149c]2849                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2850                        db.GetErrorErrStr(msglog);
[35cc972]2851                        og_info(msglog);
[fc480f2]2852                        liberaMemoria(sqlstr);
[5759db40]2853                        return false;
[3ec149c]2854                }
2855        }
2856
2857        /* DEPURACIÓN DE PERFILES SOFTWARE */
2858
2859         /* Eliminar Relación de softwares con Perfiles software que quedan húerfanos */
2860        sprintf(sqlstr, "DELETE FROM perfilessoft_softwares WHERE idperfilsoft IN "\
2861                " (SELECT idperfilsoft FROM perfilessoft WHERE idperfilsoft NOT IN"\
2862                " (SELECT DISTINCT idperfilsoft from ordenadores_particiones) AND idperfilsoft NOT IN"\
2863                " (SELECT DISTINCT idperfilsoft from imagenes))");
2864        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2865                db.GetErrorErrStr(msglog);
[35cc972]2866                og_info(msglog);
[fc480f2]2867                liberaMemoria(sqlstr);
[5759db40]2868                return false;
[3ec149c]2869        }
2870        /* Eliminar Perfiles software que quedan húerfanos */
2871        sprintf(sqlstr, "DELETE FROM perfilessoft WHERE idperfilsoft NOT IN"
2872                " (SELECT DISTINCT idperfilsoft from ordenadores_particiones)"\
2873                " AND  idperfilsoft NOT IN"\
2874                " (SELECT DISTINCT idperfilsoft from imagenes)");
2875        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2876                db.GetErrorErrStr(msglog);
[35cc972]2877                og_info(msglog);
[fc480f2]2878                liberaMemoria(sqlstr);
[5759db40]2879                return false;
[3ec149c]2880        }
2881        /* Eliminar Relación de softwares con Perfiles software que quedan húerfanos */
[fc480f2]2882        sprintf(sqlstr, "DELETE FROM perfilessoft_softwares WHERE idperfilsoft NOT IN"
2883                        " (SELECT idperfilsoft from perfilessoft)");
[3ec149c]2884        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2885                db.GetErrorErrStr(msglog);
[35cc972]2886                og_info(msglog);
[fc480f2]2887                liberaMemoria(sqlstr);
[5759db40]2888                return false;
[3ec149c]2889        }
[fc480f2]2890        liberaMemoria(sqlstr);
[5759db40]2891        return true;
[3ec149c]2892}
2893// ________________________________________________________________________________________________________
2894// Función: enviaArchivo
2895//
2896//      Descripción:
2897//              Envia un archivo por la red, por bloques
2898//      Parámetros:
2899//              - socket_c: Socket del cliente que envió el mensaje
2900//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2901//      Devuelve:
[5759db40]2902//              true: Si el proceso es correcto
2903//              false: En caso de ocurrir algún error
[3ec149c]2904// ________________________________________________________________________________________________________
[9baecf8]2905static bool enviaArchivo(TRAMA *ptrTrama, struct og_client *cli)
[d647d81]2906{
[9baecf8]2907        int socket_c = og_client_socket(cli);
[3ec149c]2908        char *nfl;
2909
2910        // Toma parámetros
2911        nfl = copiaParametro("nfl",ptrTrama); // Toma nombre completo del archivo
[ba03878]2912        if (!sendArchivo(&socket_c, nfl)) {
[0a73ecf7]2913                liberaMemoria(nfl);
[8c04716]2914                syslog(LOG_ERR, "Problem sending file\n");
[5759db40]2915                return false;
[3ec149c]2916        }
[0a73ecf7]2917        liberaMemoria(nfl);
[5759db40]2918        return true;
[3ec149c]2919}
2920// ________________________________________________________________________________________________________
2921// Función: enviaArchivo
2922//
2923//      Descripción:
2924//              Envia un archivo por la red, por bloques
2925//      Parámetros:
2926//              - socket_c: Socket del cliente que envió el mensaje
2927//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2928//      Devuelve:
[5759db40]2929//              true: Si el proceso es correcto
2930//              false: En caso de ocurrir algún error
[3ec149c]2931// ________________________________________________________________________________________________________
[9baecf8]2932static bool recibeArchivo(TRAMA *ptrTrama, struct og_client *cli)
[d647d81]2933{
[9baecf8]2934        int socket_c = og_client_socket(cli);
[3ec149c]2935        char *nfl;
2936
2937        // Toma parámetros
2938        nfl = copiaParametro("nfl",ptrTrama); // Toma nombre completo del archivo
2939        ptrTrama->tipo = MSG_NOTIFICACION;
[ba03878]2940        enviaFlag(&socket_c, ptrTrama);
2941        if (!recArchivo(&socket_c, nfl)) {
[0a73ecf7]2942                liberaMemoria(nfl);
[8c04716]2943                syslog(LOG_ERR, "Problem receiving file\n");
[5759db40]2944                return false;
[3ec149c]2945        }
[0a73ecf7]2946        liberaMemoria(nfl);
[5759db40]2947        return true;
[3ec149c]2948}
2949// ________________________________________________________________________________________________________
2950// Función: envioProgramacion
2951//
2952//      Descripción:
2953//              Envia un comando de actualización a todos los ordenadores que han sido programados con
2954//              alguna acción para que entren en el bucle de comandos pendientes y las ejecuten
2955//      Parámetros:
2956//              - socket_c: Socket del cliente que envió el mensaje
2957//              - ptrTrama: Trama recibida por el servidor con el contenido y los parámetros
2958//      Devuelve:
[5759db40]2959//              true: Si el proceso es correcto
2960//              false: En caso de ocurrir algún error
[3ec149c]2961// ________________________________________________________________________________________________________
[9baecf8]2962static bool envioProgramacion(TRAMA *ptrTrama, struct og_client *cli)
[3ec149c]2963{
[62c0560]2964        char *ptrIP[MAXIMOS_CLIENTES],*ptrMacs[MAXIMOS_CLIENTES];
[3ec149c]2965        char sqlstr[LONSQL], msglog[LONSTD];
[db4d467]2966        char *idp,iph[LONIP],mac[LONMAC];
[3ec149c]2967        Database db;
2968        Table tbl;
[62c0560]2969        int idx,idcomando,lon;
[3ec149c]2970
[8c04716]2971        if (!db.Open(usuario, pasguor, datasource, catalog)) {
[3ec149c]2972                db.GetErrorErrStr(msglog);
[8c04716]2973                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2974                       __func__, __LINE__, msglog);
[5759db40]2975                return false;
[3ec149c]2976        }
2977
[0a73ecf7]2978        idp = copiaParametro("idp",ptrTrama); // Toma identificador de la programación de la tabla acciones
[3ec149c]2979
2980        sprintf(sqlstr, "SELECT ordenadores.ip,ordenadores.mac,acciones.idcomando FROM acciones "\
2981                        " INNER JOIN ordenadores ON ordenadores.ip=acciones.ip"\
2982                        " WHERE acciones.idprogramacion=%s",idp);
[0a73ecf7]2983       
2984        liberaMemoria(idp);
[8c04716]2985
2986        if (!db.Execute(sqlstr, tbl)) {
[3ec149c]2987                db.GetErrorErrStr(msglog);
[8c04716]2988                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2989                       __func__, __LINE__, msglog);
[5759db40]2990                return false;
[3ec149c]2991        }
[4d2cdae]2992        db.Close();
[3ec149c]2993        if(tbl.ISEOF())
[5759db40]2994                return true; // No existen registros
[3ec149c]2995
2996        /* Prepara la trama de actualizacion */
2997
2998        initParametros(ptrTrama,0);
2999        ptrTrama->tipo=MSG_COMANDO;
3000        sprintf(ptrTrama->parametros, "nfn=Actualizar\r");
3001
3002        while (!tbl.ISEOF()) { // Recorre particiones
3003                if (!tbl.Get("ip", iph)) {
3004                        tbl.GetErrorErrStr(msglog);
[95654f4]3005                        syslog(LOG_ERR, "cannot find ip column in table: %s\n",
3006                               msglog);
[5759db40]3007                        return false;
[3ec149c]3008                }
3009                if (!tbl.Get("idcomando", idcomando)) {
3010                        tbl.GetErrorErrStr(msglog);
[95654f4]3011                        syslog(LOG_ERR, "cannot find idcomando column in table: %s\n",
3012                               msglog);
[5759db40]3013                        return false;
[3ec149c]3014                }
3015                if(idcomando==1){ // Arrancar
3016                        if (!tbl.Get("mac", mac)) {
3017                                tbl.GetErrorErrStr(msglog);
[95654f4]3018                                syslog(LOG_ERR, "cannot find mac column in table: %s\n",
3019                                       msglog);
[5759db40]3020                                return false;
[3ec149c]3021                        }
[c916af9]3022
[62c0560]3023                        lon = splitCadena(ptrIP, iph, ';');
3024                        lon = splitCadena(ptrMacs, mac, ';');
3025
[e70c867]3026                        // Se manda por broadcast y por unicast
[62c0560]3027                        if (!Levanta(ptrIP, ptrMacs, lon, (char*)"1"))
[5759db40]3028                                return false;
[e70c867]3029
[62c0560]3030                        if (!Levanta(ptrIP, ptrMacs, lon, (char*)"2"))
[5759db40]3031                                return false;
[e70c867]3032
[3ec149c]3033                }
3034                if (clienteDisponible(iph, &idx)) { // Si el cliente puede recibir comandos
[2e0c063]3035                        int sock = tbsockets[idx].cli ? tbsockets[idx].cli->io.fd : -1;
3036
[3ec149c]3037                        strcpy(tbsockets[idx].estado, CLIENTE_OCUPADO); // Actualiza el estado del cliente
[0deba63]3038                        if (sock >= 0 && !mandaTrama(&sock, ptrTrama)) {
[8c04716]3039                                syslog(LOG_ERR, "failed to send response: %s\n",
3040                                       strerror(errno));
[3ec149c]3041                        }
[eeeb98a]3042                        //close(tbsockets[idx].sock); // Cierra el socket del cliente hasta nueva disponibilidad
[3ec149c]3043                }
3044                tbl.MoveNext();
3045        }
[5759db40]3046        return true; // No existen registros
[3ec149c]3047}
[f997cc1]3048
3049// This object stores function handler for messages
3050static struct {
3051        const char *nf; // Nombre de la función
[9baecf8]3052        bool (*fcn)(TRAMA *, struct og_client *cli);
[0e095f1]3053} tbfuncionesServer[] = {
[f997cc1]3054        { "InclusionCliente",                   InclusionCliente,       },
3055        { "InclusionClienteWinLnx",             InclusionClienteWinLnx, },
3056        { "AutoexecCliente",                    AutoexecCliente,        },
3057        { "ComandosPendientes",                 ComandosPendientes,     },
3058        { "DisponibilidadComandos",             DisponibilidadComandos, },
3059        { "RESPUESTA_Arrancar",                 RESPUESTA_Arrancar,     },
3060        { "RESPUESTA_Apagar",                   RESPUESTA_Apagar,       },
3061        { "RESPUESTA_Reiniciar",                RESPUESTA_Reiniciar,    },
3062        { "RESPUESTA_IniciarSesion",            RESPUESTA_IniciarSesion, },
3063        { "RESPUESTA_CrearImagen",              RESPUESTA_CrearImagen,  },
3064        { "CrearImagenBasica",                  CrearImagenBasica,      },
3065        { "RESPUESTA_CrearImagenBasica",        RESPUESTA_CrearImagenBasica, },
3066        { "CrearSoftIncremental",               CrearSoftIncremental,   },
3067        { "RESPUESTA_CrearSoftIncremental",     RESPUESTA_CrearSoftIncremental, },
3068        { "RESPUESTA_RestaurarImagen",          RESPUESTA_RestaurarImagen },
3069        { "RestaurarImagenBasica",              RestaurarImagenBasica, },
3070        { "RESPUESTA_RestaurarImagenBasica",    RESPUESTA_RestaurarImagenBasica, },
3071        { "RestaurarSoftIncremental",           RestaurarSoftIncremental, },
3072        { "RESPUESTA_RestaurarSoftIncremental", RESPUESTA_RestaurarSoftIncremental, },
3073        { "Configurar",                         Configurar,             },
3074        { "RESPUESTA_Configurar",               RESPUESTA_Configurar,   },
3075        { "EjecutarScript",                     EjecutarScript,         },
3076        { "RESPUESTA_EjecutarScript",           RESPUESTA_EjecutarScript, },
3077        { "RESPUESTA_InventarioHardware",       RESPUESTA_InventarioHardware, },
3078        { "RESPUESTA_InventarioSoftware",       RESPUESTA_InventarioSoftware, },
3079        { "enviaArchivo",                       enviaArchivo,           },
3080        { "recibeArchivo",                      recibeArchivo,          },
3081        { "envioProgramacion",                  envioProgramacion,      },
[0e095f1]3082        { NULL,                                 NULL,                   },
[f997cc1]3083};
3084
3085// ________________________________________________________________________________________________________
3086// Función: gestionaTrama
3087//
3088//              Descripción:
3089//                      Procesa las tramas recibidas .
3090//              Parametros:
3091//                      - s : Socket usado para comunicaciones
3092//      Devuelve:
[5759db40]3093//              true: Si el proceso es correcto
3094//              false: En caso de ocurrir algún error
[f997cc1]3095// ________________________________________________________________________________________________________
[8c04716]3096static void gestionaTrama(TRAMA *ptrTrama, struct og_client *cli)
[f997cc1]3097{
3098        int i, res;
3099        char *nfn;
3100
3101        if (ptrTrama){
3102                INTROaFINCAD(ptrTrama);
3103                nfn = copiaParametro("nfn",ptrTrama); // Toma nombre de la función
3104
[9baecf8]3105                for (i = 0; tbfuncionesServer[i].fcn; i++) {
3106                        if (!strncmp(tbfuncionesServer[i].nf, nfn,
3107                                     strlen(tbfuncionesServer[i].nf))) {
3108                                res = tbfuncionesServer[i].fcn(ptrTrama, cli);
[8c04716]3109                                if (!res) {
3110                                        syslog(LOG_ERR, "Failed handling of %s for client %s:%hu\n",
3111                                               tbfuncionesServer[i].nf,
3112                                               inet_ntoa(cli->addr.sin_addr),
3113                                               ntohs(cli->addr.sin_port));
3114                                } else {
3115                                        syslog(LOG_DEBUG, "Successful handling of %s for client %s:%hu\n",
3116                                               tbfuncionesServer[i].nf,
3117                                               inet_ntoa(cli->addr.sin_addr),
3118                                               ntohs(cli->addr.sin_port));
3119                                }
[9baecf8]3120                                break;
[f997cc1]3121                        }
3122                }
[13e48b4]3123                if (!tbfuncionesServer[i].fcn)
[2e0c063]3124                        syslog(LOG_ERR, "unknown request %s from client %s:%hu\n",
3125                               nfn, inet_ntoa(cli->addr.sin_addr),
3126                               ntohs(cli->addr.sin_port));
[13e48b4]3127
[f997cc1]3128                liberaMemoria(nfn);
[9baecf8]3129        }
3130}
3131
[2e0c063]3132static void og_client_release(struct ev_loop *loop, struct og_client *cli)
3133{
3134        if (cli->keepalive_idx >= 0) {
[0e16db2]3135                syslog(LOG_DEBUG, "closing keepalive connection for %s:%hu in slot %d\n",
[2e0c063]3136                       inet_ntoa(cli->addr.sin_addr),
3137                       ntohs(cli->addr.sin_port), cli->keepalive_idx);
3138                tbsockets[cli->keepalive_idx].cli = NULL;
3139        }
3140
3141        ev_io_stop(loop, &cli->io);
3142        close(cli->io.fd);
3143        free(cli);
3144}
3145
3146static void og_client_keepalive(struct ev_loop *loop, struct og_client *cli)
3147{
3148        struct og_client *old_cli;
3149
3150        old_cli = tbsockets[cli->keepalive_idx].cli;
3151        if (old_cli && old_cli != cli) {
[0e16db2]3152                syslog(LOG_DEBUG, "closing old keepalive connection for %s:%hu\n",
[2e0c063]3153                       inet_ntoa(old_cli->addr.sin_addr),
3154                       ntohs(old_cli->addr.sin_port));
3155
3156                og_client_release(loop, old_cli);
3157        }
3158        tbsockets[cli->keepalive_idx].cli = cli;
3159}
3160
3161static void og_client_reset_state(struct og_client *cli)
3162{
3163        cli->state = OG_CLIENT_RECEIVING_HEADER;
3164        cli->buf_len = 0;
3165}
3166
[39c3261]3167static int og_client_state_recv_hdr(struct og_client *cli)
[9baecf8]3168{
3169        char hdrlen[LONHEXPRM];
[39c3261]3170
3171        /* Still too short to validate protocol fingerprint and message
3172         * length.
3173         */
3174        if (cli->buf_len < 15 + LONHEXPRM)
3175                return 0;
3176
3177        if (strncmp(cli->buf, "@JMMLCAMDJ_MCDJ", 15)) {
3178                syslog(LOG_ERR, "bad fingerprint from client %s:%hu, closing\n",
3179                       inet_ntoa(cli->addr.sin_addr),
3180                       ntohs(cli->addr.sin_port));
3181                return -1;
3182        }
3183
3184        memcpy(hdrlen, &cli->buf[LONGITUD_CABECERATRAMA], LONHEXPRM);
3185        cli->msg_len = strtol(hdrlen, NULL, 16);
3186
3187        /* Header announces more that we can fit into buffer. */
3188        if (cli->msg_len >= sizeof(cli->buf)) {
3189                syslog(LOG_ERR, "too large message %u bytes from %s:%hu\n",
3190                       cli->msg_len, inet_ntoa(cli->addr.sin_addr),
3191                       ntohs(cli->addr.sin_port));
3192                return -1;
3193        }
3194
3195        return 1;
3196}
3197
[3973759]3198static TRAMA *og_msg_alloc(char *data, unsigned int len)
[39c3261]3199{
[9baecf8]3200        TRAMA *ptrTrama;
[07c51e2]3201
3202        ptrTrama = (TRAMA *)reservaMemoria(sizeof(TRAMA));
3203        if (!ptrTrama) {
3204                syslog(LOG_ERR, "OOM\n");
[3973759]3205                return NULL;
[07c51e2]3206        }
3207
3208        initParametros(ptrTrama, len);
[3973759]3209        memcpy(ptrTrama, "@JMMLCAMDJ_MCDJ", LONGITUD_CABECERATRAMA);
[07c51e2]3210        memcpy(ptrTrama->parametros, data, len);
3211        ptrTrama->lonprm = len;
3212
[3973759]3213        return ptrTrama;
3214}
[07c51e2]3215
[3973759]3216static void og_msg_free(TRAMA *ptrTrama)
3217{
[07c51e2]3218        liberaMemoria(ptrTrama->parametros);
3219        liberaMemoria(ptrTrama);
[3973759]3220}
3221
3222static int og_client_state_process_payload(struct og_client *cli)
3223{
3224        TRAMA *ptrTrama;
3225        char *data;
3226        int len;
3227
3228        len = cli->msg_len - (LONGITUD_CABECERATRAMA + LONHEXPRM);
3229        data = &cli->buf[LONGITUD_CABECERATRAMA + LONHEXPRM];
3230
3231        ptrTrama = og_msg_alloc(data, len);
3232        if (!ptrTrama)
3233                return -1;
3234
3235        gestionaTrama(ptrTrama, cli);
3236
3237        og_msg_free(ptrTrama);
[07c51e2]3238
3239        return 1;
3240}
3241
[c935fc9]3242#define OG_CLIENTS_MAX  4096
[2385710e]3243#define OG_PARTITION_MAX 4
3244
3245struct og_partition {
3246        const char      *number;
3247        const char      *code;
3248        const char      *size;
3249        const char      *filesystem;
3250        const char      *format;
3251};
[c935fc9]3252
[1a08c06]3253struct og_msg_params {
[c935fc9]3254        const char      *ips_array[OG_CLIENTS_MAX];
3255        const char      *mac_array[OG_CLIENTS_MAX];
[1a08c06]3256        unsigned int    ips_array_len;
[73c4bdff]3257        const char      *wol_type;
[775f6f0]3258        char            run_cmd[4096];
[22ab637]3259        const char      *disk;
3260        const char      *partition;
[7f2dd15]3261        const char      *repository;
3262        const char      *name;
3263        const char      *id;
3264        const char      *code;
[fc15dd1]3265        const char      *type;
3266        const char      *profile;
[2385710e]3267        const char      *cache;
3268        const char      *cache_size;
3269        struct og_partition     partition_setup[OG_PARTITION_MAX];
[1a08c06]3270};
3271
3272static int og_json_parse_clients(json_t *element, struct og_msg_params *params)
3273{
3274        unsigned int i;
3275        json_t *k;
3276
3277        if (json_typeof(element) != JSON_ARRAY)
3278                return -1;
3279
3280        for (i = 0; i < json_array_size(element); i++) {
3281                k = json_array_get(element, i);
3282                if (json_typeof(k) != JSON_STRING)
3283                        return -1;
3284
3285                params->ips_array[params->ips_array_len++] =
3286                        json_string_value(k);
3287        }
3288        return 0;
3289}
3290
[70b1e58]3291static int og_json_parse_string(json_t *element, const char **str)
3292{
3293        if (json_typeof(element) != JSON_STRING)
3294                return -1;
3295
3296        *str = json_string_value(element);
3297        return 0;
3298}
3299
[2385710e]3300static void og_json_parse_partition(json_t *element, og_partition *part)
3301{
3302        part->number = json_string_value(json_object_get(element, "partition"));
3303        part->code = json_string_value(json_object_get(element, "code"));
3304        part->filesystem = json_string_value(json_object_get(element, "filesystem"));
3305        part->size = json_string_value(json_object_get(element, "size"));
3306        part->format = json_string_value(json_object_get(element, "format"));
3307}
3308
3309static int og_json_parse_partition_setup(json_t *element, og_partition *part)
3310{
3311        unsigned int i;
3312        json_t *k;
3313
3314        if (json_typeof(element) != JSON_ARRAY)
3315                return -1;
3316
3317        for (i = 0; i < json_array_size(element) && i < OG_PARTITION_MAX; ++i) {
3318                k = json_array_get(element, i);
3319
3320                if (json_typeof(k) != JSON_OBJECT)
3321                        return -1;
3322
3323                og_json_parse_partition(k, part + i);
3324        }
3325        return 0;
3326}
3327
[8411d3b]3328static int og_cmd_legacy_send(struct og_msg_params *params, const char *cmd,
3329                              const char *state)
[1a08c06]3330{
3331        char buf[4096] = {};
3332        int len, err = 0;
3333        TRAMA *msg;
3334
[8411d3b]3335        len = snprintf(buf, sizeof(buf), "nfn=%s\r", cmd);
[1a08c06]3336
3337        msg = og_msg_alloc(buf, len);
3338        if (!msg)
3339                return -1;
3340
3341        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
[8411d3b]3342                         state, msg))
[1a08c06]3343                err = -1;
3344
3345        og_msg_free(msg);
3346
3347        return err;
3348}
3349
3350static int og_cmd_post_clients(json_t *element, struct og_msg_params *params)
3351{
3352        const char *key;
3353        json_t *value;
3354        int err = 0;
3355
3356        if (json_typeof(element) != JSON_OBJECT)
3357                return -1;
3358
3359        json_object_foreach(element, key, value) {
3360                if (!strcmp(key, "clients"))
3361                        err = og_json_parse_clients(value, params);
3362
3363                if (err < 0)
3364                        break;
3365        }
3366
[8411d3b]3367        return og_cmd_legacy_send(params, "Sondeo", CLIENTE_APAGADO);
[1a08c06]3368}
3369
[ea03692]3370struct og_buffer {
3371        char    *data;
3372        int     len;
3373};
3374
3375static int og_json_dump_clients(const char *buffer, size_t size, void *data)
3376{
3377        struct og_buffer *og_buffer = (struct og_buffer *)data;
3378
3379        memcpy(og_buffer->data + og_buffer->len, buffer, size);
3380        og_buffer->len += size;
3381
3382        return 0;
3383}
3384
3385static int og_cmd_get_clients(json_t *element, struct og_msg_params *params,
3386                              char *buffer_reply)
3387{
3388        json_t *root, *array, *addr, *state, *object;
3389        struct og_buffer og_buffer = {
3390                .data   = buffer_reply,
3391        };
3392        int i;
3393
3394        array = json_array();
3395        if (!array)
3396                return -1;
3397
3398        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
3399                if (tbsockets[i].ip[0] == '\0')
3400                        continue;
3401
3402                object = json_object();
3403                if (!object) {
3404                        json_decref(array);
3405                        return -1;
3406                }
3407                addr = json_string(tbsockets[i].ip);
3408                if (!addr) {
3409                        json_decref(object);
3410                        json_decref(array);
3411                        return -1;
3412                }
3413                json_object_set_new(object, "addr", addr);
3414
3415                state = json_string(tbsockets[i].estado);
3416                if (!state) {
3417                        json_decref(object);
3418                        json_decref(array);
3419                        return -1;
3420                }
3421                json_object_set_new(object, "state", state);
3422
3423                json_array_append_new(array, object);
3424        }
3425        root = json_pack("{s:o}", "clients", array);
3426        if (!root) {
3427                json_decref(array);
3428                return -1;
3429        }
3430
[a36ed20]3431        json_dump_callback(root, og_json_dump_clients, &og_buffer, 0);
[ea03692]3432        json_decref(root);
3433
3434        return 0;
3435}
3436
[73c4bdff]3437static int og_json_parse_target(json_t *element, struct og_msg_params *params)
3438{
3439        const char *key;
3440        json_t *value;
3441
3442        if (json_typeof(element) != JSON_OBJECT) {
3443                return -1;
3444        }
3445
3446        json_object_foreach(element, key, value) {
3447                if (!strcmp(key, "addr")) {
3448                        if (json_typeof(value) != JSON_STRING)
3449                                return -1;
3450
3451                        params->ips_array[params->ips_array_len] =
3452                                json_string_value(value);
3453                } else if (!strcmp(key, "mac")) {
3454                        if (json_typeof(value) != JSON_STRING)
3455                                return -1;
3456
3457                        params->mac_array[params->ips_array_len] =
3458                                json_string_value(value);
3459                }
3460        }
3461
3462        return 0;
3463}
3464
3465static int og_json_parse_targets(json_t *element, struct og_msg_params *params)
3466{
3467        unsigned int i;
3468        json_t *k;
3469        int err;
3470
3471        if (json_typeof(element) != JSON_ARRAY)
3472                return -1;
3473
3474        for (i = 0; i < json_array_size(element); i++) {
3475                k = json_array_get(element, i);
3476
3477                if (json_typeof(k) != JSON_OBJECT)
3478                        return -1;
3479
3480                err = og_json_parse_target(k, params);
3481                if (err < 0)
3482                        return err;
3483
3484                params->ips_array_len++;
3485        }
3486        return 0;
3487}
3488
3489static int og_json_parse_type(json_t *element, struct og_msg_params *params)
3490{
3491        const char *type;
3492
3493        if (json_typeof(element) != JSON_STRING)
3494                return -1;
3495
3496        params->wol_type = json_string_value(element);
3497
3498        type = json_string_value(element);
3499        if (!strcmp(type, "unicast"))
3500                params->wol_type = "2";
3501        else if (!strcmp(type, "broadcast"))
3502                params->wol_type = "1";
3503
3504        return 0;
3505}
3506
3507static int og_cmd_wol(json_t *element, struct og_msg_params *params)
3508{
3509        const char *key;
3510        json_t *value;
3511        int err = 0;
3512
3513        if (json_typeof(element) != JSON_OBJECT)
3514                return -1;
3515
3516        json_object_foreach(element, key, value) {
3517                if (!strcmp(key, "clients")) {
3518                        err = og_json_parse_targets(value, params);
3519                } else if (!strcmp(key, "type")) {
3520                        err = og_json_parse_type(value, params);
3521                }
3522
3523                if (err < 0)
3524                        break;
3525        }
3526
3527        if (!Levanta((char **)params->ips_array, (char **)params->mac_array,
3528                     params->ips_array_len, (char *)params->wol_type))
3529                return -1;
3530
3531        return 0;
3532}
3533
[775f6f0]3534static int og_json_parse_run(json_t *element, struct og_msg_params *params)
3535{
3536        if (json_typeof(element) != JSON_STRING)
3537                return -1;
3538
3539        snprintf(params->run_cmd, sizeof(params->run_cmd), "%s",
3540                 json_string_value(element));
3541
3542        return 0;
3543}
3544
3545static int og_cmd_run_post(json_t *element, struct og_msg_params *params)
3546{
3547        char buf[4096] = {}, iph[4096] = {};
3548        int err = 0, len;
3549        const char *key;
3550        unsigned int i;
3551        json_t *value;
3552        TRAMA *msg;
3553
3554        if (json_typeof(element) != JSON_OBJECT)
3555                return -1;
3556
3557        json_object_foreach(element, key, value) {
3558                if (!strcmp(key, "clients"))
3559                        err = og_json_parse_clients(value, params);
3560                if (!strcmp(key, "run"))
3561                        err = og_json_parse_run(value, params);
3562
3563                if (err < 0)
3564                        break;
3565        }
3566
3567        for (i = 0; i < params->ips_array_len; i++) {
3568                len = snprintf(iph + strlen(iph), sizeof(iph), "%s;",
3569                               params->ips_array[i]);
3570        }
3571        len = snprintf(buf, sizeof(buf), "nfn=ConsolaRemota\riph=%s\rscp=%s\r",
3572                       iph, params->run_cmd);
3573
3574        msg = og_msg_alloc(buf, len);
3575        if (!msg)
3576                return -1;
3577
3578        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
3579                         CLIENTE_OCUPADO, msg))
3580                err = -1;
3581
3582        og_msg_free(msg);
3583
3584        if (err < 0)
3585                return err;
3586
3587        for (i = 0; i < params->ips_array_len; i++) {
3588                char filename[4096];
3589                FILE *f;
3590
3591                sprintf(filename, "/tmp/_Seconsola_%s", params->ips_array[i]);
3592                f = fopen(filename, "wt");
3593                fclose(f);
3594        }
3595
3596        return 0;
3597}
3598
[165cea3]3599static int og_cmd_run_get(json_t *element, struct og_msg_params *params,
3600                          char *buffer_reply)
3601{
3602        struct og_buffer og_buffer = {
3603                .data   = buffer_reply,
3604        };
3605        json_t *root, *value, *array;
3606        const char *key;
3607        unsigned int i;
3608        int err = 0;
3609
3610        if (json_typeof(element) != JSON_OBJECT)
3611                return -1;
3612
3613        json_object_foreach(element, key, value) {
3614                if (!strcmp(key, "clients"))
3615                        err = og_json_parse_clients(value, params);
3616
3617                if (err < 0)
3618                        return err;
3619        }
3620
3621        array = json_array();
3622        if (!array)
3623                return -1;
3624
3625        for (i = 0; i < params->ips_array_len; i++) {
3626                json_t *object, *output, *addr;
3627                char data[4096] = {};
3628                char filename[4096];
3629                int fd, numbytes;
3630
3631                sprintf(filename, "/tmp/_Seconsola_%s", params->ips_array[i]);
3632
3633                fd = open(filename, O_RDONLY);
3634                if (!fd)
3635                        return -1;
3636
3637                numbytes = read(fd, data, sizeof(data));
3638                if (numbytes < 0) {
3639                        close(fd);
3640                        return -1;
3641                }
3642                data[sizeof(data) - 1] = '\0';
3643                close(fd);
3644
3645                object = json_object();
3646                if (!object) {
3647                        json_decref(array);
3648                        return -1;
3649                }
3650                addr = json_string(params->ips_array[i]);
3651                if (!addr) {
3652                        json_decref(object);
3653                        json_decref(array);
3654                        return -1;
3655                }
3656                json_object_set_new(object, "addr", addr);
3657
3658                output = json_string(data);
3659                if (!output) {
3660                        json_decref(object);
3661                        json_decref(array);
3662                        return -1;
3663                }
3664                json_object_set_new(object, "output", output);
3665
3666                json_array_append_new(array, object);
3667        }
3668
3669        root = json_pack("{s:o}", "clients", array);
3670        if (!root)
3671                return -1;
3672
[a36ed20]3673        json_dump_callback(root, og_json_dump_clients, &og_buffer, 0);
[165cea3]3674        json_decref(root);
3675
3676        return 0;
3677}
3678
[22ab637]3679static int og_cmd_session(json_t *element, struct og_msg_params *params)
3680{
3681        char buf[4096], iph[4096];
3682        int err = 0, len;
3683        const char *key;
3684        unsigned int i;
3685        json_t *value;
3686        TRAMA *msg;
3687
3688        if (json_typeof(element) != JSON_OBJECT)
3689                return -1;
3690
3691        json_object_foreach(element, key, value) {
[fe0e6c4]3692                if (!strcmp(key, "clients"))
[22ab637]3693                        err = og_json_parse_clients(value, params);
[fe0e6c4]3694                else if (!strcmp(key, "disk"))
[70b1e58]3695                        err = og_json_parse_string(value, &params->disk);
[fe0e6c4]3696                else if (!strcmp(key, "partition"))
[70b1e58]3697                        err = og_json_parse_string(value, &params->partition);
[22ab637]3698
3699                if (err < 0)
3700                        return err;
3701        }
3702
3703        for (i = 0; i < params->ips_array_len; i++) {
3704                snprintf(iph + strlen(iph), sizeof(iph), "%s;",
3705                         params->ips_array[i]);
3706        }
3707        len = snprintf(buf, sizeof(buf),
3708                       "nfn=IniciarSesion\riph=%s\rdsk=%s\rpar=%s\r",
3709                       iph, params->disk, params->partition);
3710
3711        msg = og_msg_alloc(buf, len);
3712        if (!msg)
3713                return -1;
3714
3715        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
3716                         CLIENTE_APAGADO, msg))
3717                err = -1;
3718
3719        og_msg_free(msg);
3720
3721        return 0;
3722}
3723
[b231a5a]3724static int og_cmd_poweroff(json_t *element, struct og_msg_params *params)
3725{
3726        const char *key;
3727        json_t *value;
3728        int err = 0;
3729
3730        if (json_typeof(element) != JSON_OBJECT)
3731                return -1;
3732
3733        json_object_foreach(element, key, value) {
3734                if (!strcmp(key, "clients"))
3735                        err = og_json_parse_clients(value, params);
3736
3737                if (err < 0)
3738                        break;
3739        }
3740
3741        return og_cmd_legacy_send(params, "Apagar", CLIENTE_OCUPADO);
3742}
3743
[b317d24]3744static int og_cmd_refresh(json_t *element, struct og_msg_params *params)
3745{
3746        const char *key;
3747        json_t *value;
3748        int err = 0;
3749
3750        if (json_typeof(element) != JSON_OBJECT)
3751                return -1;
3752
3753        json_object_foreach(element, key, value) {
3754                if (!strcmp(key, "clients"))
3755                        err = og_json_parse_clients(value, params);
3756
3757                if (err < 0)
3758                        break;
3759        }
3760
3761        return og_cmd_legacy_send(params, "Actualizar", CLIENTE_APAGADO);
3762}
3763
[68270b3]3764static int og_cmd_reboot(json_t *element, struct og_msg_params *params)
3765{
3766        const char *key;
3767        json_t *value;
3768        int err = 0;
3769
3770        if (json_typeof(element) != JSON_OBJECT)
3771                return -1;
3772
3773        json_object_foreach(element, key, value) {
3774                if (!strcmp(key, "clients"))
3775                        err = og_json_parse_clients(value, params);
3776
3777                if (err < 0)
3778                        break;
3779        }
3780
3781        return og_cmd_legacy_send(params, "Reiniciar", CLIENTE_OCUPADO);
3782}
3783
[5513435]3784static int og_cmd_stop(json_t *element, struct og_msg_params *params)
3785{
3786        const char *key;
3787        json_t *value;
3788        int err = 0;
3789
3790        if (json_typeof(element) != JSON_OBJECT)
3791                return -1;
3792
3793        json_object_foreach(element, key, value) {
3794                if (!strcmp(key, "clients"))
3795                        err = og_json_parse_clients(value, params);
3796
3797                if (err < 0)
3798                        break;
3799        }
3800
3801        return og_cmd_legacy_send(params, "Purgar", CLIENTE_APAGADO);
3802}
3803
[1316c877]3804static int og_cmd_hardware(json_t *element, struct og_msg_params *params)
3805{
3806        const char *key;
3807        json_t *value;
3808        int err = 0;
3809
3810        if (json_typeof(element) != JSON_OBJECT)
3811                return -1;
3812
3813        json_object_foreach(element, key, value) {
3814                if (!strcmp(key, "clients"))
3815                        err = og_json_parse_clients(value, params);
3816
3817                if (err < 0)
3818                        break;
3819        }
3820
3821        return og_cmd_legacy_send(params, "InventarioHardware",
3822                                  CLIENTE_OCUPADO);
3823}
3824
[a0f41fc]3825static int og_cmd_software(json_t *element, struct og_msg_params *params)
3826{
3827        const char *key;
3828        json_t *value;
3829        int err = 0;
3830
3831        if (json_typeof(element) != JSON_OBJECT)
3832                return -1;
3833
3834        json_object_foreach(element, key, value) {
3835                if (!strcmp(key, "clients"))
3836                        err = og_json_parse_clients(value, params);
3837
3838                if (err < 0)
3839                        break;
3840        }
3841
3842        return og_cmd_legacy_send(params, "InventarioSoftware",
3843                                  CLIENTE_OCUPADO);
3844}
3845
[7f2dd15]3846static int og_cmd_create_image(json_t *element, struct og_msg_params *params)
3847{
3848        char buf[4096] = {};
3849        int err = 0, len;
3850        const char *key;
3851        json_t *value;
3852        TRAMA *msg;
3853
3854        if (json_typeof(element) != JSON_OBJECT)
3855                return -1;
3856
3857        json_object_foreach(element, key, value) {
3858                if (!strcmp(key, "disk"))
[70b1e58]3859                        err = og_json_parse_string(value, &params->disk);
[7f2dd15]3860                else if (!strcmp(key, "partition"))
[70b1e58]3861                        err = og_json_parse_string(value, &params->partition);
[7f2dd15]3862                else if (!strcmp(key, "name"))
[70b1e58]3863                        err = og_json_parse_string(value, &params->name);
[7f2dd15]3864                else if (!strcmp(key, "repository"))
[70b1e58]3865                        err = og_json_parse_string(value, &params->repository);
[7f2dd15]3866                else if (!strcmp(key, "clients"))
3867                        err = og_json_parse_clients(value, params);
3868                else if (!strcmp(key, "id"))
[70b1e58]3869                        err = og_json_parse_string(value, &params->id);
[7f2dd15]3870                else if (!strcmp(key, "code"))
[70b1e58]3871                        err = og_json_parse_string(value, &params->code);
[7f2dd15]3872
3873                if (err < 0)
3874                        break;
3875        }
3876
3877        len = snprintf(buf, sizeof(buf),
3878                        "nfn=CrearImagen\rdsk=%s\rpar=%s\rcpt=%s\ridi=%s\rnci=%s\ripr=%s\r",
3879                        params->disk, params->partition, params->code,
3880                        params->id, params->name, params->repository);
3881
3882        msg = og_msg_alloc(buf, len);
3883        if (!msg)
3884                return -1;
3885
3886        og_send_cmd((char **)params->ips_array, params->ips_array_len,
3887                    CLIENTE_OCUPADO, msg);
3888
3889        og_msg_free(msg);
3890
3891        return 0;
3892}
3893
[fc15dd1]3894static int og_cmd_restore_image(json_t *element, struct og_msg_params *params)
3895{
3896        char buf[4096] = {};
3897        int err = 0, len;
3898        const char *key;
3899        json_t *value;
3900        TRAMA *msg;
3901
3902        if (json_typeof(element) != JSON_OBJECT)
3903                return -1;
3904
3905        json_object_foreach(element, key, value) {
3906                if (!strcmp(key, "disk"))
3907                        err = og_json_parse_string(value, &params->disk);
3908                else if (!strcmp(key, "partition"))
3909                        err = og_json_parse_string(value, &params->partition);
3910                else if (!strcmp(key, "name"))
3911                        err = og_json_parse_string(value, &params->name);
3912                else if (!strcmp(key, "repository"))
3913                        err = og_json_parse_string(value, &params->repository);
3914                else if (!strcmp(key, "clients"))
3915                        err = og_json_parse_clients(value, params);
3916                else if (!strcmp(key, "type"))
3917                        err = og_json_parse_string(value, &params->type);
3918                else if (!strcmp(key, "profile"))
3919                        err = og_json_parse_string(value, &params->profile);
3920                else if (!strcmp(key, "id"))
3921                        err = og_json_parse_string(value, &params->id);
3922
3923                if (err < 0)
3924                        break;
3925        }
3926
3927        len = snprintf(buf, sizeof(buf),
3928                       "nfn=RestaurarImagen\ridi=%s\rdsk=%s\rpar=%s\rifs=%s\r"
3929                       "nci=%s\ripr=%s\rptc=%s\r",
3930                       params->id, params->disk, params->partition,
3931                       params->profile, params->name,
3932                       params->repository, params->type);
3933
3934        msg = og_msg_alloc(buf, len);
3935        if (!msg)
3936                return -1;
3937
3938        og_send_cmd((char **)params->ips_array, params->ips_array_len,
3939                    CLIENTE_OCUPADO, msg);
3940
3941        og_msg_free(msg);
3942
3943        return 0;
3944}
3945
[2385710e]3946static int og_cmd_setup_image(json_t *element, struct og_msg_params *params)
3947{
3948        char buf[4096] = {};
3949        int err = 0, len;
3950        const char *key;
3951        json_t *value;
3952        TRAMA *msg;
3953
3954        if (json_typeof(element) != JSON_OBJECT)
3955                return -1;
3956
3957        json_object_foreach(element, key, value) {
3958                if (!strcmp(key, "clients"))
3959                        err = og_json_parse_clients(value, params);
3960                else if (!strcmp(key, "disk"))
3961                        err = og_json_parse_string(value, &params->disk);
3962                else if (!strcmp(key, "cache"))
3963                        err = og_json_parse_string(value, &params->cache);
3964                else if (!strcmp(key, "cache_size"))
3965                        err = og_json_parse_string(value, &params->cache_size);
3966                else if (!strcmp(key, "partition_setup"))
3967                        err = og_json_parse_partition_setup(value, params->partition_setup);
3968
3969                if (err < 0)
3970                        break;
3971        }
3972
3973        len = snprintf(buf, sizeof(buf),
3974                        "nfn=Configurar\rdsk=%s\rcfg=dis=%s*che=%s*tch=%s!",
3975                        params->disk, params->disk, params->cache, params->cache_size);
3976
3977        for (unsigned int i = 0; i < OG_PARTITION_MAX; ++i) {
3978                const og_partition *part = params->partition_setup + i;
3979
3980                len += snprintf(buf + strlen(buf), sizeof(buf),
3981                        "par=%s*cpt=%s*sfi=%s*tam=%s*ope=%s%%",
3982                        part->number, part->code, part->filesystem, part->size, part->format);
3983        }
3984
3985        msg = og_msg_alloc(buf, len + 1);
3986        if (!msg)
3987                return -1;
3988
3989        og_send_cmd((char **)params->ips_array, params->ips_array_len,
3990                        CLIENTE_OCUPADO, msg);
3991
3992        og_msg_free(msg);
3993
3994        return 0;
3995}
3996
[e804134]3997static int og_client_method_not_found(struct og_client *cli)
3998{
3999        /* To meet RFC 7231, this function MUST generate an Allow header field
4000         * containing the correct methods. For example: "Allow: POST\r\n"
4001         */
4002        char buf[] = "HTTP/1.1 405 Method Not Allowed\r\n"
4003                     "Content-Length: 0\r\n\r\n";
4004
4005        send(og_client_socket(cli), buf, strlen(buf), 0);
4006
4007        return -1;
4008}
4009
[391f9be]4010static int og_client_bad_request(struct og_client *cli)
4011{
4012        char buf[] = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
4013
4014        send(og_client_socket(cli), buf, strlen(buf), 0);
4015
4016        return -1;
4017}
4018
[1a08c06]4019static int og_client_not_found(struct og_client *cli)
4020{
4021        char buf[] = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
4022
4023        send(og_client_socket(cli), buf, strlen(buf), 0);
4024
4025        return -1;
4026}
4027
[2ccec278]4028static int og_client_not_authorized(struct og_client *cli)
4029{
[f06fcf6f]4030        char buf[] = "HTTP/1.1 401 Unauthorized\r\n"
4031                     "WWW-Authenticate: Basic\r\n"
4032                     "Content-Length: 0\r\n\r\n";
[2ccec278]4033
4034        send(og_client_socket(cli), buf, strlen(buf), 0);
4035
4036        return -1;
4037}
4038
[d6852fb]4039static int og_server_internal_error(struct og_client *cli)
4040{
4041        char buf[] = "HTTP/1.1 500 Internal Server Error\r\n"
4042                     "Content-Length: 0\r\n\r\n";
4043
4044        send(og_client_socket(cli), buf, strlen(buf), 0);
4045
4046        return -1;
4047}
4048
[611f470]4049#define OG_MSG_RESPONSE_MAXLEN  65536
4050
[ea03692]4051static int og_client_ok(struct og_client *cli, char *buf_reply)
[1a08c06]4052{
[611f470]4053        char buf[OG_MSG_RESPONSE_MAXLEN] = {};
[5bbcedc]4054        int err = 0, len;
[ea03692]4055
[5bbcedc]4056        len = snprintf(buf, sizeof(buf),
4057                       "HTTP/1.1 200 OK\r\nContent-Length: %ld\r\n\r\n%s",
4058                       strlen(buf_reply), buf_reply);
[d6852fb]4059        if (len >= (int)sizeof(buf))
4060                err = og_server_internal_error(cli);
[1a08c06]4061
4062        send(og_client_socket(cli), buf, strlen(buf), 0);
4063
[5bbcedc]4064        return err;
[1a08c06]4065}
4066
4067enum og_rest_method {
4068        OG_METHOD_GET   = 0,
4069        OG_METHOD_POST,
4070};
4071
4072static int og_client_state_process_payload_rest(struct og_client *cli)
4073{
[611f470]4074        char buf_reply[OG_MSG_RESPONSE_MAXLEN] = {};
[1a08c06]4075        struct og_msg_params params = {};
4076        enum og_rest_method method;
[b3467f7]4077        const char *cmd, *body;
[1a08c06]4078        json_error_t json_err;
4079        json_t *root = NULL;
4080        int err = 0;
4081
[2cced2b3]4082        syslog(LOG_DEBUG, "%s:%hu %.32s ...\n",
4083               inet_ntoa(cli->addr.sin_addr),
4084               ntohs(cli->addr.sin_port), cli->buf);
4085
[1a08c06]4086        if (!strncmp(cli->buf, "GET", strlen("GET"))) {
4087                method = OG_METHOD_GET;
4088                cmd = cli->buf + strlen("GET") + 2;
4089        } else if (!strncmp(cli->buf, "POST", strlen("POST"))) {
4090                method = OG_METHOD_POST;
4091                cmd = cli->buf + strlen("POST") + 2;
4092        } else
[e804134]4093                return og_client_method_not_found(cli);
[1a08c06]4094
4095        body = strstr(cli->buf, "\r\n\r\n") + 4;
4096
[2ccec278]4097        if (strcmp(cli->auth_token, auth_token)) {
4098                syslog(LOG_ERR, "wrong Authentication key\n");
4099                return og_client_not_authorized(cli);
4100        }
4101
[b3467f7]4102        if (cli->content_length) {
[1a08c06]4103                root = json_loads(body, 0, &json_err);
4104                if (!root) {
4105                        syslog(LOG_ERR, "malformed json line %d: %s\n",
4106                               json_err.line, json_err.text);
4107                        return og_client_not_found(cli);
4108                }
4109        }
4110
4111        if (!strncmp(cmd, "clients", strlen("clients"))) {
[ea03692]4112                if (method != OG_METHOD_POST &&
4113                    method != OG_METHOD_GET)
[e804134]4114                        return og_client_method_not_found(cli);
[ea03692]4115
4116                if (method == OG_METHOD_POST && !root) {
[1a08c06]4117                        syslog(LOG_ERR, "command clients with no payload\n");
[391f9be]4118                        return og_client_bad_request(cli);
[1a08c06]4119                }
[ea03692]4120                switch (method) {
4121                case OG_METHOD_POST:
4122                        err = og_cmd_post_clients(root, &params);
4123                        break;
4124                case OG_METHOD_GET:
4125                        err = og_cmd_get_clients(root, &params, buf_reply);
4126                        break;
4127                }
[73c4bdff]4128        } else if (!strncmp(cmd, "wol", strlen("wol"))) {
4129                if (method != OG_METHOD_POST)
[e804134]4130                        return og_client_method_not_found(cli);
[73c4bdff]4131
4132                if (!root) {
4133                        syslog(LOG_ERR, "command wol with no payload\n");
[391f9be]4134                        return og_client_bad_request(cli);
[73c4bdff]4135                }
4136                err = og_cmd_wol(root, &params);
[775f6f0]4137        } else if (!strncmp(cmd, "shell/run", strlen("shell/run"))) {
4138                if (method != OG_METHOD_POST)
[e804134]4139                        return og_client_method_not_found(cli);
[775f6f0]4140
4141                if (!root) {
4142                        syslog(LOG_ERR, "command run with no payload\n");
[391f9be]4143                        return og_client_bad_request(cli);
[775f6f0]4144                }
4145                err = og_cmd_run_post(root, &params);
[165cea3]4146        } else if (!strncmp(cmd, "shell/output", strlen("shell/output"))) {
4147                if (method != OG_METHOD_POST)
[e804134]4148                        return og_client_method_not_found(cli);
[165cea3]4149
4150                if (!root) {
4151                        syslog(LOG_ERR, "command output with no payload\n");
[391f9be]4152                        return og_client_bad_request(cli);
[165cea3]4153                }
4154
4155                err = og_cmd_run_get(root, &params, buf_reply);
[22ab637]4156        } else if (!strncmp(cmd, "session", strlen("session"))) {
4157                if (method != OG_METHOD_POST)
[e804134]4158                        return og_client_method_not_found(cli);
[22ab637]4159
4160                if (!root) {
4161                        syslog(LOG_ERR, "command session with no payload\n");
[391f9be]4162                        return og_client_bad_request(cli);
[22ab637]4163                }
4164                err = og_cmd_session(root, &params);
[b231a5a]4165        } else if (!strncmp(cmd, "poweroff", strlen("poweroff"))) {
4166                if (method != OG_METHOD_POST)
[e804134]4167                        return og_client_method_not_found(cli);
[b231a5a]4168
4169                if (!root) {
4170                        syslog(LOG_ERR, "command poweroff with no payload\n");
[391f9be]4171                        return og_client_bad_request(cli);
[b231a5a]4172                }
4173                err = og_cmd_poweroff(root, &params);
[68270b3]4174        } else if (!strncmp(cmd, "reboot", strlen("reboot"))) {
4175                if (method != OG_METHOD_POST)
[e804134]4176                        return og_client_method_not_found(cli);
[68270b3]4177
4178                if (!root) {
4179                        syslog(LOG_ERR, "command reboot with no payload\n");
[391f9be]4180                        return og_client_bad_request(cli);
[68270b3]4181                }
4182                err = og_cmd_reboot(root, &params);
[5513435]4183        } else if (!strncmp(cmd, "stop", strlen("stop"))) {
4184                if (method != OG_METHOD_POST)
[e804134]4185                        return og_client_method_not_found(cli);
[5513435]4186
4187                if (!root) {
4188                        syslog(LOG_ERR, "command stop with no payload\n");
[391f9be]4189                        return og_client_bad_request(cli);
[5513435]4190                }
4191                err = og_cmd_stop(root, &params);
[b317d24]4192        } else if (!strncmp(cmd, "refresh", strlen("refresh"))) {
4193                if (method != OG_METHOD_POST)
[e804134]4194                        return og_client_method_not_found(cli);
[b317d24]4195
4196                if (!root) {
4197                        syslog(LOG_ERR, "command refresh with no payload\n");
[391f9be]4198                        return og_client_bad_request(cli);
[b317d24]4199                }
4200                err = og_cmd_refresh(root, &params);
[1316c877]4201        } else if (!strncmp(cmd, "hardware", strlen("hardware"))) {
4202                if (method != OG_METHOD_POST)
[e804134]4203                        return og_client_method_not_found(cli);
[1316c877]4204
4205                if (!root) {
4206                        syslog(LOG_ERR, "command hardware with no payload\n");
[391f9be]4207                        return og_client_bad_request(cli);
[1316c877]4208                }
4209                err = og_cmd_hardware(root, &params);
[a0f41fc]4210        } else if (!strncmp(cmd, "software", strlen("software"))) {
4211                if (method != OG_METHOD_POST)
[e804134]4212                        return og_client_method_not_found(cli);
[a0f41fc]4213
4214                if (!root) {
4215                        syslog(LOG_ERR, "command software with no payload\n");
[391f9be]4216                        return og_client_bad_request(cli);
[a0f41fc]4217                }
4218                err = og_cmd_software(root, &params);
[7f2dd15]4219        } else if (!strncmp(cmd, "image/create", strlen("image/create"))) {
4220                if (method != OG_METHOD_POST)
4221                        return og_client_method_not_found(cli);
4222
4223                if (!root) {
4224                        syslog(LOG_ERR, "command create with no payload\n");
4225                        return og_client_bad_request(cli);
4226                }
4227                err = og_cmd_create_image(root, &params);
[fc15dd1]4228        } else if (!strncmp(cmd, "image/restore", strlen("image/restore"))) {
4229                if (method != OG_METHOD_POST)
4230                        return og_client_method_not_found(cli);
4231
4232                if (!root) {
4233                        syslog(LOG_ERR, "command create with no payload\n");
4234                        return og_client_bad_request(cli);
4235                }
4236                err = og_cmd_restore_image(root, &params);
[2385710e]4237        } else if (!strncmp(cmd, "image/setup", strlen("image/setup"))) {
4238                if (method != OG_METHOD_POST)
4239                        return og_client_method_not_found(cli);
4240
4241                if (!root) {
4242                        syslog(LOG_ERR, "command create with no payload\n");
4243                        return og_client_bad_request(cli);
4244                }
4245                err = og_cmd_setup_image(root, &params);
[1a08c06]4246        } else {
[ca239ad]4247                syslog(LOG_ERR, "unknown command: %.32s ...\n", cmd);
[1a08c06]4248                err = og_client_not_found(cli);
4249        }
4250
[ea03692]4251        if (root)
4252                json_decref(root);
[1a08c06]4253
[0c1ff40]4254        if (err < 0)
4255                return err;
4256
4257        err = og_client_ok(cli, buf_reply);
4258        if (err < 0) {
4259                syslog(LOG_ERR, "HTTP response to %s:%hu is too large\n",
4260                       inet_ntoa(cli->addr.sin_addr),
4261                       ntohs(cli->addr.sin_port));
4262        }
[1a08c06]4263
4264        return err;
4265}
4266
4267static int og_client_state_recv_hdr_rest(struct og_client *cli)
4268{
[b3467f7]4269        char *ptr;
[1a08c06]4270
[b3467f7]4271        ptr = strstr(cli->buf, "\r\n\r\n");
4272        if (!ptr)
[1a08c06]4273                return 0;
4274
[b3467f7]4275        cli->msg_len = ptr - cli->buf + 4;
4276
4277        ptr = strstr(cli->buf, "Content-Length: ");
4278        if (ptr) {
4279                sscanf(ptr, "Content-Length: %i[^\r\n]", &cli->content_length);
[8793b71]4280                if (cli->content_length < 0)
4281                        return -1;
[b3467f7]4282                cli->msg_len += cli->content_length;
4283        }
4284
[2ccec278]4285        ptr = strstr(cli->buf, "Authorization: ");
4286        if (ptr)
[ba5651bc]4287                sscanf(ptr, "Authorization: %63[^\r\n]", cli->auth_token);
[2ccec278]4288
[1a08c06]4289        return 1;
4290}
4291
[07c51e2]4292static void og_client_read_cb(struct ev_loop *loop, struct ev_io *io, int events)
4293{
4294        struct og_client *cli;
4295        int ret;
[9baecf8]4296
4297        cli = container_of(io, struct og_client, io);
4298
[2e0c063]4299        if (events & EV_ERROR) {
4300                syslog(LOG_ERR, "unexpected error event from client %s:%hu\n",
4301                               inet_ntoa(cli->addr.sin_addr),
4302                               ntohs(cli->addr.sin_port));
4303                goto close;
4304        }
4305
[9baecf8]4306        ret = recv(io->fd, cli->buf + cli->buf_len,
4307                   sizeof(cli->buf) - cli->buf_len, 0);
[2e0c063]4308        if (ret <= 0) {
4309                if (ret < 0) {
4310                        syslog(LOG_ERR, "error reading from client %s:%hu (%s)\n",
4311                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
4312                               strerror(errno));
4313                } else {
[0e16db2]4314                        syslog(LOG_DEBUG, "closed connection by %s:%hu\n",
[2e0c063]4315                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4316                }
[9baecf8]4317                goto close;
[2e0c063]4318        }
4319
4320        if (cli->keepalive_idx >= 0)
4321                return;
[9baecf8]4322
4323        ev_timer_again(loop, &cli->timer);
4324
4325        cli->buf_len += ret;
[d8a2d5f]4326        if (cli->buf_len >= sizeof(cli->buf)) {
4327                syslog(LOG_ERR, "client request from %s:%hu is too long\n",
4328                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4329                goto close;
4330        }
[9baecf8]4331
4332        switch (cli->state) {
4333        case OG_CLIENT_RECEIVING_HEADER:
[1a08c06]4334                if (cli->rest)
4335                        ret = og_client_state_recv_hdr_rest(cli);
4336                else
4337                        ret = og_client_state_recv_hdr(cli);
4338
[39c3261]4339                if (ret < 0)
[9baecf8]4340                        goto close;
[39c3261]4341                if (!ret)
4342                        return;
[9baecf8]4343
4344                cli->state = OG_CLIENT_RECEIVING_PAYLOAD;
4345                /* Fall through. */
4346        case OG_CLIENT_RECEIVING_PAYLOAD:
4347                /* Still not enough data to process request. */
4348                if (cli->buf_len < cli->msg_len)
4349                        return;
4350
4351                cli->state = OG_CLIENT_PROCESSING_REQUEST;
4352                /* fall through. */
4353        case OG_CLIENT_PROCESSING_REQUEST:
[0c1ff40]4354                if (cli->rest) {
[1a08c06]4355                        ret = og_client_state_process_payload_rest(cli);
[0c1ff40]4356                        if (ret < 0) {
4357                                syslog(LOG_ERR, "Failed to process HTTP request from %s:%hu\n",
4358                                       inet_ntoa(cli->addr.sin_addr),
4359                                       ntohs(cli->addr.sin_port));
4360                        }
4361                } else {
[1a08c06]4362                        ret = og_client_state_process_payload(cli);
[0c1ff40]4363                }
[07c51e2]4364                if (ret < 0)
[9baecf8]4365                        goto close;
4366
[2e0c063]4367                if (cli->keepalive_idx < 0) {
[0e16db2]4368                        syslog(LOG_DEBUG, "server closing connection to %s:%hu\n",
[2e0c063]4369                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
[9baecf8]4370                        goto close;
[2e0c063]4371                } else {
[0e16db2]4372                        syslog(LOG_DEBUG, "leaving client %s:%hu in keepalive mode\n",
[2e0c063]4373                               inet_ntoa(cli->addr.sin_addr),
4374                               ntohs(cli->addr.sin_port));
4375                        og_client_keepalive(loop, cli);
4376                        og_client_reset_state(cli);
4377                }
[9baecf8]4378                break;
[13e48b4]4379        default:
4380                syslog(LOG_ERR, "unknown state, critical internal error\n");
4381                goto close;
[f997cc1]4382        }
[9baecf8]4383        return;
4384close:
4385        ev_timer_stop(loop, &cli->timer);
[2e0c063]4386        og_client_release(loop, cli);
[f997cc1]4387}
4388
[9baecf8]4389static void og_client_timer_cb(struct ev_loop *loop, ev_timer *timer, int events)
4390{
4391        struct og_client *cli;
4392
4393        cli = container_of(timer, struct og_client, timer);
[2e0c063]4394        if (cli->keepalive_idx >= 0) {
[9baecf8]4395                ev_timer_again(loop, &cli->timer);
4396                return;
4397        }
[2e0c063]4398        syslog(LOG_ERR, "timeout request for client %s:%hu\n",
4399               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
[13e48b4]4400
[2e0c063]4401        og_client_release(loop, cli);
[9baecf8]4402}
4403
[1a08c06]4404static int socket_s, socket_rest;
4405
[9baecf8]4406static void og_server_accept_cb(struct ev_loop *loop, struct ev_io *io,
4407                                int events)
4408{
4409        struct sockaddr_in client_addr;
4410        socklen_t addrlen = sizeof(client_addr);
4411        struct og_client *cli;
4412        int client_sd;
4413
4414        if (events & EV_ERROR)
4415                return;
4416
4417        client_sd = accept(io->fd, (struct sockaddr *)&client_addr, &addrlen);
4418        if (client_sd < 0) {
[8c04716]4419                syslog(LOG_ERR, "cannot accept client connection\n");
[9baecf8]4420                return;
4421        }
4422
4423        cli = (struct og_client *)calloc(1, sizeof(struct og_client));
4424        if (!cli) {
4425                close(client_sd);
4426                return;
4427        }
[13e48b4]4428        memcpy(&cli->addr, &client_addr, sizeof(client_addr));
[2e0c063]4429        cli->keepalive_idx = -1;
[13e48b4]4430
[1a08c06]4431        if (io->fd == socket_rest)
4432                cli->rest = true;
4433
[0e16db2]4434        syslog(LOG_DEBUG, "connection from client %s:%hu\n",
[2e0c063]4435               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
[9baecf8]4436
4437        ev_io_init(&cli->io, og_client_read_cb, client_sd, EV_READ);
4438        ev_io_start(loop, &cli->io);
4439        ev_timer_init(&cli->timer, og_client_timer_cb, OG_CLIENT_TIMEOUT, 0.);
4440        ev_timer_start(loop, &cli->timer);
4441}
4442
[588052e]4443static int og_socket_server_init(const char *port)
4444{
4445        struct sockaddr_in local;
4446        int sd, on = 1;
4447
4448        sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
4449        if (sd < 0) {
4450                syslog(LOG_ERR, "cannot create main socket\n");
4451                return -1;
4452        }
4453        setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(int));
4454
4455        local.sin_addr.s_addr = htonl(INADDR_ANY);
4456        local.sin_family = AF_INET;
4457        local.sin_port = htons(atoi(port));
4458
4459        if (bind(sd, (struct sockaddr *) &local, sizeof(local)) < 0) {
[438afb2]4460                close(sd);
[588052e]4461                syslog(LOG_ERR, "cannot bind socket\n");
4462                return -1;
4463        }
4464
4465        listen(sd, 250);
4466
4467        return sd;
4468}
4469
[9baecf8]4470int main(int argc, char *argv[])
4471{
[1a08c06]4472        struct ev_io ev_io_server, ev_io_server_rest;
[9baecf8]4473        struct ev_loop *loop = ev_default_loop(0);
4474        int i;
[3ec149c]4475
[4797e93]4476        if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4477                exit(EXIT_FAILURE);
4478
[b11b753]4479        openlog("ogAdmServer", LOG_PID, LOG_DAEMON);
[13e48b4]4480
[3ec149c]4481        /*--------------------------------------------------------------------------------------------------------
4482         Validación de parámetros de ejecución y lectura del fichero de configuración del servicio
4483         ---------------------------------------------------------------------------------------------------------*/
4484        if (!validacionParametros(argc, argv, 1)) // Valida parámetros de ejecución
4485                exit(EXIT_FAILURE);
4486
4487        if (!tomaConfiguracion(szPathFileCfg)) { // Toma parametros de configuracion
4488                exit(EXIT_FAILURE);
4489        }
4490
4491        /*--------------------------------------------------------------------------------------------------------
4492         // Inicializa array de información de los clientes
4493         ---------------------------------------------------------------------------------------------------------*/
4494        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
4495                tbsockets[i].ip[0] = '\0';
[2e0c063]4496                tbsockets[i].cli = NULL;
[3ec149c]4497        }
4498        /*--------------------------------------------------------------------------------------------------------
4499         Creación y configuración del socket del servicio
4500         ---------------------------------------------------------------------------------------------------------*/
[588052e]4501        socket_s = og_socket_server_init(puerto);
4502        if (socket_s < 0)
[3ec149c]4503                exit(EXIT_FAILURE);
[9baecf8]4504
4505        ev_io_init(&ev_io_server, og_server_accept_cb, socket_s, EV_READ);
4506        ev_io_start(loop, &ev_io_server);
4507
[1a08c06]4508        socket_rest = og_socket_server_init("8888");
4509        if (socket_rest < 0)
4510                exit(EXIT_FAILURE);
4511
4512        ev_io_init(&ev_io_server_rest, og_server_accept_cb, socket_rest, EV_READ);
4513        ev_io_start(loop, &ev_io_server_rest);
4514
[3ec149c]4515        infoLog(1); // Inicio de sesión
[9baecf8]4516
[256fbf2]4517        /* old log file has been deprecated. */
4518        og_log(97, false);
4519
[13e48b4]4520        syslog(LOG_INFO, "Waiting for connections\n");
4521
[9baecf8]4522        while (1)
4523                ev_loop(loop, 0);
4524
[3ec149c]4525        exit(EXIT_SUCCESS);
4526}
Note: See TracBrowser for help on using the repository browser.