source: ogServer-Git/sources/ogAdmServer.cpp @ 54ecdbb

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

#915 Validate POST /clients parameters

This patch adds og_msg_params_validate function as well as some flags that can
be used to validate parameters of a REST API request.

This patch ensures that all required parameters are sent in the request.

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