source: ogServer-Git/sources/ogAdmServer.cpp @ 45f414e

Last change on this file since 45f414e was 43c7da8, checked in by OpenGnSys Support Team <soporte-og@…>, 5 years ago

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

This patch implements the command "image/create/incremental".

Request:

{"clients":192.168.56.11?,

"disk":"1",
"partition":"1",
"id":"3",
"name":"basica1",
"repository":"192.168.56.10",
"sync_params":{"sync":"1",

"path":"",
"diff":"0",
"diff_id":"4",
"diff_name":"p2",
"remove":"1",
"compress":"0",
"cleanup":"0",
"cache":"0",
"cleanup_cache":"0",
"remove_dst":"0"
}

}

Reply:

200 OK

  • Property mode set to 100644
File size: 144.8 KB
Line 
1// *******************************************************************************************************
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
8// *******************************************************************************************************
9#include "ogAdmServer.h"
10#include "ogAdmLib.c"
11#include <ev.h>
12#include <syslog.h>
13#include <sys/ioctl.h>
14#include <ifaddrs.h>
15#include <sys/types.h>
16#include <sys/stat.h>
17#include <fcntl.h>
18#include <jansson.h>
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
24static char interface[LONPRM]; // Interface name
25static char auth_token[LONPRM]; // API token
26
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:
35//              true: Si el proceso es correcto
36//              false: En caso de ocurrir algún error
37//________________________________________________________________________________________________________
38static bool tomaConfiguracion(const char *filecfg)
39{
40        char buf[1024], *line;
41        char *key, *value;
42        FILE *fcfg;
43
44        if (filecfg == NULL || strlen(filecfg) == 0) {
45                syslog(LOG_ERR, "No configuration file has been specified\n");
46                return false;
47        }
48
49        fcfg = fopen(filecfg, "rt");
50        if (fcfg == NULL) {
51                syslog(LOG_ERR, "Cannot open configuration file `%s'\n",
52                       filecfg);
53                return false;
54        }
55
56        servidoradm[0] = (char) NULL; //inicializar variables globales
57
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);
79                else if (!strcmp(StrToUpper(key), "INTERFACE"))
80                        snprintf(interface, sizeof(interface), "%s", value);
81                else if (!strcmp(StrToUpper(key), "APITOKEN"))
82                        snprintf(auth_token, sizeof(auth_token), "%s", value);
83
84                line = fgets(buf, sizeof(buf), fcfg);
85        }
86
87        fclose(fcfg);
88
89        if (!servidoradm[0]) {
90                syslog(LOG_ERR, "Missing SERVIDORADM in configuration file\n");
91                return false;
92        }
93        if (!puerto[0]) {
94                syslog(LOG_ERR, "Missing PUERTO in configuration file\n");
95                return false;
96        }
97        if (!usuario[0]) {
98                syslog(LOG_ERR, "Missing USUARIO in configuration file\n");
99                return false;
100        }
101        if (!pasguor[0]) {
102                syslog(LOG_ERR, "Missing PASSWORD in configuration file\n");
103                return false;
104        }
105        if (!datasource[0]) {
106                syslog(LOG_ERR, "Missing DATASOURCE in configuration file\n");
107                return false;
108        }
109        if (!catalog[0]) {
110                syslog(LOG_ERR, "Missing CATALOG in configuration file\n");
111                return false;
112        }
113        if (!interface[0])
114                syslog(LOG_ERR, "Missing INTERFACE in configuration file\n");
115
116        return true;
117}
118
119enum og_client_state {
120        OG_CLIENT_RECEIVING_HEADER      = 0,
121        OG_CLIENT_RECEIVING_PAYLOAD,
122        OG_CLIENT_PROCESSING_REQUEST,
123};
124
125#define OG_MSG_REQUEST_MAXLEN   4096
126
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;
133        struct sockaddr_in      addr;
134        enum og_client_state    state;
135        char                    buf[OG_MSG_REQUEST_MAXLEN];
136        unsigned int            buf_len;
137        unsigned int            msg_len;
138        int                     keepalive_idx;
139        bool                    rest;
140        int                     content_length;
141        char                    auth_token[64];
142};
143
144static inline int og_client_socket(const struct og_client *cli)
145{
146        return cli->io.fd;
147}
148
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:
158//              true: Si el cliente está disponible
159//              false: En caso contrario
160// ________________________________________________________________________________________________________
161bool clienteDisponible(char *ip, int* idx)
162{
163        int estado;
164
165        if (clienteExistente(ip, idx)) {
166                estado = strcmp(tbsockets[*idx].estado, CLIENTE_OCUPADO); // Cliente ocupado
167                if (estado == 0)
168                        return false;
169
170                estado = strcmp(tbsockets[*idx].estado, CLIENTE_APAGADO); // Cliente apagado
171                if (estado == 0)
172                        return false;
173
174                estado = strcmp(tbsockets[*idx].estado, CLIENTE_INICIANDO); // Cliente en proceso de inclusión
175                if (estado == 0)
176                        return false;
177
178                return true; // En caso contrario el cliente está disponible
179        }
180        return false; // Cliente no está registrado en el sistema
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:
191//              true: Si el cliente está registrado
192//              false: En caso contrario
193// ________________________________________________________________________________________________________
194bool clienteExistente(char *ip, int* idx)
195{
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;
200                        return true;
201                }
202        }
203        return false;
204}
205// ________________________________________________________________________________________________________
206// Función: hayHueco
207//
208//      Descripción:
209//              Esta función devuelve true o false dependiendo de que haya hueco en la tabla de sockets para un nuevo cliente.
210//      Parametros:
211//              - idx:   Primer indice libre que se podrn utilizar
212//      Devuelve:
213//              true: Si el proceso es correcto
214//              false: En caso de ocurrir algún error
215// ________________________________________________________________________________________________________
216static bool hayHueco(int *idx)
217{
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;
223                        return true;
224                }
225        }
226        return false;
227}
228// ________________________________________________________________________________________________________
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:
237//              true: Si el proceso es correcto
238//              false: En caso de ocurrir algún error
239// ________________________________________________________________________________________________________
240static bool InclusionClienteWinLnx(TRAMA *ptrTrama, struct og_client *cli)
241{
242        int socket_c = og_client_socket(cli);
243        int res,idordenador,lon;
244        char nombreordenador[LONFIL];
245
246        res = procesoInclusionClienteWinLnx(socket_c, ptrTrama, &idordenador,
247                                            nombreordenador);
248
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);   
257
258        if (!mandaTrama(&socket_c, ptrTrama)) {
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));
262                return false;
263        }
264        return true;
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// ________________________________________________________________________________________________________
280bool procesoInclusionClienteWinLnx(int socket_c, TRAMA *ptrTrama, int *idordenador, char *nombreordenador)
281 {
282        char msglog[LONSTD], sqlstr[LONSQL];
283        Database db;
284        Table tbl;
285        char *iph;
286
287        // Toma parámetros
288        iph = copiaParametro("iph",ptrTrama); // Toma ip
289
290        if (!db.Open(usuario, pasguor, datasource, catalog)) {
291                liberaMemoria(iph);
292                db.GetErrorErrStr(msglog);
293                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
294                       __func__, __LINE__, msglog);
295                return false;
296        }
297
298        // Recupera los datos del cliente
299        sprintf(sqlstr,
300                        "SELECT idordenador,nombreordenador FROM ordenadores "
301                                " WHERE ordenadores.ip = '%s'", iph);
302
303        if (!db.Execute(sqlstr, tbl)) {
304                liberaMemoria(iph);
305                db.GetErrorErrStr(msglog);
306                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
307                       __func__, __LINE__, msglog);
308                db.Close();
309                return false;
310        }
311
312        if (tbl.ISEOF()) {
313                liberaMemoria(iph);
314                syslog(LOG_ERR, "client does not exist in database (%s:%d)\n",
315                       __func__, __LINE__);
316                db.liberaResult(tbl);
317                db.Close();
318                return false;
319        }
320
321        syslog(LOG_DEBUG, "Client %s requesting inclusion\n", iph);
322
323        if (!tbl.Get("idordenador", *idordenador)) {
324                liberaMemoria(iph);
325                db.liberaResult(tbl);
326                tbl.GetErrorErrStr(msglog);
327                og_info(msglog);
328                db.Close();
329                return false;
330        }
331        if (!tbl.Get("nombreordenador", nombreordenador)) {
332                liberaMemoria(iph);
333                db.liberaResult(tbl);
334                tbl.GetErrorErrStr(msglog);
335                og_info(msglog);
336                db.Close();
337                return false;
338        }
339        db.liberaResult(tbl);
340        db.Close();
341
342        if (!registraCliente(iph)) { // Incluyendo al cliente en la tabla de sokets
343                liberaMemoria(iph);
344                syslog(LOG_ERR, "client table is full\n");
345                return false;
346        }
347        liberaMemoria(iph);
348        return true;
349}
350// ________________________________________________________________________________________________________
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:
360//              true: Si el proceso es correcto
361//              false: En caso de ocurrir algún error
362// ________________________________________________________________________________________________________
363static bool InclusionCliente(TRAMA *ptrTrama, struct og_client *cli)
364{
365        int socket_c = og_client_socket(cli);
366
367        if (!procesoInclusionCliente(cli, ptrTrama)) {
368                initParametros(ptrTrama,0);
369                strcpy(ptrTrama->parametros, "nfn=RESPUESTA_InclusionCliente\rres=0\r");
370                if (!mandaTrama(&socket_c, ptrTrama)) {
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));
374                        return false;
375                }
376        }
377        return true;
378}
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:
388//              true: Si el proceso es correcto
389//              false: En caso de ocurrir algún error
390// ________________________________________________________________________________________________________
391bool procesoInclusionCliente(struct og_client *cli, TRAMA *ptrTrama)
392{
393        int socket_c = og_client_socket(cli);
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
406        if (!db.Open(usuario, pasguor, datasource, catalog)) {
407                liberaMemoria(iph);
408                liberaMemoria(cfg);
409                db.GetErrorErrStr(msglog);
410                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
411                       __func__, __LINE__, msglog);
412                return false;
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
422        if (!db.Execute(sqlstr, tbl)) {
423                db.GetErrorErrStr(msglog);
424                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
425                       __func__, __LINE__, msglog);
426                return false;
427        }
428
429        if (tbl.ISEOF()) {
430                syslog(LOG_ERR, "client does not exist in database (%s:%d)\n",
431                       __func__, __LINE__);
432                return false;
433        }
434
435        syslog(LOG_DEBUG, "Client %s requesting inclusion\n", iph);
436
437        if (!tbl.Get("idordenador", idordenador)) {
438                tbl.GetErrorErrStr(msglog);
439                og_info(msglog);
440                return false;
441        }
442        if (!tbl.Get("nombreordenador", nombreordenador)) {
443                tbl.GetErrorErrStr(msglog);
444                og_info(msglog);
445                return false;
446        }
447        if (!tbl.Get("idmenu", idmenu)) {
448                tbl.GetErrorErrStr(msglog);
449                og_info(msglog);
450                return false;
451        }
452        if (!tbl.Get("cache", cache)) {
453                tbl.GetErrorErrStr(msglog);
454                og_info(msglog);
455                return false;
456        }
457        if (!tbl.Get("idproautoexec", idproautoexec)) {
458                tbl.GetErrorErrStr(msglog);
459                og_info(msglog);
460                return false;
461        }
462        if (!tbl.Get("idaula", idaula)) {
463                tbl.GetErrorErrStr(msglog);
464                og_info(msglog);
465                return false;
466        }
467        if (!tbl.Get("idcentro", idcentro)) {
468                tbl.GetErrorErrStr(msglog);
469                og_info(msglog);
470                return false;
471        }
472
473        resul = actualizaConfiguracion(db, tbl, cfg, idordenador); // Actualiza la configuración del ordenador
474        liberaMemoria(cfg);
475        db.Close();
476
477        if (!resul) {
478                liberaMemoria(iph);
479                syslog(LOG_ERR, "Cannot add client to database\n");
480                return false;
481        }
482
483        if (!registraCliente(iph)) { // Incluyendo al cliente en la tabla de sokets
484                liberaMemoria(iph);
485                syslog(LOG_ERR, "client table is full\n");
486                return false;
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
503        if (!mandaTrama(&socket_c, ptrTrama)) {
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));
507                return false;
508        }
509        liberaMemoria(iph);
510        return true;
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:
523//              true: Si el proceso es correcto
524//              false: En caso de ocurrir algún error
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// ________________________________________________________________________________________________________
533bool actualizaConfiguracion(Database db, Table tbl, char *cfg, int ido)
534{
535        char msglog[LONSTD], sqlstr[LONSQL];
536        int lon, p, c,i, dato, swu, idsoi, idsfi,k;
537        char *ptrPar[MAXPAR], *ptrCfg[7], *ptrDual[2], tbPar[LONSTD];
538        char *ser, *disk, *par, *cpt, *sfi, *soi, *tam, *uso; // Parametros de configuración.
539
540        lon = 0;
541        p = splitCadena(ptrPar, cfg, '\n');
542        for (i = 0; i < p; i++) {
543                c = splitCadena(ptrCfg, ptrPar[i], '\t');
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'"
552                                                " WHERE idordenador=%d AND numserie IS NULL",
553                                                ser, ido);
554                                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
555                                        db.GetErrorErrStr(msglog);
556                                        og_info(msglog);
557                                        return false;
558                                }
559                        }
560                        continue;
561                }
562
563                // Distribución de particionado.
564                disk = par = cpt = sfi = soi = tam = uso = NULL;
565
566                splitCadena(ptrDual, ptrCfg[0], '=');
567                disk = ptrDual[1]; // Número de disco
568
569                splitCadena(ptrDual, ptrCfg[1], '=');
570                par = ptrDual[1]; // Número de partición
571
572                k=splitCadena(ptrDual, ptrCfg[2], '=');
573                if(k==2){
574                        cpt = ptrDual[1]; // Código de partición
575                }else{
576                        cpt = (char*)"0";
577                }
578
579                k=splitCadena(ptrDual, ptrCfg[3], '=');
580                if(k==2){
581                        sfi = ptrDual[1]; // Sistema de ficheros
582                        /* Comprueba existencia del s0xistema de ficheros instalado */
583                        idsfi = checkDato(db, tbl, sfi, "sistemasficheros", "descripcion","idsistemafichero");
584                }
585                else
586                        idsfi=0;
587
588                k=splitCadena(ptrDual, ptrCfg[4], '=');
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
597                splitCadena(ptrDual, ptrCfg[5], '=');
598                tam = ptrDual[1]; // Tamaño de la partición
599
600                splitCadena(ptrDual, ptrCfg[6], '=');
601                uso = ptrDual[1]; // Porcentaje de uso del S.F.
602
603                lon += sprintf(tbPar + lon, "(%s, %s),", disk, par);
604
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",
608                                ido, disk, par);
609
610
611                if (!db.Execute(sqlstr, tbl)) {
612                        db.GetErrorErrStr(msglog);
613                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
614                               __func__, __LINE__, msglog);
615                        return false;
616                }
617                if (tbl.ISEOF()) { // Si no existe el registro
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);
621
622
623                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
624                                db.GetErrorErrStr(msglog);
625                                og_info(msglog);
626                                return false;
627                        }
628                } else { // Existe el registro
629                        swu = true; // Se supone que algún dato ha cambiado
630                        if (!tbl.Get("codpar", dato)) { // Toma dato
631                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
632                                og_info(msglog);
633                                return false;
634                        }
635                        if (strtol(cpt, NULL, 16) == dato) {// Parámetro tipo de partición (hexadecimal) igual al almacenado (decimal)
636                                if (!tbl.Get("tamano", dato)) { // Toma dato
637                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
638                                        og_info(msglog);
639                                        return false;
640                                }
641                                if (atoi(tam) == dato) {// Parámetro tamaño igual al almacenado
642                                        if (!tbl.Get("idsistemafichero", dato)) { // Toma dato
643                                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
644                                                og_info(msglog);
645                                                return false;
646                                        }
647                                        if (idsfi == dato) {// Parámetro sistema de fichero igual al almacenado
648                                                if (!tbl.Get("idnombreso", dato)) { // Toma dato
649                                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
650                                                        og_info(msglog);
651                                                        return false;
652                                                }
653                                                if (idsoi == dato) {// Parámetro sistema de fichero distinto al almacenado
654                                                        swu = false; // Todos los parámetros de la partición son iguales, no se actualiza
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,"
663                                        " uso=%s,"
664                                        " idsistemafichero=%d,"
665                                        " idnombreso=%d,"
666                                        " idimagen=0,"
667                                        " idperfilsoft=0,"
668                                        " fechadespliegue=NULL"
669                                        " WHERE idordenador=%d AND numdisk=%s AND numpar=%s",
670                                        cpt, tam, uso, idsfi, idsoi, ido, disk, par);
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                        }
677                        if (!db.Execute(sqlstr, tbl)) {
678                                db.GetErrorErrStr(msglog);
679                                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
680                                       __func__, __LINE__, msglog);
681                                return false;
682                        }
683                }
684        }
685        lon += sprintf(tbPar + lon, "(0,0)");
686        // Eliminar particiones almacenadas que ya no existen
687        sprintf(sqlstr, "DELETE FROM ordenadores_particiones WHERE idordenador=%d AND (numdisk, numpar) NOT IN (%s)",
688                        ido, tbPar);
689        if (!db.Execute(sqlstr, tbl)) {
690                db.GetErrorErrStr(msglog);
691                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
692                       __func__, __LINE__, msglog);
693                return false;
694        }
695        return true;
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
717int checkDato(Database db, Table tbl, char *dato, const char *tabla,
718                     const char *nomdato, const char *nomidentificador)
719{
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
729        if (!db.Execute(sqlstr, tbl)) {
730                db.GetErrorErrStr(msglog);
731                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
732                       __func__, __LINE__, msglog);
733                return (0);
734        }
735        if (tbl.ISEOF()) { //  Software NO existente
736                sprintf(sqlstr, "INSERT INTO %s (%s) VALUES('%s')", tabla, nomdato, dato);
737                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
738                        db.GetErrorErrStr(msglog); // Error al acceder al registro
739                        og_info(msglog);
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
746                        og_info(msglog);
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
752                                og_info(msglog);
753                                return (0);
754                        }
755                }
756        } else {
757                if (!tbl.Get(nomidentificador, identificador)) { // Toma dato
758                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
759                        og_info(msglog);
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:
773//              true: Si el proceso es correcto
774//              false: En caso de ocurrir algún error
775// ________________________________________________________________________________________________________
776bool registraCliente(char *iph)
777{
778        int idx;
779
780        if (!clienteExistente(iph, &idx)) { // Si no existe la IP ...
781                if (!hayHueco(&idx)) { // Busca hueco para el nuevo cliente
782                        return false; // No hay huecos
783                }
784        }
785        strcpy(tbsockets[idx].ip, iph); // Copia IP
786        strcpy(tbsockets[idx].estado, CLIENTE_INICIANDO); // Actualiza el estado del cliente
787        return true;
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:
798//              true: Si el proceso es correcto
799//              false: En caso de ocurrir algún error
800// ________________________________________________________________________________________________________
801static bool AutoexecCliente(TRAMA *ptrTrama, struct og_client *cli)
802{
803        int socket_c = og_client_socket(cli);
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);
815        liberaMemoria(iph);
816        fileexe = fopen(fileautoexec, "wb"); // Abre fichero de script
817        if (fileexe == NULL) {
818                syslog(LOG_ERR, "cannot create temporary file\n");
819                return false;
820        }
821
822        if (!db.Open(usuario, pasguor, datasource, catalog)) {
823                db.GetErrorErrStr(msglog);
824                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
825                       __func__, __LINE__, msglog);
826                return false;
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
838        db.Close();
839        fclose(fileexe);
840
841        if (!mandaTrama(&socket_c, ptrTrama)) {
842                liberaMemoria(exe);
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));
846                return false;
847        }
848        liberaMemoria(exe);
849        return true;
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:
859//              true: Si el proceso es correcto
860//              false: En caso de ocurrir algún error
861// ________________________________________________________________________________________________________
862bool recorreProcedimientos(Database db, char *parametros, FILE *fileexe, char *idp)
863{
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
873        if (!db.Execute(sqlstr, tbl)) {
874                db.GetErrorErrStr(msglog);
875                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
876                       __func__, __LINE__, msglog);
877                return false;
878        }
879        while (!tbl.ISEOF()) { // Recorre procedimientos
880                if (!tbl.Get("procedimientoid", procedimientoid)) { // Toma dato
881                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
882                        og_info(msglog);
883                        return false;
884                }
885                if (procedimientoid > 0) { // Procedimiento recursivo
886                        sprintf(idprocedimiento, "%d", procedimientoid);
887                        if (!recorreProcedimientos(db, parametros, fileexe, idprocedimiento)) {
888                                return false;
889                        }
890                } else {
891                        if (!tbl.Get("parametros", parametros)) { // Toma dato
892                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
893                                og_info(msglog);
894                                return false;
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        }
902        return true;
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:
913//              true: Si el proceso es correcto
914//              false: En caso de ocurrir algún error
915// ________________________________________________________________________________________________________
916static bool ComandosPendientes(TRAMA *ptrTrama, struct og_client *cli)
917{
918        int socket_c = og_client_socket(cli);
919        char *ido,*iph,pids[LONPRM];
920        int ids, idx;
921
922        iph = copiaParametro("iph",ptrTrama); // Toma dirección IP
923        ido = copiaParametro("ido",ptrTrama); // Toma identificador del ordenador
924
925        if (!clienteExistente(iph, &idx)) { // Busca índice del cliente
926                liberaMemoria(iph);
927                liberaMemoria(ido);
928                syslog(LOG_ERR, "client does not exist\n");
929                return false;
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        }
940        if (!mandaTrama(&socket_c, ptrTrama)) {
941                liberaMemoria(iph);
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));
946                return false;
947        }
948        liberaMemoria(iph);
949        liberaMemoria(ido);     
950        return true;
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)
960//              - ids: Identificador de la sesion(Salida)
961//      Devuelve:
962//              true: Si el proceso es correcto
963//              false: En caso de ocurrir algún error
964// ________________________________________________________________________________________________________
965bool buscaComandos(char *ido, TRAMA *ptrTrama, int *ids)
966{
967        char msglog[LONSTD], sqlstr[LONSQL];
968        Database db;
969        Table tbl;
970        int lonprm;
971
972        if (!db.Open(usuario, pasguor, datasource, catalog)) {
973                db.GetErrorErrStr(msglog);
974                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
975                       __func__, __LINE__, msglog);
976                return false;
977        }
978        sprintf(sqlstr,"SELECT sesion,parametros,length( parametros) as lonprm"\
979                        " FROM acciones WHERE idordenador=%s AND estado='%d' ORDER BY idaccion", ido, ACCION_INICIADA);
980        if (!db.Execute(sqlstr, tbl)) {
981                db.GetErrorErrStr(msglog);
982                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
983                       __func__, __LINE__, msglog);
984                return false;
985        }
986        if (tbl.ISEOF()) {
987                db.Close();
988                return false; // No hay comandos pendientes
989        } else { // Busca entre todas las acciones de diversos ambitos
990                if (!tbl.Get("sesion", *ids)) { // Toma identificador de la sesion
991                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
992                        og_info(msglog);
993                        return false;
994                }
995                if (!tbl.Get("lonprm", lonprm)) { // Toma parámetros del comando
996                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
997                        og_info(msglog);
998                        return false;
999                }
1000                if(!initParametros(ptrTrama,lonprm+LONGITUD_PARAMETROS)){
1001                        db.Close();
1002                        syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
1003                        return false;
1004                }
1005                if (!tbl.Get("parametros", ptrTrama->parametros)) { // Toma parámetros del comando
1006                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
1007                        og_info(msglog);
1008                        return false;
1009                }
1010        }
1011        db.Close();
1012        return true; // Hay comandos pendientes, se toma el primero de la cola
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:
1023//              true: Si el proceso es correcto
1024//              false: En caso de ocurrir algún error
1025// ________________________________________________________________________________________________________
1026//
1027static bool DisponibilidadComandos(TRAMA *ptrTrama, struct og_client *cli)
1028{
1029        char *iph, *tpc;
1030        int idx;
1031
1032        iph = copiaParametro("iph",ptrTrama); // Toma ip
1033        if (!clienteExistente(iph, &idx)) { // Busca índice del cliente
1034                liberaMemoria(iph);
1035                syslog(LOG_ERR, "client does not exist\n");
1036                return false;
1037        }
1038        tpc = copiaParametro("tpc",ptrTrama); // Tipo de cliente (Plataforma y S.O.)
1039        strcpy(tbsockets[idx].estado, tpc);
1040        cli->keepalive_idx = idx;
1041        liberaMemoria(iph);
1042        liberaMemoria(tpc);             
1043        return true;
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
1054//              - ids: identificador de la sesión
1055//              - ido: Identificador del ordenador que notifica
1056//              - db: Objeto base de datos (operativo)
1057//              - tbl: Objeto tabla
1058//      Devuelve:
1059//              true: Si el proceso es correcto
1060//              false: En caso de ocurrir algún error
1061// ________________________________________________________________________________________________________
1062static bool respuestaEstandar(TRAMA *ptrTrama, char *iph, char *ido, Database db,
1063                Table tbl)
1064{
1065        char msglog[LONSTD], sqlstr[LONSQL];
1066        char *res, *ids, *der;
1067        char fechafin[LONPRM];
1068        struct tm* st;
1069        int idaccion;
1070
1071        ids = copiaParametro("ids",ptrTrama); // Toma identificador de la sesión
1072
1073        if (ids == NULL) // No existe seguimiento de la acción
1074                return true;
1075
1076        if (atoi(ids) == 0){ // No existe seguimiento de la acción
1077                liberaMemoria(ids);
1078                return true;
1079        }
1080
1081        sprintf(sqlstr,
1082                        "SELECT * FROM acciones WHERE idordenador=%s"
1083                        " AND sesion=%s ORDER BY idaccion", ido,ids);
1084
1085        liberaMemoria(ids);
1086
1087        if (!db.Execute(sqlstr, tbl)) {
1088                db.GetErrorErrStr(msglog);
1089                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1090                       __func__, __LINE__, msglog);
1091                return false;
1092        }
1093        if (tbl.ISEOF()) {
1094                syslog(LOG_ERR, "no actions available\n");
1095                return true;
1096        }
1097        if (!tbl.Get("idaccion", idaccion)) { // Toma identificador de la accion
1098                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
1099                og_info(msglog);
1100                return false;
1101        }
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
1106        res = copiaParametro("res",ptrTrama); // Toma resultado
1107        der = copiaParametro("der",ptrTrama); // Toma descripción del error (si hubiera habido)
1108       
1109        sprintf(sqlstr,
1110                        "UPDATE acciones"\
1111                        "   SET resultado='%s',estado='%d',fechahorafin='%s',descrinotificacion='%s'"\
1112                        " WHERE idordenador=%s AND idaccion=%d",
1113                        res, ACCION_FINALIZADA, fechafin, der, ido, idaccion);
1114                       
1115        if (!db.Execute(sqlstr, tbl)) { // Error al actualizar
1116                liberaMemoria(res);
1117                liberaMemoria(der);
1118                db.GetErrorErrStr(msglog);
1119                og_info(msglog);
1120                return false;
1121        }
1122       
1123        liberaMemoria(der);
1124       
1125        if (atoi(res) == ACCION_FALLIDA) {
1126                liberaMemoria(res);
1127                return false; // Error en la ejecución del comando
1128        }
1129
1130        liberaMemoria(res);
1131        return true;
1132}
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
1144                        if (sock >= 0 && !mandaTrama(&sock, ptrTrama)) {
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
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:
1162//              true: Si el proceso es correcto
1163//              false: En caso de ocurrir algún error
1164// ________________________________________________________________________________________________________
1165bool enviaComando(TRAMA* ptrTrama, const char *estado)
1166{
1167        char *iph, *Ipes, *ptrIpes[MAXIMOS_CLIENTES];
1168        int lon;
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) {
1174                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
1175                return false;
1176        }
1177       
1178        strcpy(Ipes, iph); // Copia cadena de IPES
1179        liberaMemoria(iph);
1180
1181        lon = splitCadena(ptrIpes, Ipes, ';');
1182        FINCADaINTRO(ptrTrama);
1183
1184        if (!og_send_cmd(ptrIpes, lon, estado, ptrTrama))
1185                return false;
1186
1187        liberaMemoria(Ipes);
1188        return true;
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:
1199//              true: Si el proceso es correcto
1200//              false: En caso de ocurrir algún error
1201// ________________________________________________________________________________________________________
1202bool respuestaConsola(int socket_c, TRAMA *ptrTrama, int res)
1203{
1204        initParametros(ptrTrama,0);
1205        sprintf(ptrTrama->parametros, "res=%d\r", res);
1206        if (!mandaTrama(&socket_c, ptrTrama)) {
1207                syslog(LOG_ERR, "%s:%d failed to send response: %s\n",
1208                       __func__, __LINE__, strerror(errno));
1209                return false;
1210        }
1211        return true;
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:
1219//              - iph: Cadena de direcciones ip separadas por ";"
1220//              - mac: Cadena de direcciones mac separadas por ";"
1221//              - mar: Método de arranque (1=Broadcast, 2=Unicast)
1222//      Devuelve:
1223//              true: Si el proceso es correcto
1224//              false: En caso de ocurrir algún error
1225// ________________________________________________________________________________________________________
1226
1227bool Levanta(char *ptrIP[], char *ptrMacs[], int lon, char *mar)
1228{
1229        unsigned int on = 1;
1230        sockaddr_in local;
1231        int i, res;
1232        int s;
1233
1234        /* Creación de socket para envío de magig packet */
1235        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1236        if (s < 0) {
1237                syslog(LOG_ERR, "cannot create socket for magic packet\n");
1238                return false;
1239        }
1240        res = setsockopt(s, SOL_SOCKET, SO_BROADCAST, (unsigned int *) &on,
1241                         sizeof(on));
1242        if (res < 0) {
1243                syslog(LOG_ERR, "cannot set broadcast socket\n");
1244                return false;
1245        }
1246        memset(&local, 0, sizeof(local));
1247        local.sin_family = AF_INET;
1248        local.sin_port = htons(PUERTO_WAKEUP);
1249        local.sin_addr.s_addr = htonl(INADDR_ANY);
1250
1251        for (i = 0; i < lon; i++) {
1252                if (!WakeUp(s, ptrIP[i], ptrMacs[i], mar)) {
1253                        syslog(LOG_ERR, "problem sending magic packet\n");
1254                        close(s);
1255                        return false;
1256                }
1257        }
1258        close(s);
1259        return true;
1260}
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        }
1296        freeifaddrs(ifaddr);
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
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
1338//              - iph : Cadena con la dirección ip
1339//              - mac : Cadena con la dirección mac en formato XXXXXXXXXXXX
1340//              - mar: Método de arranque (1=Broadcast, 2=Unicast)
1341//      Devuelve:
1342//              true: Si el proceso es correcto
1343//              false: En caso de ocurrir algún error
1344//_____________________________________________________________________________________________________________
1345//
1346bool WakeUp(int s, char* iph, char *mac, char *mar)
1347{
1348        unsigned int macaddr[OG_WOL_MACADDR_LEN];
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;
1355
1356        for (i = 0; i < 6; i++) // Primera secuencia de la trama Wake Up (0xFFFFFFFFFFFF)
1357                Trama_WakeUp.secuencia_FF[i] = 0xFF;
1358
1359        sscanf(mac, "%02x%02x%02x%02x%02x%02x",
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];
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
1373        switch (atoi(mar)) {
1374        case OG_WOL_BROADCAST:
1375                ret = wake_up_broadcast(s, &WakeUpCliente, &Trama_WakeUp);
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                }
1383                ret = wake_up_unicast(s, &WakeUpCliente, &Trama_WakeUp, &addr);
1384                break;
1385        default:
1386                syslog(LOG_ERR, "unknown wol type\n");
1387                ret = false;
1388                break;
1389        }
1390        return ret;
1391}
1392// ________________________________________________________________________________________________________
1393// Función: RESPUESTA_Arrancar
1394//
1395//      Descripción:
1396//              Respuesta del cliente al comando Arrancar
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:
1401//              true: Si el proceso es correcto
1402//              false: En caso de ocurrir algún error
1403// ________________________________________________________________________________________________________
1404static bool RESPUESTA_Arrancar(TRAMA* ptrTrama, struct og_client *cli)
1405{
1406        char msglog[LONSTD];
1407        Database db;
1408        Table tbl;
1409        int i;
1410        char *iph, *ido;
1411        char *tpc;
1412
1413        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1414                db.GetErrorErrStr(msglog);
1415                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1416                       __func__, __LINE__, msglog);
1417                return false;
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)) {
1424                liberaMemoria(iph);
1425                liberaMemoria(ido);
1426                syslog(LOG_ERR, "failed to register notification\n");
1427                return false;
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);
1433               
1434        liberaMemoria(iph);
1435        liberaMemoria(ido);
1436        liberaMemoria(tpc);
1437       
1438        db.Close(); // Cierra conexión
1439        return true;
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:
1450//              true: Si el proceso es correcto
1451//              false: En caso de ocurrir algún error
1452// ________________________________________________________________________________________________________
1453static bool RESPUESTA_Apagar(TRAMA* ptrTrama, struct og_client *cli)
1454{
1455        char msglog[LONSTD];
1456        Database db;
1457        Table tbl;
1458        int i;
1459        char *iph, *ido;
1460
1461        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1462                db.GetErrorErrStr(msglog);
1463                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1464                       __func__, __LINE__, msglog);
1465                return false;
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)) {
1472                liberaMemoria(iph);
1473                liberaMemoria(ido);
1474                syslog(LOG_ERR, "failed to register notification\n");
1475                return false; // Error al registrar notificacion
1476        }
1477
1478        if (clienteExistente(iph, &i)) // Actualiza estado
1479                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
1480       
1481        liberaMemoria(iph);
1482        liberaMemoria(ido);
1483       
1484        db.Close(); // Cierra conexión
1485        return true;
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:
1496//              true: Si el proceso es correcto
1497//              false: En caso de ocurrir algún error
1498// ________________________________________________________________________________________________________
1499static bool RESPUESTA_Reiniciar(TRAMA* ptrTrama, struct og_client *cli)
1500{
1501        char msglog[LONSTD];
1502        Database db;
1503        Table tbl;
1504        int i;
1505        char *iph, *ido;
1506
1507        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1508                db.GetErrorErrStr(msglog);
1509                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1510                       __func__, __LINE__, msglog);
1511                return false;
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)) {
1518                liberaMemoria(iph);
1519                liberaMemoria(ido);
1520                syslog(LOG_ERR, "failed to register notification\n");
1521                return false; // Error al registrar notificacion
1522        }
1523
1524        if (clienteExistente(iph, &i)) // Actualiza estado
1525                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
1526       
1527        liberaMemoria(iph);
1528        liberaMemoria(ido);
1529
1530        db.Close(); // Cierra conexión
1531        return true;
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:
1542//              true: Si el proceso es correcto
1543//              false: En caso de ocurrir algún error
1544// ________________________________________________________________________________________________________
1545static bool RESPUESTA_IniciarSesion(TRAMA* ptrTrama, struct og_client *cli)
1546{
1547        char msglog[LONSTD];
1548        Database db;
1549        Table tbl;
1550        int i;
1551        char *iph, *ido;
1552
1553        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1554                db.GetErrorErrStr(msglog);
1555                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1556                       __func__, __LINE__, msglog);
1557                return false;
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)) {
1564                liberaMemoria(iph);
1565                liberaMemoria(ido);
1566                syslog(LOG_ERR, "failed to register notification\n");
1567                return false; // Error al registrar notificacion
1568        }
1569
1570        if (clienteExistente(iph, &i)) // Actualiza estado
1571                strcpy(tbsockets[i].estado, CLIENTE_APAGADO);
1572               
1573        liberaMemoria(iph);
1574        liberaMemoria(ido);
1575               
1576        db.Close(); // Cierra conexión
1577        return true;
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:
1588//              true: Si el proceso es correcto
1589//              false: En caso de ocurrir algún error
1590// ________________________________________________________________________________________________________
1591static bool RESPUESTA_CrearImagen(TRAMA* ptrTrama, struct og_client *cli)
1592{
1593        char msglog[LONSTD];
1594        Database db;
1595        Table tbl;
1596        char *iph, *dsk, *par, *cpt, *ipr, *ido;
1597        char *idi;
1598        bool res;
1599
1600        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1601                db.GetErrorErrStr(msglog);
1602                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1603                       __func__, __LINE__, msglog);
1604                return false;
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)) {
1611                liberaMemoria(iph);
1612                liberaMemoria(ido);
1613                syslog(LOG_ERR, "failed to register notification\n");
1614                return false; // Error al registrar notificacion
1615        }
1616
1617        // Acciones posteriores
1618        idi = copiaParametro("idi",ptrTrama);
1619        dsk = copiaParametro("dsk",ptrTrama);
1620        par = copiaParametro("par",ptrTrama);
1621        cpt = copiaParametro("cpt",ptrTrama);
1622        ipr = copiaParametro("ipr",ptrTrama);
1623
1624        res=actualizaCreacionImagen(db, tbl, idi, dsk, par, cpt, ipr, ido);
1625
1626        liberaMemoria(idi);
1627        liberaMemoria(par);
1628        liberaMemoria(cpt);
1629        liberaMemoria(ipr);
1630
1631        if(!res){
1632                syslog(LOG_ERR, "Problem processing update\n");
1633                db.Close();
1634                return false;
1635        }
1636
1637        db.Close(); // Cierra conexión
1638        return true;
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
1649//              - dsk: Disco de donde se creó
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:
1655//              true: Si el proceso es correcto
1656//              false: En caso de ocurrir algún error
1657// ________________________________________________________________________________________________________
1658bool actualizaCreacionImagen(Database db, Table tbl, char *idi, char *dsk,
1659                             char *par, char *cpt, char *ipr, char *ido)
1660{
1661        char msglog[LONSTD], sqlstr[LONSQL];
1662        int idr,ifs;
1663
1664        /* Toma identificador del repositorio correspondiente al ordenador modelo */
1665        snprintf(sqlstr, LONSQL,
1666                        "SELECT repositorios.idrepositorio"
1667                        "  FROM repositorios"
1668                        "  LEFT JOIN ordenadores USING (idrepositorio)"
1669                        " WHERE repositorios.ip='%s' AND ordenadores.idordenador=%s", ipr, ido);
1670
1671        if (!db.Execute(sqlstr, tbl)) {
1672                db.GetErrorErrStr(msglog);
1673                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1674                       __func__, __LINE__, msglog);
1675                return false;
1676        }
1677        if (!tbl.Get("idrepositorio", idr)) { // Toma dato
1678                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
1679                og_info(msglog);
1680                return false;
1681        }
1682
1683        /* Toma identificador del perfilsoftware */
1684        snprintf(sqlstr, LONSQL,
1685                        "SELECT idperfilsoft"
1686                        "  FROM ordenadores_particiones"
1687                        " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", ido, dsk, par);
1688
1689        if (!db.Execute(sqlstr, tbl)) {
1690                db.GetErrorErrStr(msglog);
1691                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1692                       __func__, __LINE__, msglog);
1693                return false;
1694        }
1695        if (!tbl.Get("idperfilsoft", ifs)) { // Toma dato
1696                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
1697                og_info(msglog);
1698                return false;
1699        }
1700
1701        /* Actualizar los datos de la imagen */
1702        snprintf(sqlstr, LONSQL,
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);
1708
1709        if (!db.Execute(sqlstr, tbl)) {
1710                db.GetErrorErrStr(msglog);
1711                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1712                       __func__, __LINE__, msglog);
1713                return false;
1714        }
1715        /* Actualizar los datos en el cliente */
1716        snprintf(sqlstr, LONSQL,
1717                "UPDATE ordenadores_particiones"
1718                "   SET idimagen=%s, revision=(SELECT revision FROM imagenes WHERE idimagen=%s),"
1719                "       fechadespliegue=NOW()"
1720                " WHERE idordenador=%s AND numdisk=%s AND numpar=%s",
1721                idi, idi, ido, dsk, par);
1722        if (!db.Execute(sqlstr, tbl)) {
1723                db.GetErrorErrStr(msglog);
1724                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1725                       __func__, __LINE__, msglog);
1726                return false;
1727        }
1728        return true;
1729}
1730// ________________________________________________________________________________________________________
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:
1739//              true: Si el proceso es correcto
1740//              false: En caso de ocurrir algún error
1741// ________________________________________________________________________________________________________
1742static bool CrearImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
1743{
1744        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
1745                respuestaConsola(og_client_socket(cli), ptrTrama, false);
1746                return false;
1747        }
1748        respuestaConsola(og_client_socket(cli), ptrTrama, true);
1749        return true;
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:
1760//              true: Si el proceso es correcto
1761//              false: En caso de ocurrir algún error
1762// ________________________________________________________________________________________________________
1763static bool RESPUESTA_CrearImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
1764{
1765        // La misma respuesta que la creación de imagen monolítica
1766        return RESPUESTA_CrearImagen(ptrTrama, cli);
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:
1778//              true: Si el proceso es correcto
1779//              false: En caso de ocurrir algún error
1780// ________________________________________________________________________________________________________
1781static bool CrearSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
1782{
1783        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
1784                respuestaConsola(og_client_socket(cli), ptrTrama, false);
1785                return false;
1786        }
1787        respuestaConsola(og_client_socket(cli), ptrTrama, true);
1788        return true;
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:
1799//              true: Si el proceso es correcto
1800//              false: En caso de ocurrir algún error
1801// ________________________________________________________________________________________________________
1802static bool RESPUESTA_CrearSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
1803{
1804        Database db;
1805        Table tbl;
1806        char *iph,*par,*ido,*idf;
1807        int ifs;
1808        char msglog[LONSTD],sqlstr[LONSQL];
1809
1810        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1811                db.GetErrorErrStr(msglog);
1812                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1813                       __func__, __LINE__, msglog);
1814                return false;
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);
1822                liberaMemoria(ido);
1823                syslog(LOG_ERR, "failed to register notification\n");
1824                return false;
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);     
1835
1836        if (!db.Execute(sqlstr, tbl)) {
1837                db.GetErrorErrStr(msglog);
1838                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1839                       __func__, __LINE__, msglog);
1840                return false;
1841        }
1842        if (!tbl.Get("idperfilsoft", ifs)) { // Toma dato
1843                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
1844                og_info(msglog);
1845                return false;
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);     
1852
1853        if (!db.Execute(sqlstr, tbl)) {
1854                db.GetErrorErrStr(msglog);
1855                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
1856                       __func__, __LINE__, msglog);
1857                return false;
1858        }
1859        db.Close(); // Cierra conexión
1860        return true;
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:
1871//              true: Si el proceso es correcto
1872//              false: En caso de ocurrir algún error
1873// ________________________________________________________________________________________________________
1874static bool RestaurarImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
1875{
1876        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
1877                respuestaConsola(og_client_socket(cli), ptrTrama, false);
1878                return false;
1879        }
1880        respuestaConsola(og_client_socket(cli), ptrTrama, true);
1881        return true;
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:
1892//              true: Si el proceso es correcto
1893//              false: En caso de ocurrir algún error
1894// ________________________________________________________________________________________________________
1895static bool RestaurarSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
1896{
1897        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
1898                respuestaConsola(og_client_socket(cli), ptrTrama, false);
1899                return false;
1900        }
1901        respuestaConsola(og_client_socket(cli), ptrTrama, true);
1902        return true;
1903}
1904// ________________________________________________________________________________________________________
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:
1913//              true: Si el proceso es correcto
1914//              false: En caso de ocurrir algún error
1915// ________________________________________________________________________________________________________
1916//
1917static bool RESPUESTA_RestaurarImagen(TRAMA* ptrTrama, struct og_client *cli)
1918{
1919        char msglog[LONSTD];
1920        Database db;
1921        Table tbl;
1922        bool res;
1923        char *iph, *ido, *idi, *dsk, *par, *ifs, *cfg;
1924
1925        if (!db.Open(usuario, pasguor, datasource, catalog)) {
1926                db.GetErrorErrStr(msglog);
1927                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
1928                       __func__, __LINE__, msglog);
1929                return false;
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)) {
1936                liberaMemoria(iph);
1937                liberaMemoria(ido);
1938                syslog(LOG_ERR, "failed to register notification\n");
1939                return false;
1940        }
1941
1942        // Acciones posteriores
1943        idi = copiaParametro("idi",ptrTrama); // Toma identificador de la imagen
1944        dsk = copiaParametro("dsk",ptrTrama); // Número de disco
1945        par = copiaParametro("par",ptrTrama); // Número de partición
1946        ifs = copiaParametro("ifs",ptrTrama); // Identificador del perfil software contenido
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        }
1952        res=actualizaRestauracionImagen(db, tbl, idi, dsk, par, ido, ifs);
1953       
1954        liberaMemoria(iph);
1955        liberaMemoria(ido);
1956        liberaMemoria(idi);
1957        liberaMemoria(par);
1958        liberaMemoria(ifs);
1959
1960        if(!res){
1961                syslog(LOG_ERR, "Problem after restoring image\n");
1962                db.Close();
1963                return false;
1964        }
1965
1966        db.Close(); // Cierra conexión
1967        return true;
1968}
1969// ________________________________________________________________________________________________________
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:
1979//              true: Si el proceso es correcto
1980//              false: En caso de ocurrir algún error
1981// ________________________________________________________________________________________________________
1982//
1983static bool RESPUESTA_RestaurarImagenBasica(TRAMA* ptrTrama, struct og_client *cli)
1984{
1985        return RESPUESTA_RestaurarImagen(ptrTrama, cli);
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:
1996//              true: Si el proceso es correcto
1997//              false: En caso de ocurrir algún error
1998// ________________________________________________________________________________________________________
1999static bool RESPUESTA_RestaurarSoftIncremental(TRAMA* ptrTrama, struct og_client *cli)
2000{
2001        return RESPUESTA_RestaurarImagen(ptrTrama, cli);
2002}
2003// ________________________________________________________________________________________________________
2004// Función: actualizaRestauracionImagen
2005//
2006//      Descripción:
2007//              Esta función actualiza la base de datos con el resultado de la restauración de una imagen
2008//      Parámetros:
2009//              - db: Objeto base de datos (ya operativo)
2010//              - tbl: Objeto tabla
2011//              - idi: Identificador de la imagen
2012//              - dsk: Disco de donde se restauró
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:
2017//              true: Si el proceso es correcto
2018//              false: En caso de ocurrir algún error
2019// ________________________________________________________________________________________________________
2020bool actualizaRestauracionImagen(Database db, Table tbl, char *idi,
2021                                 char *dsk, char *par, char *ido, char *ifs)
2022{
2023        char msglog[LONSTD], sqlstr[LONSQL];
2024
2025        /* Actualizar los datos de la imagen */
2026        snprintf(sqlstr, LONSQL,
2027                        "UPDATE ordenadores_particiones"
2028                        "   SET idimagen=%s, idperfilsoft=%s, fechadespliegue=NOW(),"
2029                        "       revision=(SELECT revision FROM imagenes WHERE idimagen=%s),"
2030                        "       idnombreso=IFNULL((SELECT idnombreso FROM perfilessoft WHERE idperfilsoft=%s),0)"
2031                        " WHERE idordenador=%s AND numdisk=%s AND numpar=%s", idi, ifs, idi, ifs, ido, dsk, par);
2032
2033        if (!db.Execute(sqlstr, tbl)) {
2034                db.GetErrorErrStr(msglog);
2035                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2036                       __func__, __LINE__, msglog);
2037                return false;
2038        }
2039        return true;
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:
2050//              true: Si el proceso es correcto
2051//              false: En caso de ocurrir algún error
2052// ________________________________________________________________________________________________________
2053static bool Configurar(TRAMA* ptrTrama, struct og_client *cli)
2054{
2055        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
2056                respuestaConsola(og_client_socket(cli), ptrTrama, false);
2057                return false;
2058        }
2059        respuestaConsola(og_client_socket(cli), ptrTrama, true);
2060        return true;
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:
2071//              true: Si el proceso es correcto
2072//              false: En caso de ocurrir algún error
2073// ________________________________________________________________________________________________________
2074//
2075static bool RESPUESTA_Configurar(TRAMA* ptrTrama, struct og_client *ci)
2076{
2077        char msglog[LONSTD];
2078        Database db;
2079        Table tbl;
2080        bool res;
2081        char *iph, *ido,*cfg;
2082
2083        if (!db.Open(usuario, pasguor, datasource, catalog)) {
2084                db.GetErrorErrStr(msglog);
2085                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2086                       __func__, __LINE__, msglog);
2087                return false;
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)) {
2094                liberaMemoria(iph);
2095                liberaMemoria(ido);
2096                syslog(LOG_ERR, "failed to register notification\n");
2097                return false;
2098        }
2099
2100        cfg = copiaParametro("cfg",ptrTrama); // Toma configuración de particiones
2101        res=actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador
2102       
2103        liberaMemoria(iph);
2104        liberaMemoria(ido);     
2105        liberaMemoria(cfg);     
2106
2107        if(!res){
2108                syslog(LOG_ERR, "Problem updating client configuration\n");
2109                return false;
2110        }
2111
2112        db.Close(); // Cierra conexión
2113        return true;
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:
2124//              true: Si el proceso es correcto
2125//              false: En caso de ocurrir algún error
2126// ________________________________________________________________________________________________________
2127static bool EjecutarScript(TRAMA* ptrTrama, struct og_client *cli)
2128{
2129        if (!enviaComando(ptrTrama, CLIENTE_OCUPADO)) {
2130                respuestaConsola(og_client_socket(cli), ptrTrama, false);
2131                return false;
2132        }
2133        respuestaConsola(og_client_socket(cli), ptrTrama, true);
2134        return true;
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:
2145//              true: Si el proceso es correcto
2146//              false: En caso de ocurrir algún error
2147// ________________________________________________________________________________________________________
2148static bool RESPUESTA_EjecutarScript(TRAMA* ptrTrama, struct og_client *cli)
2149{
2150        char msglog[LONSTD];
2151        Database db;
2152        Table tbl;
2153        char *iph, *ido,*cfg;
2154
2155        if (!db.Open(usuario, pasguor, datasource, catalog)) {
2156                db.GetErrorErrStr(msglog);
2157                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2158                       __func__, __LINE__, msglog);
2159                return false;
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)) {
2166                liberaMemoria(iph);
2167                liberaMemoria(ido);
2168                syslog(LOG_ERR, "failed to register notification\n");
2169                return false;
2170        }
2171       
2172        cfg = copiaParametro("cfg",ptrTrama); // Toma configuración de particiones
2173        if(cfg){
2174                actualizaConfiguracion(db, tbl, cfg, atoi(ido)); // Actualiza la configuración del ordenador
2175                liberaMemoria(cfg);     
2176        }
2177
2178        liberaMemoria(iph);
2179        liberaMemoria(ido);
2180
2181       
2182        db.Close(); // Cierra conexión
2183        return true;
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:
2194//              true: Si el proceso es correcto
2195//              false: En caso de ocurrir algún error
2196// ________________________________________________________________________________________________________
2197static bool RESPUESTA_InventarioHardware(TRAMA* ptrTrama, struct og_client *cli)
2198{
2199        char msglog[LONSTD];
2200        Database db;
2201        Table tbl;
2202        bool res;
2203        char *iph, *ido, *idc, *npc, *hrd, *buffer;
2204
2205        if (!db.Open(usuario, pasguor, datasource, catalog)) {
2206                db.GetErrorErrStr(msglog);
2207                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2208                       __func__, __LINE__, msglog);
2209                return false;
2210        }
2211
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)) {
2216                liberaMemoria(iph);
2217                liberaMemoria(ido);
2218                syslog(LOG_ERR, "failed to register notification\n");
2219                return false;
2220        }
2221        // Lee archivo de inventario enviado anteriormente
2222        hrd = copiaParametro("hrd",ptrTrama);
2223        buffer = rTrim(leeArchivo(hrd));
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){
2238                syslog(LOG_ERR, "Problem updating client configuration\n");
2239                return false;
2240        }
2241               
2242        db.Close(); // Cierra conexión
2243        return true;
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// ________________________________________________________________________________________________________
2258//
2259bool actualizaHardware(Database db, Table tbl, char *hrd, char *ido, char *npc,
2260                       char *idc)
2261{
2262        char msglog[LONSTD], sqlstr[LONSQL];
2263        int idtipohardware, idperfilhard;
2264        int lon, i, j, aux;
2265        bool retval;
2266        char *whard;
2267        int tbidhardware[MAXHARDWARE];
2268        char *tbHardware[MAXHARDWARE],*dualHardware[2], descripcion[250], strInt[LONINT], *idhardwares;
2269
2270        /* Toma Centro (Unidad Organizativa) */
2271        sprintf(sqlstr, "SELECT * FROM ordenadores WHERE idordenador=%s", ido);
2272
2273        if (!db.Execute(sqlstr, tbl)) {
2274                db.GetErrorErrStr(msglog);
2275                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2276                       __func__, __LINE__, msglog);
2277                return false;
2278        }
2279        if (!tbl.Get("idperfilhard", idperfilhard)) { // Toma dato
2280                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2281                og_info(msglog);
2282                return false;
2283        }
2284        whard=escaparCadena(hrd); // Codificar comillas simples
2285        if(!whard)
2286                return false;
2287        /* Recorre componentes hardware*/
2288        lon = splitCadena(tbHardware, whard, '\n');
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]);
2294         RegistraLog(msglog,false);
2295         }
2296         */
2297        for (i = 0; i < lon; i++) {
2298                splitCadena(dualHardware, rTrim(tbHardware[i]), '=');
2299                //sprintf(msglog,"nemonico: %s",dualHardware[0]);
2300                //RegistraLog(msglog,false);
2301                //sprintf(msglog,"valor: %s",dualHardware[1]);
2302                //RegistraLog(msglog,false);
2303                sprintf(sqlstr, "SELECT idtipohardware,descripcion FROM tipohardwares "
2304                        " WHERE nemonico='%s'", dualHardware[0]);
2305                if (!db.Execute(sqlstr, tbl)) {
2306                        db.GetErrorErrStr(msglog);
2307                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2308                               __func__, __LINE__, msglog);
2309                        return false;
2310                }
2311                if (tbl.ISEOF()) { //  Tipo de Hardware NO existente
2312                        sprintf(msglog, "%s: %s)", tbErrores[54], dualHardware[0]);
2313                        og_info(msglog);
2314                        return false;
2315                } else { //  Tipo de Hardware Existe
2316                        if (!tbl.Get("idtipohardware", idtipohardware)) { // Toma dato
2317                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2318                                og_info(msglog);
2319                                return false;
2320                        }
2321                        if (!tbl.Get("descripcion", descripcion)) { // Toma dato
2322                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2323                                og_info(msglog);
2324                                return false;
2325                        }
2326
2327                        sprintf(sqlstr, "SELECT idhardware FROM hardwares "
2328                                " WHERE idtipohardware=%d AND descripcion='%s'",
2329                                        idtipohardware, dualHardware[1]);
2330
2331                        if (!db.Execute(sqlstr, tbl)) {
2332                                db.GetErrorErrStr(msglog);
2333                                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2334                                       __func__, __LINE__, msglog);
2335                                return false;
2336                        }
2337
2338                        if (tbl.ISEOF()) { //  Hardware NO existente
2339                                sprintf(sqlstr, "INSERT hardwares (idtipohardware,descripcion,idcentro,grupoid) "
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
2344                                        og_info(msglog);
2345                                        return false;
2346                                }
2347                                // Recupera el identificador del hardware
2348                                sprintf(sqlstr, "SELECT LAST_INSERT_ID() as identificador");
2349                                if (!db.Execute(sqlstr, tbl)) {
2350                                        db.GetErrorErrStr(msglog);
2351                                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2352                                               __func__, __LINE__, msglog);
2353                                        return false;
2354                                }
2355                                if (!tbl.ISEOF()) { // Si existe registro
2356                                        if (!tbl.Get("identificador", tbidhardware[i])) {
2357                                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2358                                                og_info(msglog);
2359                                                return false;
2360                                        }
2361                                }
2362                        } else {
2363                                if (!tbl.Get("idhardware", tbidhardware[i])) { // Toma dato
2364                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2365                                        og_info(msglog);
2366                                        return false;
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) {
2387                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
2388                return false;
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)) {
2396                syslog(LOG_ERR, "Problem updating client hardware\n");
2397                retval=false;
2398        }
2399        else {
2400                retval=true;
2401        }
2402        liberaMemoria(whard);
2403        liberaMemoria(idhardwares);
2404        return (retval);
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// ________________________________________________________________________________________________________
2420bool cuestionPerfilHardware(Database db, Table tbl, char *idc, char *ido,
2421                int idperfilhardware, char *idhardwares, char *npc, int *tbidhardware,
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) {
2430                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
2431                return false;
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);
2441
2442        if (!db.Execute(sqlstr, tbl)) {
2443                db.GetErrorErrStr(msglog);
2444                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2445                       __func__, __LINE__, msglog);
2446                liberaMemoria(sqlstr);
2447                return false;
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)"
2451                                " VALUES('Perfil hardware (%s) ',%s,0)", npc, idc);
2452                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2453                        db.GetErrorErrStr(msglog);
2454                        og_info(msglog);
2455                        liberaMemoria(sqlstr);
2456                        return false;
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);
2462                        og_info(msglog);
2463                        liberaMemoria(sqlstr);
2464                        return false;
2465                }
2466                if (!tbl.ISEOF()) { // Si existe registro
2467                        if (!tbl.Get("identificador", nwidperfilhard)) {
2468                                tbl.GetErrorErrStr(msglog);
2469                                og_info(msglog);
2470                                liberaMemoria(sqlstr);
2471                                return false;
2472                        }
2473                }
2474                // Crea la relación entre perfiles y componenetes hardware
2475                for (i = 0; i < lon; i++) {
2476                        sprintf(sqlstr, "INSERT perfileshard_hardwares  (idperfilhard,idhardware)"
2477                                                " VALUES(%d,%d)", nwidperfilhard, tbidhardware[i]);
2478                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2479                                db.GetErrorErrStr(msglog);
2480                                og_info(msglog);
2481                                liberaMemoria(sqlstr);
2482                                return false;
2483                        }
2484                }
2485        } else { // Existe un perfil con todos esos componentes
2486                if (!tbl.Get("idperfilhard", nwidperfilhard)) {
2487                        tbl.GetErrorErrStr(msglog);
2488                        og_info(msglog);
2489                        liberaMemoria(sqlstr);
2490                        return false;
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);
2499                        og_info(msglog);
2500                        liberaMemoria(sqlstr);
2501                        return false;
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);
2510                og_info(msglog);
2511                liberaMemoria(sqlstr);
2512                return false;
2513        }
2514
2515        /* Eliminar Perfiles hardware que quedan húerfanos */
2516        sprintf(sqlstr, "DELETE FROM perfileshard WHERE idperfilhard NOT IN"
2517                        " (SELECT DISTINCT idperfilhard FROM ordenadores)");
2518        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2519                db.GetErrorErrStr(msglog);
2520                og_info(msglog);
2521                liberaMemoria(sqlstr);
2522                return false;
2523        }
2524        /* Eliminar Relación de hardwares con Perfiles hardware que quedan húerfanos */
2525        sprintf(sqlstr, "DELETE FROM perfileshard_hardwares WHERE idperfilhard NOT IN"
2526                        " (SELECT idperfilhard FROM perfileshard)");
2527        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2528                db.GetErrorErrStr(msglog);
2529                og_info(msglog);
2530                liberaMemoria(sqlstr);
2531                return false;
2532        }
2533        liberaMemoria(sqlstr);
2534        return true;
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:
2545//              true: Si el proceso es correcto
2546//              false: En caso de ocurrir algún error
2547// ________________________________________________________________________________________________________
2548static bool RESPUESTA_InventarioSoftware(TRAMA* ptrTrama, struct og_client *cli)
2549{
2550        char msglog[LONSTD];
2551        Database db;
2552        Table tbl;
2553        bool res;
2554        char *iph, *ido, *npc, *idc, *par, *sft, *buffer;
2555
2556        if (!db.Open(usuario, pasguor, datasource, catalog)) {
2557                db.GetErrorErrStr(msglog);
2558                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2559                       __func__, __LINE__, msglog);
2560                return false;
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)) {
2567                liberaMemoria(iph);
2568                liberaMemoria(ido);
2569                syslog(LOG_ERR, "failed to register notification\n");
2570                return false;
2571        }
2572
2573        npc = copiaParametro("npc",ptrTrama); 
2574        idc = copiaParametro("idc",ptrTrama); // Toma identificador del Centro 
2575        par = copiaParametro("par",ptrTrama);
2576        sft = copiaParametro("sft",ptrTrama);
2577
2578        buffer = rTrim(leeArchivo(sft));
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){
2590                syslog(LOG_ERR, "cannot update software\n");
2591                return false;
2592        }
2593
2594        db.Close(); // Cierra conexión
2595        return true;
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:
2611//              true: Si el proceso es correcto
2612//              false: En caso de ocurrir algún error
2613//
2614//      Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla
2615// ________________________________________________________________________________________________________
2616bool actualizaSoftware(Database db, Table tbl, char *sft, char *par,char *ido,
2617                       char *npc, char *idc)
2618{
2619        int i, j, lon, aux, idperfilsoft, idnombreso;
2620        bool retval;
2621        char *wsft;
2622        int tbidsoftware[MAXSOFTWARE];
2623        char *tbSoftware[MAXSOFTWARE],msglog[LONSTD], sqlstr[LONSQL], strInt[LONINT], *idsoftwares;
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
2630        if (!db.Execute(sqlstr, tbl)) {
2631                db.GetErrorErrStr(msglog);
2632                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2633                       __func__, __LINE__, msglog);
2634                return false;
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);
2640                        og_info(msglog);
2641                        return false;
2642                }
2643                if (aux == atoi(par)) { // Se encuentra la partición
2644                        if (!tbl.Get("idperfilsoft", idperfilsoft)) {
2645                                tbl.GetErrorErrStr(msglog);
2646                                og_info(msglog);
2647                                return false;
2648                        }
2649                        break;
2650                }
2651                tbl.MoveNext();
2652        }
2653        wsft=escaparCadena(sft); // Codificar comillas simples
2654        if(!wsft)
2655                return false;
2656
2657        /* Recorre componentes software*/
2658        lon = splitCadena(tbSoftware, wsft, '\n');
2659
2660        if (lon == 0)
2661                return true; // No hay lineas que procesar
2662        if (lon > MAXSOFTWARE)
2663                lon = MAXSOFTWARE; // Limita el número de componentes software
2664
2665        for (i = 0; i < lon; i++) {
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
2672                sprintf(sqlstr,
2673                                "SELECT idsoftware FROM softwares WHERE descripcion ='%s'",
2674                                rTrim(tbSoftware[i]));
2675
2676                if (!db.Execute(sqlstr, tbl)) {
2677                        db.GetErrorErrStr(msglog);
2678                        syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2679                               __func__, __LINE__, msglog);
2680                        return false;
2681                }
2682
2683                if (tbl.ISEOF()) { //  Software NO existente
2684                        sprintf(sqlstr, "INSERT INTO softwares (idtiposoftware,descripcion,idcentro,grupoid)"
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
2689                                og_info(msglog);
2690                                return false;
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
2696                                og_info(msglog);
2697                                return false;
2698                        }
2699                        if (!tbl.ISEOF()) { // Si existe registro
2700                                if (!tbl.Get("identificador", tbidsoftware[i])) {
2701                                        tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2702                                        og_info(msglog);
2703                                        return false;
2704                                }
2705                        }
2706                } else {
2707                        if (!tbl.Get("idsoftware", tbidsoftware[i])) { // Toma dato
2708                                tbl.GetErrorErrStr(msglog); // Error al acceder al registro
2709                                og_info(msglog);
2710                                return false;
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) {
2731                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
2732                return false;
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
2739        if (!cuestionPerfilSoftware(db, tbl, idc, ido, idperfilsoft, idnombreso, idsoftwares, 
2740                        npc, par, tbidsoftware, lon)) {
2741                syslog(LOG_ERR, "cannot update software\n");
2742                og_info(msglog);
2743                retval=false;
2744        }
2745        else {
2746                retval=true;
2747        }
2748        liberaMemoria(wsft);
2749        liberaMemoria(idsoftwares);
2750        return (retval);
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
2760//              - idnombreso: Identificador del sistema operativo
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:
2767//              true: Si el proceso es correcto
2768//              false: En caso de ocurrir algún error
2769//
2770//      Versión 1.1.0: Se incluye el sistema operativo. Autora: Irina Gómez - ETSII Universidad Sevilla
2771//_________________________________________________________________________________________________________
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{
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) {
2782                syslog(LOG_ERR, "%s:%d OOM\n", __FILE__, __LINE__);
2783                return false;
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);
2793
2794        if (!db.Execute(sqlstr, tbl)) {
2795                db.GetErrorErrStr(msglog);
2796                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2797                       __func__, __LINE__, msglog);
2798                liberaMemoria(sqlstr);
2799                return false;
2800        }
2801        if (tbl.ISEOF()) { // No existe un perfil software con esos componentes de componentes software, lo crea
2802                sprintf(sqlstr, "INSERT perfilessoft  (descripcion, idcentro, grupoid, idnombreso)"
2803                                " VALUES('Perfil Software (%s, Part:%s) ',%s,0,%i)", npc, par, idc,idnombreso);
2804                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2805                        db.GetErrorErrStr(msglog);
2806                        og_info(msglog);
2807                        return false;
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);
2813                        og_info(msglog);
2814                        liberaMemoria(sqlstr);
2815                        return false;
2816                }
2817                if (!tbl.ISEOF()) { // Si existe registro
2818                        if (!tbl.Get("identificador", nwidperfilsoft)) {
2819                                tbl.GetErrorErrStr(msglog);
2820                                og_info(msglog);
2821                                liberaMemoria(sqlstr);
2822                                return false;
2823                        }
2824                }
2825                // Crea la relación entre perfiles y componenetes software
2826                for (i = 0; i < lon; i++) {
2827                        sprintf(sqlstr, "INSERT perfilessoft_softwares (idperfilsoft,idsoftware)"
2828                                                " VALUES(%d,%d)", nwidperfilsoft, tbidsoftware[i]);
2829                        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2830                                db.GetErrorErrStr(msglog);
2831                                og_info(msglog);
2832                                liberaMemoria(sqlstr);
2833                                return false;
2834                        }
2835                }
2836        } else { // Existe un perfil con todos esos componentes
2837                if (!tbl.Get("idperfilsoft", nwidperfilsoft)) {
2838                        tbl.GetErrorErrStr(msglog);
2839                        og_info(msglog);
2840                        liberaMemoria(sqlstr);
2841                        return false;
2842                }
2843        }
2844
2845        if (idperfilsoftware != nwidperfilsoft) { // No coinciden los perfiles
2846                // Actualiza el identificador del perfil software del ordenador
2847                sprintf(sqlstr, "UPDATE ordenadores_particiones SET idperfilsoft=%d,idimagen=0"
2848                                " WHERE idordenador=%s AND numpar=%s", nwidperfilsoft, ido, par);
2849                if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2850                        db.GetErrorErrStr(msglog);
2851                        og_info(msglog);
2852                        liberaMemoria(sqlstr);
2853                        return false;
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);
2866                og_info(msglog);
2867                liberaMemoria(sqlstr);
2868                return false;
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);
2877                og_info(msglog);
2878                liberaMemoria(sqlstr);
2879                return false;
2880        }
2881        /* Eliminar Relación de softwares con Perfiles software que quedan húerfanos */
2882        sprintf(sqlstr, "DELETE FROM perfilessoft_softwares WHERE idperfilsoft NOT IN"
2883                        " (SELECT idperfilsoft from perfilessoft)");
2884        if (!db.Execute(sqlstr, tbl)) { // Error al insertar
2885                db.GetErrorErrStr(msglog);
2886                og_info(msglog);
2887                liberaMemoria(sqlstr);
2888                return false;
2889        }
2890        liberaMemoria(sqlstr);
2891        return true;
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:
2902//              true: Si el proceso es correcto
2903//              false: En caso de ocurrir algún error
2904// ________________________________________________________________________________________________________
2905static bool enviaArchivo(TRAMA *ptrTrama, struct og_client *cli)
2906{
2907        int socket_c = og_client_socket(cli);
2908        char *nfl;
2909
2910        // Toma parámetros
2911        nfl = copiaParametro("nfl",ptrTrama); // Toma nombre completo del archivo
2912        if (!sendArchivo(&socket_c, nfl)) {
2913                liberaMemoria(nfl);
2914                syslog(LOG_ERR, "Problem sending file\n");
2915                return false;
2916        }
2917        liberaMemoria(nfl);
2918        return true;
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:
2929//              true: Si el proceso es correcto
2930//              false: En caso de ocurrir algún error
2931// ________________________________________________________________________________________________________
2932static bool recibeArchivo(TRAMA *ptrTrama, struct og_client *cli)
2933{
2934        int socket_c = og_client_socket(cli);
2935        char *nfl;
2936
2937        // Toma parámetros
2938        nfl = copiaParametro("nfl",ptrTrama); // Toma nombre completo del archivo
2939        ptrTrama->tipo = MSG_NOTIFICACION;
2940        enviaFlag(&socket_c, ptrTrama);
2941        if (!recArchivo(&socket_c, nfl)) {
2942                liberaMemoria(nfl);
2943                syslog(LOG_ERR, "Problem receiving file\n");
2944                return false;
2945        }
2946        liberaMemoria(nfl);
2947        return true;
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:
2959//              true: Si el proceso es correcto
2960//              false: En caso de ocurrir algún error
2961// ________________________________________________________________________________________________________
2962static bool envioProgramacion(TRAMA *ptrTrama, struct og_client *cli)
2963{
2964        char *ptrIP[MAXIMOS_CLIENTES],*ptrMacs[MAXIMOS_CLIENTES];
2965        char sqlstr[LONSQL], msglog[LONSTD];
2966        char *idp,iph[LONIP],mac[LONMAC];
2967        Database db;
2968        Table tbl;
2969        int idx,idcomando,lon;
2970
2971        if (!db.Open(usuario, pasguor, datasource, catalog)) {
2972                db.GetErrorErrStr(msglog);
2973                syslog(LOG_ERR, "cannot open connection database (%s:%d) %s\n",
2974                       __func__, __LINE__, msglog);
2975                return false;
2976        }
2977
2978        idp = copiaParametro("idp",ptrTrama); // Toma identificador de la programación de la tabla acciones
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);
2983       
2984        liberaMemoria(idp);
2985
2986        if (!db.Execute(sqlstr, tbl)) {
2987                db.GetErrorErrStr(msglog);
2988                syslog(LOG_ERR, "failed to query database (%s:%d) %s\n",
2989                       __func__, __LINE__, msglog);
2990                return false;
2991        }
2992        db.Close();
2993        if(tbl.ISEOF())
2994                return true; // No existen registros
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);
3005                        syslog(LOG_ERR, "cannot find ip column in table: %s\n",
3006                               msglog);
3007                        return false;
3008                }
3009                if (!tbl.Get("idcomando", idcomando)) {
3010                        tbl.GetErrorErrStr(msglog);
3011                        syslog(LOG_ERR, "cannot find idcomando column in table: %s\n",
3012                               msglog);
3013                        return false;
3014                }
3015                if(idcomando==1){ // Arrancar
3016                        if (!tbl.Get("mac", mac)) {
3017                                tbl.GetErrorErrStr(msglog);
3018                                syslog(LOG_ERR, "cannot find mac column in table: %s\n",
3019                                       msglog);
3020                                return false;
3021                        }
3022
3023                        lon = splitCadena(ptrIP, iph, ';');
3024                        lon = splitCadena(ptrMacs, mac, ';');
3025
3026                        // Se manda por broadcast y por unicast
3027                        if (!Levanta(ptrIP, ptrMacs, lon, (char*)"1"))
3028                                return false;
3029
3030                        if (!Levanta(ptrIP, ptrMacs, lon, (char*)"2"))
3031                                return false;
3032
3033                }
3034                if (clienteDisponible(iph, &idx)) { // Si el cliente puede recibir comandos
3035                        int sock = tbsockets[idx].cli ? tbsockets[idx].cli->io.fd : -1;
3036
3037                        strcpy(tbsockets[idx].estado, CLIENTE_OCUPADO); // Actualiza el estado del cliente
3038                        if (sock >= 0 && !mandaTrama(&sock, ptrTrama)) {
3039                                syslog(LOG_ERR, "failed to send response: %s\n",
3040                                       strerror(errno));
3041                        }
3042                        //close(tbsockets[idx].sock); // Cierra el socket del cliente hasta nueva disponibilidad
3043                }
3044                tbl.MoveNext();
3045        }
3046        return true; // No existen registros
3047}
3048
3049// This object stores function handler for messages
3050static struct {
3051        const char *nf; // Nombre de la función
3052        bool (*fcn)(TRAMA *, struct og_client *cli);
3053} tbfuncionesServer[] = {
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,      },
3082        { NULL,                                 NULL,                   },
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:
3093//              true: Si el proceso es correcto
3094//              false: En caso de ocurrir algún error
3095// ________________________________________________________________________________________________________
3096static void gestionaTrama(TRAMA *ptrTrama, struct og_client *cli)
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
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);
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                                }
3120                                break;
3121                        }
3122                }
3123                if (!tbfuncionesServer[i].fcn)
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));
3127
3128                liberaMemoria(nfn);
3129        }
3130}
3131
3132static void og_client_release(struct ev_loop *loop, struct og_client *cli)
3133{
3134        if (cli->keepalive_idx >= 0) {
3135                syslog(LOG_DEBUG, "closing keepalive connection for %s:%hu in slot %d\n",
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) {
3152                syslog(LOG_DEBUG, "closing old keepalive connection for %s:%hu\n",
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
3167static int og_client_state_recv_hdr(struct og_client *cli)
3168{
3169        char hdrlen[LONHEXPRM];
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
3198static TRAMA *og_msg_alloc(char *data, unsigned int len)
3199{
3200        TRAMA *ptrTrama;
3201
3202        ptrTrama = (TRAMA *)reservaMemoria(sizeof(TRAMA));
3203        if (!ptrTrama) {
3204                syslog(LOG_ERR, "OOM\n");
3205                return NULL;
3206        }
3207
3208        initParametros(ptrTrama, len);
3209        memcpy(ptrTrama, "@JMMLCAMDJ_MCDJ", LONGITUD_CABECERATRAMA);
3210        memcpy(ptrTrama->parametros, data, len);
3211        ptrTrama->lonprm = len;
3212
3213        return ptrTrama;
3214}
3215
3216static void og_msg_free(TRAMA *ptrTrama)
3217{
3218        liberaMemoria(ptrTrama->parametros);
3219        liberaMemoria(ptrTrama);
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);
3238
3239        return 1;
3240}
3241
3242#define OG_CLIENTS_MAX  4096
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};
3252
3253struct og_sync_params {
3254        const char      *sync;
3255        const char      *diff;
3256        const char      *remove;
3257        const char      *compress;
3258        const char      *cleanup;
3259        const char      *cache;
3260        const char      *cleanup_cache;
3261        const char      *remove_dst;
3262        const char      *diff_id;
3263        const char      *diff_name;
3264        const char      *path;
3265        const char      *method;
3266};
3267
3268struct og_msg_params {
3269        const char      *ips_array[OG_CLIENTS_MAX];
3270        const char      *mac_array[OG_CLIENTS_MAX];
3271        unsigned int    ips_array_len;
3272        const char      *wol_type;
3273        char            run_cmd[4096];
3274        const char      *disk;
3275        const char      *partition;
3276        const char      *repository;
3277        const char      *name;
3278        const char      *id;
3279        const char      *code;
3280        const char      *type;
3281        const char      *profile;
3282        const char      *cache;
3283        const char      *cache_size;
3284        struct og_partition     partition_setup[OG_PARTITION_MAX];
3285        struct og_sync_params sync_setup;
3286};
3287
3288static int og_json_parse_clients(json_t *element, struct og_msg_params *params)
3289{
3290        unsigned int i;
3291        json_t *k;
3292
3293        if (json_typeof(element) != JSON_ARRAY)
3294                return -1;
3295
3296        for (i = 0; i < json_array_size(element); i++) {
3297                k = json_array_get(element, i);
3298                if (json_typeof(k) != JSON_STRING)
3299                        return -1;
3300
3301                params->ips_array[params->ips_array_len++] =
3302                        json_string_value(k);
3303        }
3304        return 0;
3305}
3306
3307static int og_json_parse_string(json_t *element, const char **str)
3308{
3309        if (json_typeof(element) != JSON_STRING)
3310                return -1;
3311
3312        *str = json_string_value(element);
3313        return 0;
3314}
3315
3316static int og_json_parse_sync_params(json_t *element, og_sync_params *params)
3317{
3318        const char *key;
3319        json_t *value;
3320        int err = 0;
3321
3322        json_object_foreach(element, key, value) {
3323                if (!strcmp(key, "sync"))
3324                        err = og_json_parse_string(value, &params->sync);
3325                else if (!strcmp(key, "diff"))
3326                        err = og_json_parse_string(value, &params->diff);
3327                else if (!strcmp(key, "remove"))
3328                        err = og_json_parse_string(value, &params->remove);
3329                else if (!strcmp(key, "compress"))
3330                        err = og_json_parse_string(value, &params->compress);
3331                else if (!strcmp(key, "cleanup"))
3332                        err = og_json_parse_string(value, &params->cleanup);
3333                else if (!strcmp(key, "cache"))
3334                        err = og_json_parse_string(value, &params->cache);
3335                else if (!strcmp(key, "cleanup_cache"))
3336                        err = og_json_parse_string(value, &params->cleanup_cache);
3337                else if (!strcmp(key, "remove_dst"))
3338                        err = og_json_parse_string(value, &params->remove_dst);
3339                else if (!strcmp(key, "diff_id"))
3340                        err = og_json_parse_string(value, &params->diff_id);
3341                else if (!strcmp(key, "diff_name"))
3342                        err = og_json_parse_string(value, &params->diff_name);
3343                else if (!strcmp(key, "path"))
3344                        err = og_json_parse_string(value, &params->path);
3345                else if (!strcmp(key, "method"))
3346                        err = og_json_parse_string(value, &params->method);
3347
3348                if (err != 0)
3349                        return err;
3350        }
3351        return err;
3352}
3353
3354static int og_json_parse_partition(json_t *element, og_partition *part)
3355{
3356        const char *key;
3357        json_t *value;
3358        int err = 0;
3359
3360        json_object_foreach(element, key, value) {
3361                if (!strcmp(key, "partition"))
3362                        err = og_json_parse_string(value, &part->number);
3363                else if (!strcmp(key, "code"))
3364                        err = og_json_parse_string(value, &part->code);
3365                else if (!strcmp(key, "filesystem"))
3366                        err = og_json_parse_string(value, &part->filesystem);
3367                else if (!strcmp(key, "size"))
3368                        err = og_json_parse_string(value, &part->size);
3369                else if (!strcmp(key, "format"))
3370                        err = og_json_parse_string(value, &part->format);
3371
3372                if (err < 0)
3373                        return err;
3374        }
3375        return err;
3376}
3377
3378static int og_json_parse_partition_setup(json_t *element, og_partition *part)
3379{
3380        unsigned int i;
3381        json_t *k;
3382
3383        if (json_typeof(element) != JSON_ARRAY)
3384                return -1;
3385
3386        for (i = 0; i < json_array_size(element) && i < OG_PARTITION_MAX; ++i) {
3387                k = json_array_get(element, i);
3388
3389                if (json_typeof(k) != JSON_OBJECT)
3390                        return -1;
3391
3392                if (og_json_parse_partition(k, part + i) != 0)
3393                        return -1;
3394        }
3395        return 0;
3396}
3397
3398static int og_cmd_legacy_send(struct og_msg_params *params, const char *cmd,
3399                              const char *state)
3400{
3401        char buf[4096] = {};
3402        int len, err = 0;
3403        TRAMA *msg;
3404
3405        len = snprintf(buf, sizeof(buf), "nfn=%s\r", cmd);
3406
3407        msg = og_msg_alloc(buf, len);
3408        if (!msg)
3409                return -1;
3410
3411        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
3412                         state, msg))
3413                err = -1;
3414
3415        og_msg_free(msg);
3416
3417        return err;
3418}
3419
3420static int og_cmd_post_clients(json_t *element, struct og_msg_params *params)
3421{
3422        const char *key;
3423        json_t *value;
3424        int err = 0;
3425
3426        if (json_typeof(element) != JSON_OBJECT)
3427                return -1;
3428
3429        json_object_foreach(element, key, value) {
3430                if (!strcmp(key, "clients"))
3431                        err = og_json_parse_clients(value, params);
3432
3433                if (err < 0)
3434                        break;
3435        }
3436
3437        return og_cmd_legacy_send(params, "Sondeo", CLIENTE_APAGADO);
3438}
3439
3440struct og_buffer {
3441        char    *data;
3442        int     len;
3443};
3444
3445static int og_json_dump_clients(const char *buffer, size_t size, void *data)
3446{
3447        struct og_buffer *og_buffer = (struct og_buffer *)data;
3448
3449        memcpy(og_buffer->data + og_buffer->len, buffer, size);
3450        og_buffer->len += size;
3451
3452        return 0;
3453}
3454
3455static int og_cmd_get_clients(json_t *element, struct og_msg_params *params,
3456                              char *buffer_reply)
3457{
3458        json_t *root, *array, *addr, *state, *object;
3459        struct og_buffer og_buffer = {
3460                .data   = buffer_reply,
3461        };
3462        int i;
3463
3464        array = json_array();
3465        if (!array)
3466                return -1;
3467
3468        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
3469                if (tbsockets[i].ip[0] == '\0')
3470                        continue;
3471
3472                object = json_object();
3473                if (!object) {
3474                        json_decref(array);
3475                        return -1;
3476                }
3477                addr = json_string(tbsockets[i].ip);
3478                if (!addr) {
3479                        json_decref(object);
3480                        json_decref(array);
3481                        return -1;
3482                }
3483                json_object_set_new(object, "addr", addr);
3484
3485                state = json_string(tbsockets[i].estado);
3486                if (!state) {
3487                        json_decref(object);
3488                        json_decref(array);
3489                        return -1;
3490                }
3491                json_object_set_new(object, "state", state);
3492
3493                json_array_append_new(array, object);
3494        }
3495        root = json_pack("{s:o}", "clients", array);
3496        if (!root) {
3497                json_decref(array);
3498                return -1;
3499        }
3500
3501        json_dump_callback(root, og_json_dump_clients, &og_buffer, 0);
3502        json_decref(root);
3503
3504        return 0;
3505}
3506
3507static int og_json_parse_target(json_t *element, struct og_msg_params *params)
3508{
3509        const char *key;
3510        json_t *value;
3511
3512        if (json_typeof(element) != JSON_OBJECT) {
3513                return -1;
3514        }
3515
3516        json_object_foreach(element, key, value) {
3517                if (!strcmp(key, "addr")) {
3518                        if (json_typeof(value) != JSON_STRING)
3519                                return -1;
3520
3521                        params->ips_array[params->ips_array_len] =
3522                                json_string_value(value);
3523                } else if (!strcmp(key, "mac")) {
3524                        if (json_typeof(value) != JSON_STRING)
3525                                return -1;
3526
3527                        params->mac_array[params->ips_array_len] =
3528                                json_string_value(value);
3529                }
3530        }
3531
3532        return 0;
3533}
3534
3535static int og_json_parse_targets(json_t *element, struct og_msg_params *params)
3536{
3537        unsigned int i;
3538        json_t *k;
3539        int err;
3540
3541        if (json_typeof(element) != JSON_ARRAY)
3542                return -1;
3543
3544        for (i = 0; i < json_array_size(element); i++) {
3545                k = json_array_get(element, i);
3546
3547                if (json_typeof(k) != JSON_OBJECT)
3548                        return -1;
3549
3550                err = og_json_parse_target(k, params);
3551                if (err < 0)
3552                        return err;
3553
3554                params->ips_array_len++;
3555        }
3556        return 0;
3557}
3558
3559static int og_json_parse_type(json_t *element, struct og_msg_params *params)
3560{
3561        const char *type;
3562
3563        if (json_typeof(element) != JSON_STRING)
3564                return -1;
3565
3566        params->wol_type = json_string_value(element);
3567
3568        type = json_string_value(element);
3569        if (!strcmp(type, "unicast"))
3570                params->wol_type = "2";
3571        else if (!strcmp(type, "broadcast"))
3572                params->wol_type = "1";
3573
3574        return 0;
3575}
3576
3577static int og_cmd_wol(json_t *element, struct og_msg_params *params)
3578{
3579        const char *key;
3580        json_t *value;
3581        int err = 0;
3582
3583        if (json_typeof(element) != JSON_OBJECT)
3584                return -1;
3585
3586        json_object_foreach(element, key, value) {
3587                if (!strcmp(key, "clients")) {
3588                        err = og_json_parse_targets(value, params);
3589                } else if (!strcmp(key, "type")) {
3590                        err = og_json_parse_type(value, params);
3591                }
3592
3593                if (err < 0)
3594                        break;
3595        }
3596
3597        if (!Levanta((char **)params->ips_array, (char **)params->mac_array,
3598                     params->ips_array_len, (char *)params->wol_type))
3599                return -1;
3600
3601        return 0;
3602}
3603
3604static int og_json_parse_run(json_t *element, struct og_msg_params *params)
3605{
3606        if (json_typeof(element) != JSON_STRING)
3607                return -1;
3608
3609        snprintf(params->run_cmd, sizeof(params->run_cmd), "%s",
3610                 json_string_value(element));
3611
3612        return 0;
3613}
3614
3615static int og_cmd_run_post(json_t *element, struct og_msg_params *params)
3616{
3617        char buf[4096] = {}, iph[4096] = {};
3618        int err = 0, len;
3619        const char *key;
3620        unsigned int i;
3621        json_t *value;
3622        TRAMA *msg;
3623
3624        if (json_typeof(element) != JSON_OBJECT)
3625                return -1;
3626
3627        json_object_foreach(element, key, value) {
3628                if (!strcmp(key, "clients"))
3629                        err = og_json_parse_clients(value, params);
3630                if (!strcmp(key, "run"))
3631                        err = og_json_parse_run(value, params);
3632
3633                if (err < 0)
3634                        break;
3635        }
3636
3637        for (i = 0; i < params->ips_array_len; i++) {
3638                len = snprintf(iph + strlen(iph), sizeof(iph), "%s;",
3639                               params->ips_array[i]);
3640        }
3641        len = snprintf(buf, sizeof(buf), "nfn=ConsolaRemota\riph=%s\rscp=%s\r",
3642                       iph, params->run_cmd);
3643
3644        msg = og_msg_alloc(buf, len);
3645        if (!msg)
3646                return -1;
3647
3648        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
3649                         CLIENTE_OCUPADO, msg))
3650                err = -1;
3651
3652        og_msg_free(msg);
3653
3654        if (err < 0)
3655                return err;
3656
3657        for (i = 0; i < params->ips_array_len; i++) {
3658                char filename[4096];
3659                FILE *f;
3660
3661                sprintf(filename, "/tmp/_Seconsola_%s", params->ips_array[i]);
3662                f = fopen(filename, "wt");
3663                fclose(f);
3664        }
3665
3666        return 0;
3667}
3668
3669static int og_cmd_run_get(json_t *element, struct og_msg_params *params,
3670                          char *buffer_reply)
3671{
3672        struct og_buffer og_buffer = {
3673                .data   = buffer_reply,
3674        };
3675        json_t *root, *value, *array;
3676        const char *key;
3677        unsigned int i;
3678        int err = 0;
3679
3680        if (json_typeof(element) != JSON_OBJECT)
3681                return -1;
3682
3683        json_object_foreach(element, key, value) {
3684                if (!strcmp(key, "clients"))
3685                        err = og_json_parse_clients(value, params);
3686
3687                if (err < 0)
3688                        return err;
3689        }
3690
3691        array = json_array();
3692        if (!array)
3693                return -1;
3694
3695        for (i = 0; i < params->ips_array_len; i++) {
3696                json_t *object, *output, *addr;
3697                char data[4096] = {};
3698                char filename[4096];
3699                int fd, numbytes;
3700
3701                sprintf(filename, "/tmp/_Seconsola_%s", params->ips_array[i]);
3702
3703                fd = open(filename, O_RDONLY);
3704                if (!fd)
3705                        return -1;
3706
3707                numbytes = read(fd, data, sizeof(data));
3708                if (numbytes < 0) {
3709                        close(fd);
3710                        return -1;
3711                }
3712                data[sizeof(data) - 1] = '\0';
3713                close(fd);
3714
3715                object = json_object();
3716                if (!object) {
3717                        json_decref(array);
3718                        return -1;
3719                }
3720                addr = json_string(params->ips_array[i]);
3721                if (!addr) {
3722                        json_decref(object);
3723                        json_decref(array);
3724                        return -1;
3725                }
3726                json_object_set_new(object, "addr", addr);
3727
3728                output = json_string(data);
3729                if (!output) {
3730                        json_decref(object);
3731                        json_decref(array);
3732                        return -1;
3733                }
3734                json_object_set_new(object, "output", output);
3735
3736                json_array_append_new(array, object);
3737        }
3738
3739        root = json_pack("{s:o}", "clients", array);
3740        if (!root)
3741                return -1;
3742
3743        json_dump_callback(root, og_json_dump_clients, &og_buffer, 0);
3744        json_decref(root);
3745
3746        return 0;
3747}
3748
3749static int og_cmd_session(json_t *element, struct og_msg_params *params)
3750{
3751        char buf[4096], iph[4096];
3752        int err = 0, len;
3753        const char *key;
3754        unsigned int i;
3755        json_t *value;
3756        TRAMA *msg;
3757
3758        if (json_typeof(element) != JSON_OBJECT)
3759                return -1;
3760
3761        json_object_foreach(element, key, value) {
3762                if (!strcmp(key, "clients"))
3763                        err = og_json_parse_clients(value, params);
3764                else if (!strcmp(key, "disk"))
3765                        err = og_json_parse_string(value, &params->disk);
3766                else if (!strcmp(key, "partition"))
3767                        err = og_json_parse_string(value, &params->partition);
3768
3769                if (err < 0)
3770                        return err;
3771        }
3772
3773        for (i = 0; i < params->ips_array_len; i++) {
3774                snprintf(iph + strlen(iph), sizeof(iph), "%s;",
3775                         params->ips_array[i]);
3776        }
3777        len = snprintf(buf, sizeof(buf),
3778                       "nfn=IniciarSesion\riph=%s\rdsk=%s\rpar=%s\r",
3779                       iph, params->disk, params->partition);
3780
3781        msg = og_msg_alloc(buf, len);
3782        if (!msg)
3783                return -1;
3784
3785        if (!og_send_cmd((char **)params->ips_array, params->ips_array_len,
3786                         CLIENTE_APAGADO, msg))
3787                err = -1;
3788
3789        og_msg_free(msg);
3790
3791        return 0;
3792}
3793
3794static int og_cmd_poweroff(json_t *element, struct og_msg_params *params)
3795{
3796        const char *key;
3797        json_t *value;
3798        int err = 0;
3799
3800        if (json_typeof(element) != JSON_OBJECT)
3801                return -1;
3802
3803        json_object_foreach(element, key, value) {
3804                if (!strcmp(key, "clients"))
3805                        err = og_json_parse_clients(value, params);
3806
3807                if (err < 0)
3808                        break;
3809        }
3810
3811        return og_cmd_legacy_send(params, "Apagar", CLIENTE_OCUPADO);
3812}
3813
3814static int og_cmd_refresh(json_t *element, struct og_msg_params *params)
3815{
3816        const char *key;
3817        json_t *value;
3818        int err = 0;
3819
3820        if (json_typeof(element) != JSON_OBJECT)
3821                return -1;
3822
3823        json_object_foreach(element, key, value) {
3824                if (!strcmp(key, "clients"))
3825                        err = og_json_parse_clients(value, params);
3826
3827                if (err < 0)
3828                        break;
3829        }
3830
3831        return og_cmd_legacy_send(params, "Actualizar", CLIENTE_APAGADO);
3832}
3833
3834static int og_cmd_reboot(json_t *element, struct og_msg_params *params)
3835{
3836        const char *key;
3837        json_t *value;
3838        int err = 0;
3839
3840        if (json_typeof(element) != JSON_OBJECT)
3841                return -1;
3842
3843        json_object_foreach(element, key, value) {
3844                if (!strcmp(key, "clients"))
3845                        err = og_json_parse_clients(value, params);
3846
3847                if (err < 0)
3848                        break;
3849        }
3850
3851        return og_cmd_legacy_send(params, "Reiniciar", CLIENTE_OCUPADO);
3852}
3853
3854static int og_cmd_stop(json_t *element, struct og_msg_params *params)
3855{
3856        const char *key;
3857        json_t *value;
3858        int err = 0;
3859
3860        if (json_typeof(element) != JSON_OBJECT)
3861                return -1;
3862
3863        json_object_foreach(element, key, value) {
3864                if (!strcmp(key, "clients"))
3865                        err = og_json_parse_clients(value, params);
3866
3867                if (err < 0)
3868                        break;
3869        }
3870
3871        return og_cmd_legacy_send(params, "Purgar", CLIENTE_APAGADO);
3872}
3873
3874static int og_cmd_hardware(json_t *element, struct og_msg_params *params)
3875{
3876        const char *key;
3877        json_t *value;
3878        int err = 0;
3879
3880        if (json_typeof(element) != JSON_OBJECT)
3881                return -1;
3882
3883        json_object_foreach(element, key, value) {
3884                if (!strcmp(key, "clients"))
3885                        err = og_json_parse_clients(value, params);
3886
3887                if (err < 0)
3888                        break;
3889        }
3890
3891        return og_cmd_legacy_send(params, "InventarioHardware",
3892                                  CLIENTE_OCUPADO);
3893}
3894
3895static int og_cmd_software(json_t *element, struct og_msg_params *params)
3896{
3897        const char *key;
3898        json_t *value;
3899        int err = 0;
3900
3901        if (json_typeof(element) != JSON_OBJECT)
3902                return -1;
3903
3904        json_object_foreach(element, key, value) {
3905                if (!strcmp(key, "clients"))
3906                        err = og_json_parse_clients(value, params);
3907
3908                if (err < 0)
3909                        break;
3910        }
3911
3912        return og_cmd_legacy_send(params, "InventarioSoftware",
3913                                  CLIENTE_OCUPADO);
3914}
3915
3916static int og_cmd_create_image(json_t *element, struct og_msg_params *params)
3917{
3918        char buf[4096] = {};
3919        int err = 0, len;
3920        const char *key;
3921        json_t *value;
3922        TRAMA *msg;
3923
3924        if (json_typeof(element) != JSON_OBJECT)
3925                return -1;
3926
3927        json_object_foreach(element, key, value) {
3928                if (!strcmp(key, "disk"))
3929                        err = og_json_parse_string(value, &params->disk);
3930                else if (!strcmp(key, "partition"))
3931                        err = og_json_parse_string(value, &params->partition);
3932                else if (!strcmp(key, "name"))
3933                        err = og_json_parse_string(value, &params->name);
3934                else if (!strcmp(key, "repository"))
3935                        err = og_json_parse_string(value, &params->repository);
3936                else if (!strcmp(key, "clients"))
3937                        err = og_json_parse_clients(value, params);
3938                else if (!strcmp(key, "id"))
3939                        err = og_json_parse_string(value, &params->id);
3940                else if (!strcmp(key, "code"))
3941                        err = og_json_parse_string(value, &params->code);
3942
3943                if (err < 0)
3944                        break;
3945        }
3946
3947        len = snprintf(buf, sizeof(buf),
3948                        "nfn=CrearImagen\rdsk=%s\rpar=%s\rcpt=%s\ridi=%s\rnci=%s\ripr=%s\r",
3949                        params->disk, params->partition, params->code,
3950                        params->id, params->name, params->repository);
3951
3952        msg = og_msg_alloc(buf, len);
3953        if (!msg)
3954                return -1;
3955
3956        og_send_cmd((char **)params->ips_array, params->ips_array_len,
3957                    CLIENTE_OCUPADO, msg);
3958
3959        og_msg_free(msg);
3960
3961        return 0;
3962}
3963
3964static int og_cmd_restore_image(json_t *element, struct og_msg_params *params)
3965{
3966        char buf[4096] = {};
3967        int err = 0, len;
3968        const char *key;
3969        json_t *value;
3970        TRAMA *msg;
3971
3972        if (json_typeof(element) != JSON_OBJECT)
3973                return -1;
3974
3975        json_object_foreach(element, key, value) {
3976                if (!strcmp(key, "disk"))
3977                        err = og_json_parse_string(value, &params->disk);
3978                else if (!strcmp(key, "partition"))
3979                        err = og_json_parse_string(value, &params->partition);
3980                else if (!strcmp(key, "name"))
3981                        err = og_json_parse_string(value, &params->name);
3982                else if (!strcmp(key, "repository"))
3983                        err = og_json_parse_string(value, &params->repository);
3984                else if (!strcmp(key, "clients"))
3985                        err = og_json_parse_clients(value, params);
3986                else if (!strcmp(key, "type"))
3987                        err = og_json_parse_string(value, &params->type);
3988                else if (!strcmp(key, "profile"))
3989                        err = og_json_parse_string(value, &params->profile);
3990                else if (!strcmp(key, "id"))
3991                        err = og_json_parse_string(value, &params->id);
3992
3993                if (err < 0)
3994                        break;
3995        }
3996
3997        len = snprintf(buf, sizeof(buf),
3998                       "nfn=RestaurarImagen\ridi=%s\rdsk=%s\rpar=%s\rifs=%s\r"
3999                       "nci=%s\ripr=%s\rptc=%s\r",
4000                       params->id, params->disk, params->partition,
4001                       params->profile, params->name,
4002                       params->repository, params->type);
4003
4004        msg = og_msg_alloc(buf, len);
4005        if (!msg)
4006                return -1;
4007
4008        og_send_cmd((char **)params->ips_array, params->ips_array_len,
4009                    CLIENTE_OCUPADO, msg);
4010
4011        og_msg_free(msg);
4012
4013        return 0;
4014}
4015
4016static int og_cmd_setup_image(json_t *element, struct og_msg_params *params)
4017{
4018        char buf[4096] = {};
4019        int err = 0, len;
4020        const char *key;
4021        json_t *value;
4022        TRAMA *msg;
4023
4024        if (json_typeof(element) != JSON_OBJECT)
4025                return -1;
4026
4027        json_object_foreach(element, key, value) {
4028                if (!strcmp(key, "clients"))
4029                        err = og_json_parse_clients(value, params);
4030                else if (!strcmp(key, "disk"))
4031                        err = og_json_parse_string(value, &params->disk);
4032                else if (!strcmp(key, "cache"))
4033                        err = og_json_parse_string(value, &params->cache);
4034                else if (!strcmp(key, "cache_size"))
4035                        err = og_json_parse_string(value, &params->cache_size);
4036                else if (!strcmp(key, "partition_setup"))
4037                        err = og_json_parse_partition_setup(value, params->partition_setup);
4038
4039                if (err < 0)
4040                        break;
4041        }
4042
4043        len = snprintf(buf, sizeof(buf),
4044                        "nfn=Configurar\rdsk=%s\rcfg=dis=%s*che=%s*tch=%s!",
4045                        params->disk, params->disk, params->cache, params->cache_size);
4046
4047        for (unsigned int i = 0; i < OG_PARTITION_MAX; ++i) {
4048                const og_partition *part = params->partition_setup + i;
4049
4050                len += snprintf(buf + strlen(buf), sizeof(buf),
4051                        "par=%s*cpt=%s*sfi=%s*tam=%s*ope=%s%%",
4052                        part->number, part->code, part->filesystem, part->size, part->format);
4053        }
4054
4055        msg = og_msg_alloc(buf, len + 1);
4056        if (!msg)
4057                return -1;
4058
4059        og_send_cmd((char **)params->ips_array, params->ips_array_len,
4060                        CLIENTE_OCUPADO, msg);
4061
4062        og_msg_free(msg);
4063
4064        return 0;
4065}
4066
4067static int og_cmd_create_basic_image(json_t *element, struct og_msg_params *params)
4068{
4069        char buf[4096] = {};
4070        int err = 0, len;
4071        const char *key;
4072        json_t *value;
4073        TRAMA *msg;
4074
4075        if (json_typeof(element) != JSON_OBJECT)
4076                return -1;
4077
4078        json_object_foreach(element, key, value) {
4079                if (!strcmp(key, "clients"))
4080                        err = og_json_parse_clients(value, params);
4081                else if (!strcmp(key, "disk"))
4082                        err = og_json_parse_string(value, &params->disk);
4083                else if (!strcmp(key, "partition"))
4084                        err = og_json_parse_string(value, &params->partition);
4085                else if (!strcmp(key, "code"))
4086                        err = og_json_parse_string(value, &params->code);
4087                else if (!strcmp(key, "id"))
4088                        err = og_json_parse_string(value, &params->id);
4089                else if (!strcmp(key, "name"))
4090                        err = og_json_parse_string(value, &params->name);
4091                else if (!strcmp(key, "repository"))
4092                        err = og_json_parse_string(value, &params->repository);
4093                else if (!strcmp(key, "sync_params"))
4094                        err = og_json_parse_sync_params(value, &(params->sync_setup));
4095
4096                if (err < 0)
4097                        break;
4098        }
4099
4100        len = snprintf(buf, sizeof(buf),
4101                       "nfn=CrearImagenBasica\rdsk=%s\rpar=%s\rcpt=%s\ridi=%s\r"
4102                       "nci=%s\ripr=%s\rrti=\rmsy=%s\rwhl=%s\reli=%s\rcmp=%s\rbpi=%s\r"
4103                       "cpc=%s\rbpc=%s\rnba=%s\r",
4104                       params->disk, params->partition, params->code, params->id,
4105                       params->name, params->repository, params->sync_setup.sync,
4106                       params->sync_setup.diff, params->sync_setup.remove,
4107                       params->sync_setup.compress, params->sync_setup.cleanup,
4108                       params->sync_setup.cache, params->sync_setup.cleanup_cache,
4109                       params->sync_setup.remove_dst);
4110
4111        msg = og_msg_alloc(buf, len);
4112        if (!msg)
4113                return -1;
4114
4115        og_send_cmd((char **)params->ips_array, params->ips_array_len,
4116                    CLIENTE_OCUPADO, msg);
4117
4118        og_msg_free(msg);
4119
4120        return 0;
4121}
4122
4123static int og_cmd_create_incremental_image(json_t *element, struct og_msg_params *params)
4124{
4125        char buf[4096] = {};
4126        int err = 0, len;
4127        const char *key;
4128        json_t *value;
4129        TRAMA *msg;
4130
4131        if (json_typeof(element) != JSON_OBJECT)
4132                return -1;
4133
4134        json_object_foreach(element, key, value) {
4135                if (!strcmp(key, "clients"))
4136                        err = og_json_parse_clients(value, params);
4137                else if (!strcmp(key, "disk"))
4138                        err = og_json_parse_string(value, &params->disk);
4139                else if (!strcmp(key, "partition"))
4140                        err = og_json_parse_string(value, &params->partition);
4141                else if (!strcmp(key, "id"))
4142                        err = og_json_parse_string(value, &params->id);
4143                else if (!strcmp(key, "name"))
4144                        err = og_json_parse_string(value, &params->name);
4145                else if (!strcmp(key, "repository"))
4146                        err = og_json_parse_string(value, &params->repository);
4147                else if (!strcmp(key, "sync_params"))
4148                        err = og_json_parse_sync_params(value, &(params->sync_setup));
4149
4150                if (err < 0)
4151                        break;
4152        }
4153
4154        len = snprintf(buf, sizeof(buf),
4155                       "nfn=CrearSoftIncremental\rdsk=%s\rpar=%s\ridi=%s\rnci=%s\r"
4156                       "rti=%s\ripr=%s\ridf=%s\rncf=%s\rmsy=%s\rwhl=%s\reli=%s\rcmp=%s\r"
4157                       "bpi=%s\rcpc=%s\rbpc=%s\rnba=%s\r",
4158                       params->disk, params->partition, params->id, params->name,
4159                       params->sync_setup.path, params->repository, params->sync_setup.diff_id,
4160                       params->sync_setup.diff_name, params->sync_setup.sync,
4161                       params->sync_setup.diff, params->sync_setup.remove_dst,
4162                       params->sync_setup.compress, params->sync_setup.cleanup,
4163                       params->sync_setup.cache, params->sync_setup.cleanup_cache,
4164                       params->sync_setup.remove_dst);
4165
4166        msg = og_msg_alloc(buf, len);
4167        if (!msg)
4168                return -1;
4169
4170        og_send_cmd((char **)params->ips_array, params->ips_array_len,
4171                    CLIENTE_OCUPADO, msg);
4172
4173        og_msg_free(msg);
4174
4175        return 0;
4176}
4177
4178static int og_cmd_restore_basic_image(json_t *element, struct og_msg_params *params)
4179{
4180        char buf[4096] = {};
4181        int err = 0, len;
4182        const char *key;
4183        json_t *value;
4184        TRAMA *msg;
4185
4186        if (json_typeof(element) != JSON_OBJECT)
4187                return -1;
4188
4189        json_object_foreach(element, key, value) {
4190                if (!strcmp(key, "clients"))
4191                        err = og_json_parse_clients(value, params);
4192                else if (!strcmp(key, "disk"))
4193                        err = og_json_parse_string(value, &params->disk);
4194                else if (!strcmp(key, "partition"))
4195                        err = og_json_parse_string(value, &params->partition);
4196                else if (!strcmp(key, "id"))
4197                        err = og_json_parse_string(value, &params->id);
4198                else if (!strcmp(key, "name"))
4199                        err = og_json_parse_string(value, &params->name);
4200                else if (!strcmp(key, "repository"))
4201                        err = og_json_parse_string(value, &params->repository);
4202                else if (!strcmp(key, "profile"))
4203                        err = og_json_parse_string(value, &params->profile);
4204                else if (!strcmp(key, "type"))
4205                        err = og_json_parse_string(value, &params->type);
4206                else if (!strcmp(key, "sync_params"))
4207                        err = og_json_parse_sync_params(value, &(params->sync_setup));
4208
4209                if (err < 0)
4210                        break;
4211        }
4212
4213        len = snprintf(buf, sizeof(buf),
4214                       "nfn=RestaurarImagenBasica\rdsk=%s\rpar=%s\ridi=%s\rnci=%s\r"
4215                           "ipr=%s\rifs=%s\rrti=%s\rmet=%s\rmsy=%s\rtpt=%s\rwhl=%s\r"
4216                           "eli=%s\rcmp=%s\rbpi=%s\rcpc=%s\rbpc=%s\rnba=%s\r",
4217                       params->disk, params->partition, params->id, params->name,
4218                           params->repository, params->profile, params->sync_setup.path,
4219                           params->sync_setup.method, params->sync_setup.sync, params->type,
4220                           params->sync_setup.diff, params->sync_setup.remove,
4221                       params->sync_setup.compress, params->sync_setup.cleanup,
4222                       params->sync_setup.cache, params->sync_setup.cleanup_cache,
4223                       params->sync_setup.remove_dst);
4224
4225        msg = og_msg_alloc(buf, len);
4226        if (!msg)
4227                return -1;
4228
4229        og_send_cmd((char **)params->ips_array, params->ips_array_len,
4230                    CLIENTE_OCUPADO, msg);
4231
4232        og_msg_free(msg);
4233
4234        return 0;
4235}
4236
4237static int og_client_method_not_found(struct og_client *cli)
4238{
4239        /* To meet RFC 7231, this function MUST generate an Allow header field
4240         * containing the correct methods. For example: "Allow: POST\r\n"
4241         */
4242        char buf[] = "HTTP/1.1 405 Method Not Allowed\r\n"
4243                     "Content-Length: 0\r\n\r\n";
4244
4245        send(og_client_socket(cli), buf, strlen(buf), 0);
4246
4247        return -1;
4248}
4249
4250static int og_client_bad_request(struct og_client *cli)
4251{
4252        char buf[] = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
4253
4254        send(og_client_socket(cli), buf, strlen(buf), 0);
4255
4256        return -1;
4257}
4258
4259static int og_client_not_found(struct og_client *cli)
4260{
4261        char buf[] = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
4262
4263        send(og_client_socket(cli), buf, strlen(buf), 0);
4264
4265        return -1;
4266}
4267
4268static int og_client_not_authorized(struct og_client *cli)
4269{
4270        char buf[] = "HTTP/1.1 401 Unauthorized\r\n"
4271                     "WWW-Authenticate: Basic\r\n"
4272                     "Content-Length: 0\r\n\r\n";
4273
4274        send(og_client_socket(cli), buf, strlen(buf), 0);
4275
4276        return -1;
4277}
4278
4279static int og_server_internal_error(struct og_client *cli)
4280{
4281        char buf[] = "HTTP/1.1 500 Internal Server Error\r\n"
4282                     "Content-Length: 0\r\n\r\n";
4283
4284        send(og_client_socket(cli), buf, strlen(buf), 0);
4285
4286        return -1;
4287}
4288
4289#define OG_MSG_RESPONSE_MAXLEN  65536
4290
4291static int og_client_ok(struct og_client *cli, char *buf_reply)
4292{
4293        char buf[OG_MSG_RESPONSE_MAXLEN] = {};
4294        int err = 0, len;
4295
4296        len = snprintf(buf, sizeof(buf),
4297                       "HTTP/1.1 200 OK\r\nContent-Length: %ld\r\n\r\n%s",
4298                       strlen(buf_reply), buf_reply);
4299        if (len >= (int)sizeof(buf))
4300                err = og_server_internal_error(cli);
4301
4302        send(og_client_socket(cli), buf, strlen(buf), 0);
4303
4304        return err;
4305}
4306
4307enum og_rest_method {
4308        OG_METHOD_GET   = 0,
4309        OG_METHOD_POST,
4310};
4311
4312static int og_client_state_process_payload_rest(struct og_client *cli)
4313{
4314        char buf_reply[OG_MSG_RESPONSE_MAXLEN] = {};
4315        struct og_msg_params params = {};
4316        enum og_rest_method method;
4317        const char *cmd, *body;
4318        json_error_t json_err;
4319        json_t *root = NULL;
4320        int err = 0;
4321
4322        syslog(LOG_DEBUG, "%s:%hu %.32s ...\n",
4323               inet_ntoa(cli->addr.sin_addr),
4324               ntohs(cli->addr.sin_port), cli->buf);
4325
4326        if (!strncmp(cli->buf, "GET", strlen("GET"))) {
4327                method = OG_METHOD_GET;
4328                cmd = cli->buf + strlen("GET") + 2;
4329        } else if (!strncmp(cli->buf, "POST", strlen("POST"))) {
4330                method = OG_METHOD_POST;
4331                cmd = cli->buf + strlen("POST") + 2;
4332        } else
4333                return og_client_method_not_found(cli);
4334
4335        body = strstr(cli->buf, "\r\n\r\n") + 4;
4336
4337        if (strcmp(cli->auth_token, auth_token)) {
4338                syslog(LOG_ERR, "wrong Authentication key\n");
4339                return og_client_not_authorized(cli);
4340        }
4341
4342        if (cli->content_length) {
4343                root = json_loads(body, 0, &json_err);
4344                if (!root) {
4345                        syslog(LOG_ERR, "malformed json line %d: %s\n",
4346                               json_err.line, json_err.text);
4347                        return og_client_not_found(cli);
4348                }
4349        }
4350
4351        if (!strncmp(cmd, "clients", strlen("clients"))) {
4352                if (method != OG_METHOD_POST &&
4353                    method != OG_METHOD_GET)
4354                        return og_client_method_not_found(cli);
4355
4356                if (method == OG_METHOD_POST && !root) {
4357                        syslog(LOG_ERR, "command clients with no payload\n");
4358                        return og_client_bad_request(cli);
4359                }
4360                switch (method) {
4361                case OG_METHOD_POST:
4362                        err = og_cmd_post_clients(root, &params);
4363                        break;
4364                case OG_METHOD_GET:
4365                        err = og_cmd_get_clients(root, &params, buf_reply);
4366                        break;
4367                }
4368        } else if (!strncmp(cmd, "wol", strlen("wol"))) {
4369                if (method != OG_METHOD_POST)
4370                        return og_client_method_not_found(cli);
4371
4372                if (!root) {
4373                        syslog(LOG_ERR, "command wol with no payload\n");
4374                        return og_client_bad_request(cli);
4375                }
4376                err = og_cmd_wol(root, &params);
4377        } else if (!strncmp(cmd, "shell/run", strlen("shell/run"))) {
4378                if (method != OG_METHOD_POST)
4379                        return og_client_method_not_found(cli);
4380
4381                if (!root) {
4382                        syslog(LOG_ERR, "command run with no payload\n");
4383                        return og_client_bad_request(cli);
4384                }
4385                err = og_cmd_run_post(root, &params);
4386        } else if (!strncmp(cmd, "shell/output", strlen("shell/output"))) {
4387                if (method != OG_METHOD_POST)
4388                        return og_client_method_not_found(cli);
4389
4390                if (!root) {
4391                        syslog(LOG_ERR, "command output with no payload\n");
4392                        return og_client_bad_request(cli);
4393                }
4394
4395                err = og_cmd_run_get(root, &params, buf_reply);
4396        } else if (!strncmp(cmd, "session", strlen("session"))) {
4397                if (method != OG_METHOD_POST)
4398                        return og_client_method_not_found(cli);
4399
4400                if (!root) {
4401                        syslog(LOG_ERR, "command session with no payload\n");
4402                        return og_client_bad_request(cli);
4403                }
4404                err = og_cmd_session(root, &params);
4405        } else if (!strncmp(cmd, "poweroff", strlen("poweroff"))) {
4406                if (method != OG_METHOD_POST)
4407                        return og_client_method_not_found(cli);
4408
4409                if (!root) {
4410                        syslog(LOG_ERR, "command poweroff with no payload\n");
4411                        return og_client_bad_request(cli);
4412                }
4413                err = og_cmd_poweroff(root, &params);
4414        } else if (!strncmp(cmd, "reboot", strlen("reboot"))) {
4415                if (method != OG_METHOD_POST)
4416                        return og_client_method_not_found(cli);
4417
4418                if (!root) {
4419                        syslog(LOG_ERR, "command reboot with no payload\n");
4420                        return og_client_bad_request(cli);
4421                }
4422                err = og_cmd_reboot(root, &params);
4423        } else if (!strncmp(cmd, "stop", strlen("stop"))) {
4424                if (method != OG_METHOD_POST)
4425                        return og_client_method_not_found(cli);
4426
4427                if (!root) {
4428                        syslog(LOG_ERR, "command stop with no payload\n");
4429                        return og_client_bad_request(cli);
4430                }
4431                err = og_cmd_stop(root, &params);
4432        } else if (!strncmp(cmd, "refresh", strlen("refresh"))) {
4433                if (method != OG_METHOD_POST)
4434                        return og_client_method_not_found(cli);
4435
4436                if (!root) {
4437                        syslog(LOG_ERR, "command refresh with no payload\n");
4438                        return og_client_bad_request(cli);
4439                }
4440                err = og_cmd_refresh(root, &params);
4441        } else if (!strncmp(cmd, "hardware", strlen("hardware"))) {
4442                if (method != OG_METHOD_POST)
4443                        return og_client_method_not_found(cli);
4444
4445                if (!root) {
4446                        syslog(LOG_ERR, "command hardware with no payload\n");
4447                        return og_client_bad_request(cli);
4448                }
4449                err = og_cmd_hardware(root, &params);
4450        } else if (!strncmp(cmd, "software", strlen("software"))) {
4451                if (method != OG_METHOD_POST)
4452                        return og_client_method_not_found(cli);
4453
4454                if (!root) {
4455                        syslog(LOG_ERR, "command software with no payload\n");
4456                        return og_client_bad_request(cli);
4457                }
4458                err = og_cmd_software(root, &params);
4459        } else if (!strncmp(cmd, "image/create/basic",
4460                            strlen("image/create/basic"))) {
4461                if (method != OG_METHOD_POST)
4462                        return og_client_method_not_found(cli);
4463
4464                if (!root) {
4465                        syslog(LOG_ERR, "command create with no payload\n");
4466                        return og_client_bad_request(cli);
4467                }
4468                err = og_cmd_create_basic_image(root, &params);
4469        } else if (!strncmp(cmd, "image/create/incremental",
4470                            strlen("image/create/incremental"))) {
4471                if (method != OG_METHOD_POST)
4472                        return og_client_method_not_found(cli);
4473
4474                if (!root) {
4475                        syslog(LOG_ERR, "command create with no payload\n");
4476                        return og_client_bad_request(cli);
4477                }
4478                err = og_cmd_create_incremental_image(root, &params);
4479        } else if (!strncmp(cmd, "image/create", strlen("image/create"))) {
4480                if (method != OG_METHOD_POST)
4481                        return og_client_method_not_found(cli);
4482
4483                if (!root) {
4484                        syslog(LOG_ERR, "command create with no payload\n");
4485                        return og_client_bad_request(cli);
4486                }
4487                err = og_cmd_create_image(root, &params);
4488        } else if (!strncmp(cmd, "image/restore/basic",
4489                                strlen("image/restore/basic"))) {
4490                if (method != OG_METHOD_POST)
4491                        return og_client_method_not_found(cli);
4492
4493                if (!root) {
4494                        syslog(LOG_ERR, "command create with no payload\n");
4495                        return og_client_bad_request(cli);
4496                }
4497                err = og_cmd_restore_basic_image(root, &params);
4498        } else if (!strncmp(cmd, "image/restore", strlen("image/restore"))) {
4499                if (method != OG_METHOD_POST)
4500                        return og_client_method_not_found(cli);
4501
4502                if (!root) {
4503                        syslog(LOG_ERR, "command create with no payload\n");
4504                        return og_client_bad_request(cli);
4505                }
4506                err = og_cmd_restore_image(root, &params);
4507        } else if (!strncmp(cmd, "image/setup", strlen("image/setup"))) {
4508                if (method != OG_METHOD_POST)
4509                        return og_client_method_not_found(cli);
4510
4511                if (!root) {
4512                        syslog(LOG_ERR, "command create with no payload\n");
4513                        return og_client_bad_request(cli);
4514                }
4515                err = og_cmd_setup_image(root, &params);
4516        } else {
4517                syslog(LOG_ERR, "unknown command: %.32s ...\n", cmd);
4518                err = og_client_not_found(cli);
4519        }
4520
4521        if (root)
4522                json_decref(root);
4523
4524        if (err < 0)
4525                return err;
4526
4527        err = og_client_ok(cli, buf_reply);
4528        if (err < 0) {
4529                syslog(LOG_ERR, "HTTP response to %s:%hu is too large\n",
4530                       inet_ntoa(cli->addr.sin_addr),
4531                       ntohs(cli->addr.sin_port));
4532        }
4533
4534        return err;
4535}
4536
4537static int og_client_state_recv_hdr_rest(struct og_client *cli)
4538{
4539        char *ptr;
4540
4541        ptr = strstr(cli->buf, "\r\n\r\n");
4542        if (!ptr)
4543                return 0;
4544
4545        cli->msg_len = ptr - cli->buf + 4;
4546
4547        ptr = strstr(cli->buf, "Content-Length: ");
4548        if (ptr) {
4549                sscanf(ptr, "Content-Length: %i[^\r\n]", &cli->content_length);
4550                if (cli->content_length < 0)
4551                        return -1;
4552                cli->msg_len += cli->content_length;
4553        }
4554
4555        ptr = strstr(cli->buf, "Authorization: ");
4556        if (ptr)
4557                sscanf(ptr, "Authorization: %63[^\r\n]", cli->auth_token);
4558
4559        return 1;
4560}
4561
4562static void og_client_read_cb(struct ev_loop *loop, struct ev_io *io, int events)
4563{
4564        struct og_client *cli;
4565        int ret;
4566
4567        cli = container_of(io, struct og_client, io);
4568
4569        if (events & EV_ERROR) {
4570                syslog(LOG_ERR, "unexpected error event from client %s:%hu\n",
4571                               inet_ntoa(cli->addr.sin_addr),
4572                               ntohs(cli->addr.sin_port));
4573                goto close;
4574        }
4575
4576        ret = recv(io->fd, cli->buf + cli->buf_len,
4577                   sizeof(cli->buf) - cli->buf_len, 0);
4578        if (ret <= 0) {
4579                if (ret < 0) {
4580                        syslog(LOG_ERR, "error reading from client %s:%hu (%s)\n",
4581                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port),
4582                               strerror(errno));
4583                } else {
4584                        syslog(LOG_DEBUG, "closed connection by %s:%hu\n",
4585                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4586                }
4587                goto close;
4588        }
4589
4590        if (cli->keepalive_idx >= 0)
4591                return;
4592
4593        ev_timer_again(loop, &cli->timer);
4594
4595        cli->buf_len += ret;
4596        if (cli->buf_len >= sizeof(cli->buf)) {
4597                syslog(LOG_ERR, "client request from %s:%hu is too long\n",
4598                       inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4599                goto close;
4600        }
4601
4602        switch (cli->state) {
4603        case OG_CLIENT_RECEIVING_HEADER:
4604                if (cli->rest)
4605                        ret = og_client_state_recv_hdr_rest(cli);
4606                else
4607                        ret = og_client_state_recv_hdr(cli);
4608
4609                if (ret < 0)
4610                        goto close;
4611                if (!ret)
4612                        return;
4613
4614                cli->state = OG_CLIENT_RECEIVING_PAYLOAD;
4615                /* Fall through. */
4616        case OG_CLIENT_RECEIVING_PAYLOAD:
4617                /* Still not enough data to process request. */
4618                if (cli->buf_len < cli->msg_len)
4619                        return;
4620
4621                cli->state = OG_CLIENT_PROCESSING_REQUEST;
4622                /* fall through. */
4623        case OG_CLIENT_PROCESSING_REQUEST:
4624                if (cli->rest) {
4625                        ret = og_client_state_process_payload_rest(cli);
4626                        if (ret < 0) {
4627                                syslog(LOG_ERR, "Failed to process HTTP request from %s:%hu\n",
4628                                       inet_ntoa(cli->addr.sin_addr),
4629                                       ntohs(cli->addr.sin_port));
4630                        }
4631                } else {
4632                        ret = og_client_state_process_payload(cli);
4633                }
4634                if (ret < 0)
4635                        goto close;
4636
4637                if (cli->keepalive_idx < 0) {
4638                        syslog(LOG_DEBUG, "server closing connection to %s:%hu\n",
4639                               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4640                        goto close;
4641                } else {
4642                        syslog(LOG_DEBUG, "leaving client %s:%hu in keepalive mode\n",
4643                               inet_ntoa(cli->addr.sin_addr),
4644                               ntohs(cli->addr.sin_port));
4645                        og_client_keepalive(loop, cli);
4646                        og_client_reset_state(cli);
4647                }
4648                break;
4649        default:
4650                syslog(LOG_ERR, "unknown state, critical internal error\n");
4651                goto close;
4652        }
4653        return;
4654close:
4655        ev_timer_stop(loop, &cli->timer);
4656        og_client_release(loop, cli);
4657}
4658
4659static void og_client_timer_cb(struct ev_loop *loop, ev_timer *timer, int events)
4660{
4661        struct og_client *cli;
4662
4663        cli = container_of(timer, struct og_client, timer);
4664        if (cli->keepalive_idx >= 0) {
4665                ev_timer_again(loop, &cli->timer);
4666                return;
4667        }
4668        syslog(LOG_ERR, "timeout request for client %s:%hu\n",
4669               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4670
4671        og_client_release(loop, cli);
4672}
4673
4674static int socket_s, socket_rest;
4675
4676static void og_server_accept_cb(struct ev_loop *loop, struct ev_io *io,
4677                                int events)
4678{
4679        struct sockaddr_in client_addr;
4680        socklen_t addrlen = sizeof(client_addr);
4681        struct og_client *cli;
4682        int client_sd;
4683
4684        if (events & EV_ERROR)
4685                return;
4686
4687        client_sd = accept(io->fd, (struct sockaddr *)&client_addr, &addrlen);
4688        if (client_sd < 0) {
4689                syslog(LOG_ERR, "cannot accept client connection\n");
4690                return;
4691        }
4692
4693        cli = (struct og_client *)calloc(1, sizeof(struct og_client));
4694        if (!cli) {
4695                close(client_sd);
4696                return;
4697        }
4698        memcpy(&cli->addr, &client_addr, sizeof(client_addr));
4699        cli->keepalive_idx = -1;
4700
4701        if (io->fd == socket_rest)
4702                cli->rest = true;
4703
4704        syslog(LOG_DEBUG, "connection from client %s:%hu\n",
4705               inet_ntoa(cli->addr.sin_addr), ntohs(cli->addr.sin_port));
4706
4707        ev_io_init(&cli->io, og_client_read_cb, client_sd, EV_READ);
4708        ev_io_start(loop, &cli->io);
4709        ev_timer_init(&cli->timer, og_client_timer_cb, OG_CLIENT_TIMEOUT, 0.);
4710        ev_timer_start(loop, &cli->timer);
4711}
4712
4713static int og_socket_server_init(const char *port)
4714{
4715        struct sockaddr_in local;
4716        int sd, on = 1;
4717
4718        sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
4719        if (sd < 0) {
4720                syslog(LOG_ERR, "cannot create main socket\n");
4721                return -1;
4722        }
4723        setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(int));
4724
4725        local.sin_addr.s_addr = htonl(INADDR_ANY);
4726        local.sin_family = AF_INET;
4727        local.sin_port = htons(atoi(port));
4728
4729        if (bind(sd, (struct sockaddr *) &local, sizeof(local)) < 0) {
4730                close(sd);
4731                syslog(LOG_ERR, "cannot bind socket\n");
4732                return -1;
4733        }
4734
4735        listen(sd, 250);
4736
4737        return sd;
4738}
4739
4740int main(int argc, char *argv[])
4741{
4742        struct ev_io ev_io_server, ev_io_server_rest;
4743        struct ev_loop *loop = ev_default_loop(0);
4744        int i;
4745
4746        if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4747                exit(EXIT_FAILURE);
4748
4749        openlog("ogAdmServer", LOG_PID, LOG_DAEMON);
4750
4751        /*--------------------------------------------------------------------------------------------------------
4752         Validación de parámetros de ejecución y lectura del fichero de configuración del servicio
4753         ---------------------------------------------------------------------------------------------------------*/
4754        if (!validacionParametros(argc, argv, 1)) // Valida parámetros de ejecución
4755                exit(EXIT_FAILURE);
4756
4757        if (!tomaConfiguracion(szPathFileCfg)) { // Toma parametros de configuracion
4758                exit(EXIT_FAILURE);
4759        }
4760
4761        /*--------------------------------------------------------------------------------------------------------
4762         // Inicializa array de información de los clientes
4763         ---------------------------------------------------------------------------------------------------------*/
4764        for (i = 0; i < MAXIMOS_CLIENTES; i++) {
4765                tbsockets[i].ip[0] = '\0';
4766                tbsockets[i].cli = NULL;
4767        }
4768        /*--------------------------------------------------------------------------------------------------------
4769         Creación y configuración del socket del servicio
4770         ---------------------------------------------------------------------------------------------------------*/
4771        socket_s = og_socket_server_init(puerto);
4772        if (socket_s < 0)
4773                exit(EXIT_FAILURE);
4774
4775        ev_io_init(&ev_io_server, og_server_accept_cb, socket_s, EV_READ);
4776        ev_io_start(loop, &ev_io_server);
4777
4778        socket_rest = og_socket_server_init("8888");
4779        if (socket_rest < 0)
4780                exit(EXIT_FAILURE);
4781
4782        ev_io_init(&ev_io_server_rest, og_server_accept_cb, socket_rest, EV_READ);
4783        ev_io_start(loop, &ev_io_server_rest);
4784
4785        infoLog(1); // Inicio de sesión
4786
4787        /* old log file has been deprecated. */
4788        og_log(97, false);
4789
4790        syslog(LOG_INFO, "Waiting for connections\n");
4791
4792        while (1)
4793                ev_loop(loop, 0);
4794
4795        exit(EXIT_SUCCESS);
4796}
Note: See TracBrowser for help on using the repository browser.