source: ogServer-Git/sources/ogAdmServer.cpp @ 0fbdcf2

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

#941 use dbi layer from procesoInclusionClienteWinLnx()

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