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