source: ogServer-Git/sources/ogAdmServer.cpp @ 03f1941

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

#941 use dbi layer from actualizaHardware

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