-
Notifications
You must be signed in to change notification settings - Fork 0
/
websck.cc
executable file
·1430 lines (975 loc) · 36.4 KB
/
websck.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#include "websck.h"
# include "gateway.h"
# include <netdb.h>
extern GHashTable* peer_tab;
extern GHashTable *nocat_conf;
extern class comm_interface* wsk_comm_interface;
extern gchar* macAddressFrom;
extern gchar* datalnet_IP;
gboolean is_IP(gchar* name){
unsigned int res;
struct sockaddr_in addr;
//struct sockaddr_in6 addr6;
res = inet_pton(AF_INET, name, &(addr.sin_addr));
//res = inet_pton(AF_INET6, name, &(addr6.sin6_addr));
if (res == 1) return TRUE;
else return FALSE;
}
void dns_callback (GObject *source_object,GAsyncResult *res,gpointer user_data){
GList * mylist;
gchar* address;
int x;
GError* gerror = NULL;
mylist = g_resolver_lookup_by_name_finish((GResolver *)source_object,res,&gerror);
if (gerror != NULL) {
g_message("dns_callback: g_resolver_lookup_by_name_finish error: %s",gerror->message);
wsk_comm_interface->wsk_set_status(WSK_DISCONNECTED,"dns_callback");
return;
}
if (mylist != NULL){
address = g_inet_address_to_string((GInetAddress *)mylist->data);
wsk_comm_interface->set_wsk_server_IP(address);
g_free(address);
x = wsk_comm_interface->wsk_create();
if (x == -1){
g_message("dns_callback: websocket initialization error, retrying...");
wsk_comm_interface->wsk_set_status(WSK_DISCONNECTED,"dns_callback");
}
}
else {
g_message("dns_callback: g_resolver_lookup_by_name_finish error ..");
wsk_comm_interface->wsk_set_status(WSK_DISCONNECTED,"dns_callback");
}
}
int callback_authentication(struct libwebsocket_context* thi, struct libwebsocket* wsi, enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len) {
switch (reason) {
case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
g_message("wsk callback_authentication: LWS_CALLBACK_CLIENT_CONNECTION_ERROR");
wsk_comm_interface->wsk_set_status(WSK_ERROR,"callback_authentication");
break;
case LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH");
break;
case LWS_CALLBACK_CLIENT_ESTABLISHED:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLIENT_ESTABLISHED");
wsk_comm_interface->clear_init();
wsk_comm_interface->wsk_set_status(WSK_CLIENT_ESTABLISHED,"callback_authentication");
break;
case LWS_CALLBACK_CLOSED:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLOSED");
wsk_comm_interface->wsk_set_status(WSK_CLOSED,"callback_authentication");
return -1;
break;
case LWS_CALLBACK_CLIENT_RECEIVE:
g_debug("wsk callback_authentication: LWS_CLIENT_RECEIVE");
//g_debug("recibidos %d bytes",len);
//g_message("recibidos %d bytes",len);
//g_message("recibido: %s",(char*)in);
//if (libwebsocket_is_final_fragment(wsi)) g_message("la trama llegó completa");
//int x;
//x = strlen((char*)in);
//g_message("contados: %d caracteres",x);
wsk_comm_interface->reception_queu->receive_frame((char *)in,len);
break;
case LWS_CALLBACK_CLIENT_RECEIVE_PONG:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLIENT_RECEIVE_PONG");
break;
case LWS_CALLBACK_CLIENT_WRITEABLE:
if (wsk_comm_interface->get_status() == WSK_IDDLE){
g_message("wsk callback_authentication: Begining wsk close secuence..");
return -1;
}
g_debug("wsk callback_authentication: LWS_CLIENT_WRITEABLE");
wsk_comm_interface->sender_queu->run(wsi,wsk_comm_interface->get_status());
/*
* without at least this delay, we choke the browser
* and the connection stalls, despite we now take care about
* flow control
I really need to see if this is important, because I don't want to waste 200 ms*/
//usleep(200);
//g_message("Se esperó con éxito");
/* get notified as soon as we can write again*/
//libwebsocket_callback_on_writable(thi, wsi);
//g_message("Se reregistró con éxito");
break;
case LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS:
g_debug("wsk callback_authentication: LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS");
break;
case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER");
break;
/* because we are protocols[0] ... */
case LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED");
/*
if ((strcmp((char*)in, "deflate-stream") == 0) && deny_deflate) {
g_message("denied deflate-stream extension\n");
return 1;
}
if ((strcmp((char*)in, "deflate-frame") == 0) && deny_deflate) {
g_message("denied deflate-frame extension\n");
return 1;
}
if ((strcmp((char*)in, "x-google-mux") == 0) && deny_mux) {
g_message("denied x-google-mux extension\n");
return 1;
}*/
return 1; // Por el momento no pienso soportar ninguna extensión.
break;
case LWS_CALLBACK_PROTOCOL_INIT:
g_debug("wsk callback_authentication: LWS_CALLBACK_PROTOCOL_INIT");
break;
case LWS_CALLBACK_ADD_POLL_FD:
g_debug("wsk callback_authentication: LWS_CALLBACK_ADD_POLL_FD");
break;
case LWS_CALLBACK_DEL_POLL_FD:
g_debug("wsk callback_authentication: LWS_CALLBACK_DEL_POLL_FD");
break;
case LWS_CALLBACK_SET_MODE_POLL_FD:
g_debug("wsk callback_authentication: LWS_CALLBACK_SET_MODE_POLL_FD");
break;
case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
g_debug("wsk callback_authentication: LWS_CALLBACK_CLEAR_MODE_POLL_FD");
break;
case LWS_CALLBACK_PROTOCOL_DESTROY:
g_debug("wsk callback_authentication: LWS_CALLBACK_PROTOCOL_DESTROY");
wsk_comm_interface->wsk_set_status(WSK_DISCONNECTED,"callback_authentication");
break;
default:
g_message("wsk callback_authentication: Libwebsocket callback function called with unnatended reason (%d)",(int)reason);
break;
}
return 0;
}
gboolean call_libwebsocket_service(void* dummy){
switch (wsk_comm_interface->get_status()){
case WSK_WAITING_CONFIRM:
// Aquí tengo que incluir un contador para un timeout, en caso de que se cumpla el timeout
// avisar a la administración del sistema del error, poner init en TRUE y poner el wsk en
// estado WSK_CLOSED para que vuelva a intentar conectarse dentro de un segundo.
break;
case WSK_ERROR:
// La misma historia que el estado anterior, poner init en TRUE para que cuando wsk_comm_interface->reset
// ponga el wsk en estado DISCONNECTED y se vuelva a entrar en esta función no haya que esperar el tiempo
// wsk_keep_alive para volver a intentar la conexión. También tengo que avisar a la administración del
// error.
wsk_comm_interface->set_init();
wsk_comm_interface->reset();
break;
case WSK_CLOSED:
wsk_comm_interface->reset();
break;
case WSK_CLIENT_ESTABLISHED:
/*if ((g_hash_table_size(peer_tab) == 0) &&
(wsk_comm_interface->sender_queu->get_count() == 0)){
if (difftime(time(NULL),wsk_comm_interface->get_last_access_time())
> wsk_comm_interface->get_wsk_time_out()){
wsk_comm_interface->wsk_set_status(WSK_IDDLE,"call_libwebsocket_service");
libwebsocket_callback_on_writable(wsk_comm_interface->get_context(),
wsk_comm_interface->get_wsi());
}
}
else*/
wsk_comm_interface->set_last_access_time();
break;
case WSK_DISCONNECTED:
/*if (!(wsk_comm_interface->is_init())){
if (difftime(time(NULL),wsk_comm_interface->get_last_access_time())
< wsk_comm_interface->get_wsk_keep_alive()) {
return TRUE;
}
}*/
wsk_comm_interface->wsk_initialize();
return TRUE;
case WSK_WAITING_DNS:
return TRUE;
default:
break;
}
libwebsocket_service(wsk_comm_interface->get_context(),0);
return TRUE;
}
unsigned int extract_value (const char* token,char* begin,bool* corre){
unsigned int resultado = 0;
char* tempo;
*corre = FALSE;
char* ptr_begin = strstr(begin, token);
if (ptr_begin != NULL){
ptr_begin = ptr_begin + strlen(token);
char* ptr_end = strchr(ptr_begin,'\"');
if (ptr_end != NULL){
tempo = (char*)calloc(1,ptr_end - ptr_begin + 1);
memcpy(tempo,ptr_begin,ptr_end - ptr_begin);
}
else return 0;
resultado = (unsigned int) strtol(tempo,NULL,0);
free(tempo);
*corre = TRUE;
}
return resultado;
}
char* extract_value_s (const char* token,char* begin,bool* corre){
char* resultado = NULL;
*corre = FALSE;
char* ptr_begin = strstr(begin, token);
if (ptr_begin != NULL){
ptr_begin = ptr_begin + strlen(token);
char* ptr_end = strchr(ptr_begin,'\"');
if (ptr_end != NULL){
resultado = (char*)calloc(1,ptr_end - ptr_begin + 1);
memcpy(resultado,ptr_begin,ptr_end - ptr_begin);
}
else return resultado;
*corre = TRUE;
}
return resultado;
}
void parse_status(int status, char* status_char){
switch (status) {
case 0:
strcpy(status_char,(char*)"WSK_DISCONNECTED");
break;
case 1:
strcpy(status_char,(char*)"WSK_WAITING_DNS");
break;
case 2:
strcpy(status_char,(char*)"WSK_WAITING_CONFIRM");
break;
case 3:
strcpy(status_char,(char*)"WSK_CLIENT_ESTABLISHED");
break;
case 4:
strcpy(status_char,(char*)"WSK_ERROR");
break;
case 5:
strcpy(status_char,(char*)"WSK_CLOSED");
break;
case 6:
strcpy(status_char,(char*)"WSK_IDDLE");
break;
default:
strcpy(status_char,(char*)"WSK_UNKNOW");
break;
}
}
/***************************** class m_frame methods *******************************/
#ifdef MFRAME
// class m_frame constructor from a message (parse an arrived xml message to a class m_frame)
/*
<Protocol Version="0">
<Frame Type="1" Command="6" FrameCount="1" AckCount="0" BodyFrameSize="0" FromDeviceId="xxx" ToDeviceId="yyy">
<Parameters Count="1">
<Parameter Name="IsAuthenticated" Value="true" />
<Parameter Name="UserToken" Value="48e3f2d3-f805-4ea7-afda-d0fe2344b0b3" />
</Parameters>
</Frame>
</Protocol>
*/
m_frame::m_frame(char* message, unsigned int m_size, bool* correct){
char* message_remaining = message;
*correct = FALSE;
//Chequear que el encabezamiento y el terminador xml estén en su sitio.
if ((memcmp ("<Protocol", message, 9) != 0) || (strstr (message, "</Protocol>") == NULL)) return;
// Buscar el terminador del protocol header, poner un caracter nulo en él y marcar el
// próximo caracter como donde vamos a seguir después de parsear el protocolo.
char* protocol_header_end = strchr(message_remaining, '>');
if (protocol_header_end != NULL){
memcpy(protocol_header_end,"\0",1);
message_remaining = protocol_header_end + 1;
}
// Buscar el valor del parámetro Version.
Version = extract_value ("Version=\"",message + 8,correct);
if (!(*correct)) return;
*correct = FALSE;
// Procesamiento de la información de la trama.
char* frame_header_begin = strstr (message_remaining, "<Frame ");
if (frame_header_begin == NULL) return;
frame_header_begin = frame_header_begin + 7;
char* frame_header_end = strchr (frame_header_begin,'>');
if (frame_header_end != NULL){
memcpy(frame_header_end,"\0",1);
if (memcmp((frame_header_end-1),"/",1) == 0) message_remaining = NULL;
else message_remaining = frame_header_end + 1;
}
else return;
Type = extract_value ("Type=\"",frame_header_begin,correct);
if (!(*correct)) return;
Command = extract_value ("Command=\"",frame_header_begin,correct);
if (!(*correct)) return;
FrameCount = extract_value ("FrameCount=\"",frame_header_begin,correct);
if (!(*correct)) return;
AckCount = extract_value ("AckCount=\"",frame_header_begin,correct);
if (!(*correct)) return;
BodyFrameSize = extract_value ("BodyFrameSize=\"",frame_header_begin,correct);
if (!(*correct)) return;
if (message_remaining == NULL){
*correct = TRUE;
return;
}
else {
// Procesamiento de los parámetros.
*correct = FALSE;
char* parameters_header_begin = strstr (message_remaining, "<Parameters ");
if (parameters_header_begin == NULL) return;
parameters_header_begin = parameters_header_begin + 12;
char* parameters_header_end = strchr (parameters_header_begin,'>');
if (parameters_header_end != NULL){
memcpy(parameters_header_end,"\0",1);
message_remaining = parameters_header_end + 1;
parameters = g_new0(struct parametros,1);
}
else return;
parameters->cantidad = extract_value ("Count=\"",parameters_header_begin,correct);
if (!(*correct)) return;
parameters->items = g_new0(item*,parameters->cantidad);
char *parameter_header_begin, *parameter_header_end;
for (unsigned int i = 0;i<parameters->cantidad;i++){
parameters->items[i] = g_new0(struct item,1);
parameter_header_begin = strstr (message_remaining, "<Parameter ");
if (parameter_header_begin == NULL) return;
parameter_header_begin = parameter_header_begin + 11;
parameter_header_end = strchr (parameter_header_begin,'>');
if (parameter_header_end != NULL){
memcpy(parameter_header_end,"\0",1);
message_remaining = parameter_header_end + 1;
}
parameters->items[i]->nombre = extract_value_s("Name=\"",parameter_header_begin,correct);
if (!(*correct)) return;
parameters->items[i]->valor = extract_value_s("Value=\"",parameter_header_begin,correct);
if (!(*correct)) return;
}
}
*correct = TRUE;
}
/* class m_frame constructor from fields (build a class m_frame given certain fields)
m_frame::m_frame(char* comando, struct parametros* parameters_in, struct data* datos_in, bool* correct) {
m_frame_index = 0;
m_frame_index_ack = 0;
command_name = comando;
parameters = NULL;
datos = NULL;
readed = false;
m_frame_as_message = NULL;
memset (frame_type,0,2);
// Este bloque if else de abajo tengo que cambiarlo por un mecanismo mejor y más parametrizable para establecer el tipo de
// trama a partir del nombre del comando.
if ((strcmp(comando,"INIT") == 0) || (strcmp(comando,"GETPARAMS") == 0) || (strcmp(comando,"LISTPARAMS") == 0)
|| (strcmp(comando,"LISTPARAM") == 0) || (strcmp(comando,"CHANGEPARAM") == 0) || (strcmp(comando," CHANGEPARAMPERS") == 0)
|| (strcmp(comando,"ADDPARAM") == 0) || (strcmp(comando," ADDPARAMPER") == 0) || (strcmp(comando,"REMPARAM") == 0)
|| (strcmp(comando,"REMPARAMPERS") == 0) || (strcmp(comando,"SAVESTATUSCLIENT") == 0) || (strcmp(comando," SAVESTATUSOK") == 0)
|| (strcmp(comando,"SAVESTATUSCLIENT") == 0) || (strcmp(comando,"GETSTATUSCLIENTS") == 0) || (strcmp(comando,"STATUSCLIENTS") == 0)
|| (strcmp(comando,"STATUSCLIENT") == 0) || (strcmp(comando,"CLEARSTATUSCLIENTS") == 0) || (strcmp(comando,"HAVESTATUS") == 0)
|| (strcmp(comando,"VER") == 0) || (strcmp(comando,"ACTUALIZAR") == 0) || (strcmp(comando,"GETARCHIVO") == 0)
|| (strcmp(comando,"SETARCHIVO") == 0) || (strcmp(comando,"AUTH") == 0)){
memcpy(frame_type,"C",1);
}
else if (strcmp(comando,"ARCHIVO") == 0){
memcpy(frame_type,"D",1);
}
else if (strcmp(comando,"ACKNOWLEDGE") == 0){
memcpy(frame_type,"A",1);
body_size = 0;
*correct = true;
//print();
return;
}
else{
lwsl_err("comando no soportado: %s",comando);
// Aquí tengo que eliminar los buffers comando, parameters_in y data_in que me pasaron en la llamada de la función pues
// ya no van a seguir haciendo falta ya que el comando es incorrecto ?
*correct = false;
return;
}
unsigned int parameters_size = 0;
if (parameters_in != NULL){
parameters = parameters_in;
for (unsigned int i = 0; i < parameters->cantidad;i++){
parameters_size = parameters_size + strlen(parameters->values[i]) + 1;
//g_message("parameter %d size = %d",i,parameters_size);
}
//g_message("total parameters_size = %d",parameters_size);
}
body_size = strlen(comando) + parameters_size ;
if (datos_in != NULL){
datos = datos_in;
body_size = body_size + datos->size + 1;
}
//g_message("body_size = %d",body_size);
if (body_size > 4075){
lwsl_err("frame maximum size exceded (%d)",body_size);
*correct = false;
}
else *correct = true;
//print();
return;
}*/
//class m_frame destructor
m_frame::~m_frame(){
//g_message("entré al destructor de m_frames");
//g_message("nombre del comando a destruir: %s",command_name);
if (parameters != NULL){
for (unsigned int i=0; i<parameters->cantidad;i++){
if (parameters->items[i] != NULL){
if (parameters->items[i]->nombre != NULL) free(parameters->items[i]->nombre);
if (parameters->items[i]->valor != NULL) free(parameters->items[i]->valor);
free(parameters->items[i]);
}
}
free(parameters);
}
}
unsigned short int m_frame::get_index(){
return FrameCount;
}
/*
unsigned short int m_frame::get_index_ack(){
return m_frame_index_ack;
}
bool m_frame::mark_readed(){
readed = true;
return readed;
}
bool m_frame::is_readed(){
return readed;
}
unsigned short int m_frame::get_body_size(){
return body_size;
}
char* m_frame::get_frame_type(){
return frame_type;
}
char* m_frame::get_command_name(){
return command_name;
}
struct parametros* m_frame::get_parameters(){
return parameters;
}
struct data* m_frame::get_data(){
return datos;
}
unsigned char* m_frame::as_message(){
unsigned char* buffer;
unsigned char* new_pos;
if (m_frame_as_message != NULL) return m_frame_as_message;
else {
buffer = (unsigned char*)g_malloc0(21 + body_size);
m_frame_as_message = buffer;
}
g_memmove(buffer,"_###_",5);
g_memmove(buffer+5,&m_frame_index,2);
g_memmove(buffer+7,"_",1);
g_memmove(buffer+8,&m_frame_index_ack,2);
g_memmove(buffer+10,"_",1);
g_memmove(buffer+11,&body_size,2);
g_memmove(buffer+13,"_",1);
g_memmove(buffer+14,&frame_type,1);
if (memcmp (&frame_type, "A", 1) != 0){
g_memmove(buffer+15,"_",1);
g_memmove(buffer+16,command_name,strlen(command_name));
new_pos = buffer + 16 + strlen(command_name);
if (parameters != NULL){
for (unsigned int i = 0;i < parameters->cantidad;i++){
g_memmove(new_pos,"_",1);
new_pos = new_pos +1;
g_memmove(new_pos,parameters->values[i],strlen(parameters->values[i]));
new_pos = new_pos + strlen(parameters->values[i]);
}
}
if (datos != NULL){
g_memmove(new_pos,":",1);
new_pos = new_pos +1;
g_memmove(new_pos,datos->binaries,datos->size);
new_pos = new_pos + datos->size;
}
}
else new_pos = buffer + 15;
g_memmove(new_pos,"_###_",5);
return buffer;
}
char* m_frame::print(){
//char cabeza[body_size+30];
char* cabeza = (char*)g_malloc0(body_size+30);
//memset (cabeza,0,body_size+30);
sprintf(cabeza,"_###_%d_%d_%d_%s",m_frame_index,m_frame_index_ack,body_size,frame_type);
if (body_size > 0){
char cuerpo[body_size];
memset (cuerpo,0,body_size);
if ( (memcmp(frame_type,"C",1) == 0) || (memcmp(frame_type,"D",1) == 0) ){
strcat (cuerpo,"_");
strcat (cuerpo,command_name);
if (parameters != NULL){
for (unsigned int i = 0;i < parameters->cantidad;i++){
strcat (cuerpo,"_");
strcat (cuerpo,parameters->values[i]);
}
}
if (datos != NULL){
strcat (cuerpo,":");
char dada[10];
memset(dada,0,10);
sprintf(dada,"%d",datos->size);
strcat (cuerpo,dada);
strcat (cuerpo,"b");
}
}
strcat(cabeza,cuerpo);
}
strcat(cabeza,"_###_");
//g_message(cabeza);
return cabeza;
}*/
#endif
/***************************** end class m_frame methods ***************************/
/***************************** class received_messages_queu methods ****************/
#ifdef MFRAME
// Constructor
received_messages_queu::received_messages_queu(){
ptr_frames = NULL;
count = 0;
}
// Destructor
received_messages_queu::~received_messages_queu(){
return;
}
// Receptor de tramas
bool received_messages_queu::receive_frame(char* message,size_t message_size){
bool right = false;
// Crear una clase m_frame con los datos que llegaron en la transmisión.
//g_message("recibiendo una trama");
class m_frame* temp_frame = new m_frame((char*) message, message_size, &right);
if (!right){ // Si hubo algún problema en la creación de la clase m_frame eliminarla y retornar false.
lwsl_warn("received_messages_queu::receive_frame: trama incorrecta..");
char* tem = (char*)g_malloc0(message_size + 2);
memcpy(tem,message,message_size);
g_debug(tem);
g_free(tem);
delete temp_frame;
return false;
}
else g_debug("received_messages_queu::receive_frame: se recibió la trama de autorización de cliente correctamente..");
// Aquí chequeo si es una trama ack, en caso de serlo por el momento solamente se descarta esta y ya.
// En un futuro se deberá chequear en la cola de salida la trama que está esperando por el ack, se elimina de la
// cola de salida (tomando las medidas extras necesarias como resetear contadores de espera para reenvío, etc) y
// se elimina la trama ack recientemente llegada.
/* Bloque comentariado temporalmente.
if (memcmp(temp_frame->get_frame_type(),"A",1) == 0){
g_message("recibido un ack");
delete temp_frame;
wsk_comm_interface->set_last_access_time();
return true;
}*/
// Chequear que no haya otra trama en la cola que tenga el mismo index, de ser así eliminar la trama
// llegada y retornar false.
for (int i = 0;i<count;i++){
if (ptr_frames[i]->get_index() == temp_frame->get_index()){
lwsl_warn("received_messages_queu::receive_frame: repeated frame arrived, descarted...");
delete temp_frame;
return false;
}
}
// Poner la trama en el final de la cola de tramas llegadas.
struct m_frame** temp = (struct m_frame**) g_malloc0(count + 1);
for (int i=0;i<count;i++){
temp[i] = ptr_frames[i];
}
if (ptr_frames != NULL) g_free(ptr_frames);
ptr_frames = temp;
ptr_frames[count] = temp_frame;
count++;
wsk_comm_interface->set_last_access_time();
if (temp_frame->Command == 6){
if (temp_frame->parameters != NULL){
if (temp_frame->parameters->cantidad == 2){
if ((temp_frame->parameters->items[0]->nombre != NULL) &&
(temp_frame->parameters->items[0]->valor != NULL) &&
(temp_frame->parameters->items[1]->nombre != NULL) &&
(temp_frame->parameters->items[1]->valor != NULL)) {
if ((strcmp(temp_frame->parameters->items[0]->nombre,"IsAuthenticated") == 0) &&
(strcmp(temp_frame->parameters->items[1]->nombre,"UserToken") == 0)){
g_idle_add((GSourceFunc)check_peer, temp_frame);
}
}
}
}
}
// Aquí tengo que chequear si la trama requiere una respuesta concreta, si no
// extraer el index de la trama que me enviaron y responder con un ack. Responder con un ack
// significa crear una trama ack y adicionarla a la cola de salida.
return true;
}
// Eliminador de trama (como parámetro se le entra el index de envío)
bool received_messages_queu::delete_frame(unsigned int m_frame_index){
for (int i = 0;i<count;i++){
if (ptr_frames[i]->get_index() == m_frame_index){
delete ptr_frames[i];
struct m_frame** temp = (struct m_frame**) g_malloc0(count-1);
if (temp != NULL){ // Si temp == NULL es porque count - 1 = 0, es decir i = 0 y la trama que se eliminó
// era la única que había.
for (int a = 0;a < i;a++){
temp[a] = ptr_frames[a];
}
for (int a = i;a < count - 1;a++){
temp[a] = ptr_frames[a+1];
}
g_free(ptr_frames);
ptr_frames = temp;
}
count--;
if (count == 0){
g_free(ptr_frames);
ptr_frames = NULL;
}
return true;
}
}
return false;
}
#endif
/***************************** end class received_messages_queu methods ************/
/***************************** class send_messages_queu methods ********************/
#ifdef MFRAME
// Constructor
send_messages_queu::send_messages_queu(){
ptr_frames = NULL;
count = 0;
return;
}
// Destructor
send_messages_queu::~send_messages_queu(){
return;
}
// Receptor de tramas
bool send_messages_queu::add_frame(char* comando, struct parametros* parameters_in, struct data* datos_in){
//bool right = false;
// Crear una clase m_frame con la información que se quiere transmitir.
/* Bloque comentariado temporalmente.
class m_frame* temp_frame = new m_frame(comando,parameters_in,datos_in, &right);
if (!right){ // Si hubo algún problema en la creación de la clase m_frame eliminarla y retornar false.
delete temp_frame;
return false;
}*/
// Chequear que no haya otra trama en la cola que tenga el mismo index, de ser así eliminar la trama
// llegada y retornar false.
/*if (ptr_frames != NULL){
for (int i = 0;i<count;i++){
if (ptr_frames[i]->get_index() == temp_frame->get_index()){
g_message("repeated frame (frame_index = %d), descarted...",temp_frame->get_index());
delete temp_frame;
return false;
}
}
}*/
// Poner la trama en el final de la cola de tramas por enviar.
struct m_frame** temp = (struct m_frame**) g_malloc0(count + 1);
if (ptr_frames != NULL){
for (int i=0;i<count;i++){
temp[i] = ptr_frames[i];
}
g_free(ptr_frames);
}
ptr_frames = temp;
//ptr_frames[count] = temp_frame;
count++;
//char* dd = ptr_frames[count]->get_command_name();
//g_message(dd);
return true;
}
void send_messages_queu::run(struct libwebsocket *wsi,enum STATUSES wsk_status){
//g_message("running send messages queu");
unsigned int message_size;