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