Blame view

src/DDClientLibCpp/DD_client.cc 31.9 KB
a952e350   Benjamin Renard   First commit of D...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* $Id: DD_client.c,v 1.3 2009/04/14 08:37:28 budnik Exp $ */
/*==============================================================
 *                  DD SYSTEM 
 *                 DD_client.c
 *                    V.4.8
 * List of changes:
 * November 1995, Version 1.0
 * August 1999 :Access security system was installed by Alexandr Grigoriev (v3.0)
 * October 22, 2002 - Communication ideology  is changed (V.4.0)
 * Oct 29, 2002 - Add DD_GetVersion() and some bags are corrected (V.4.1)
 * May 1, 2003 - Network error is developped. (The header receiving is changed): V.4.2
 * Nov 18, 2004 - Cach error is fixed.
 * Jun 17, 2007 - Fedorov, V.4.5 Create new VI and Update data requests
 * Sep 24, 2007 - Fedorov, V.4.6 Processing of return of Get_Data
 * Dec 03, 2007 - Budnik,  V.4.7 There may be several sessions with DD Server inside ONE
 *                               Client session. Keep UserHost & UserName
 * Oct 18, 2012  - Knizhnikova, V.4.8 new DD_SetTimeInfo() function
ad73f734   Benjamin Renard   Set to version 7.0.0
18
 * Dec 05, 2017  - Renard, V.7.0
a952e350   Benjamin Renard   First commit of D...
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
 *===============================================================*/

#include <unistd.h>
#include <stdio.h>
#include <string.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "DD.hh"

#ifdef LOG4CXX
log4cxx::LoggerPtr DD_Client::_logger = log4cxx::Logger::getLogger(
		"AMDA-Kernel.DD_Client");
#endif

/*------------------ GLOBAL STATIC VARIABLES --------------------------*/

//extern int errno;

/*================== FUNCTIONS =================================*/
/*----------------------- GET User Host-------------------------------*/

static size_t unixlen[] = {sizeof(char),sizeof(int),sizeof(float),sizeof(double),sizeof(short)};

static xdrproc_t ConvFunc[5]    = {(xdrproc_t )xdr_char, (xdrproc_t )xdr_int, (xdrproc_t )xdr_float, (xdrproc_t )xdr_double, (xdrproc_t )xdr_short};

DD_Client:: DD_Client() :
		idd (DD_CHAR, 0, NULL,1, (void**) malloc(sizeof(void*))),
		CurrentData(NULL),
		_varNumber(0),
	 	SocketID( -1),
	 	UserID(0),
		m1(0X000000FF),
		m2( 0X0000FF00),
		m3(0X00FF0000),
		m4( 0XFF000000),
		//Host(NULL),
	 	buffSetVarialbe(NULL),
	 	bufDD_SetTime (NULL),
	 	op(TIMESETREQ),
	    bufDD_GetData( NULL),
	    LastPacketFlag(OK),
	    bufDD_Close (NULL),
	    opDD_Close(CLOSEINSREQ),
	    bufDD_AddDataSet(NULL),
	    opDD_AddDataSet(ADDVIREQ),
	    Version(VERSION)

	{
	UserName[0] = '\0';
	UserHost[0] = '\0';
	RemSerName[0]='\0';
 	strcpy(TimeInt, "0000000000001000");
 	idd.Variables[0]=NULL;
}

int DD_Client::GetUserHost() {
	int userid;

	userid = getuid(); /* Get a client user  ID */

#ifdef LOG4CXX
	//LOG4CXX_DEBUG(_logger, "DD_Client::GetUserHost - UserId : " << userid);
#endif

	/* UserHost can be set by extern WEB function in case of WEB communicatio,
	 * or it should be defined as local host if DD_client is installed at USER
	 * computer
	 */
	if (UserHost[0] == '\0') {
		char HostName[HOSTNAMELENGTH];

		gethostname(HostName, HOSTNAMELENGTH); /* Get a client host name */

		struct sockaddr_in addr;

		if (getInfoFromHostName(HostName,addr) != 0)
			return NOHOST;

		unsigned int b1, b2, b3, b4;
		sscanf(inet_ntoa( addr.sin_addr), "%3u.%3u.%3u.%3u", &b1, &b2, &b3, &b4);
		snprintf(UserHost, MAXHOSTLENGTH, "%03u.%03u.%03u.%03u", b1, b2, b3, b4);

#ifdef LOG4CXX
c027acc9   Elena.Budnik   added username t...
105
		// LOG4CXX_DEBUG(_logger, "DD_Client::GetUserHost - UserHost : " << UserHost);
a952e350   Benjamin Renard   First commit of D...
106
107
108
109
110
111
112
113
#endif
	}
	return userid;
}

void DD_Client::setUserHost(const char* host) {
	snprintf(UserHost, MAXHOSTLENGTH, "%s", host);
#ifdef LOG4CXX
c027acc9   Elena.Budnik   added username t...
114
115
116
117
118
119
120
121
	// LOG4CXX_DEBUG(_logger, "DD_Client::setUserHost - UserHost : " << UserHost);
#endif
}

void DD_Client::setUserName(const char* name) {
	snprintf(UserName, USRLENGTH, "%s", name);
#ifdef LOG4CXX
	// LOG4CXX_DEBUG(_logger, "DD_Client::setUserName - UserName : " << UserName);
a952e350   Benjamin Renard   First commit of D...
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
#endif
}

int DD_Client::getInfoFromHostName(const char *hostName, struct sockaddr_in &addr)
{
	struct addrinfo hints;
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;
	hints.ai_protocol = 0;
	hints.ai_canonname = NULL;
	hints.ai_addr = NULL;
	hints.ai_next = NULL;

	struct addrinfo *result;
	int s;

	s = getaddrinfo(hostName, NULL, &hints, &result);

	if (s != 0)
	{
#ifdef LOG4CXX
		LOG4CXX_ERROR(_logger, "DD_Client::getIpFromHostName - Cannot get ip from host name " << hostName);
#endif
		return NOHOST;
	}

	struct sockaddr_in *h;
	h = (struct sockaddr_in *) result->ai_addr;

	memcpy(&addr,h,sizeof(struct sockaddr_in));

	freeaddrinfo(result);

	return 0;
}
/*-------------------------------------------------------------------*/

/*------------------ MAKE_CONNECTION ---------------------------*/
/*
 * The function returns opened socket, ready to read and write
 */
int DD_Client::GetSocket()
/*
 * Connect with remote server, and returns socket ID
 * In case of error return error number according DD_comm.h
 */
{
/*-------- Variables for resource file -----------------*/
   char rname[PATHLENGTH];      /* name of res file */
   char line[PATHLENGTH];
   char *path;
   FILE *resfile;       /* resource file */

/*---------- Variables for network ---------------------*/

   int normaddr;
/*
 *---------- Getting socket and its address ---------------------*/ 
/*---------------- HOST and PORT ------------------------------*/
   if((path = getenv("DDPATH")) == NULL)
   {
      strcpy(rname,"DD.res");
   }
   else
   {
      strcpy(rname,path);
      strcat(rname, "/DD.res");
   }
/*
   (void *)strcpy(rname,"./DD.res");
*/
   if((resfile = fopen(rname,"r")) == NULL)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::GetSocket - Cannot find resource file " << rname);
#endif

      fprintf(stderr,"No resource file, sorry\n");
      exit(1);
   }

   fgets(RemSerName, PATHLENGTH-1, resfile);
   fgets(line, PATHLENGTH-1, resfile);
   fclose(resfile);

   RemSerName[strlen(RemSerName)-1] = '\0';
   sscanf(line,"%5d",&(normaddr));
   

/*---------------- END of FILE READING --------------------------*/
/*
 *------- Trying to open socket with this address and name ---------
 */

   if((SocketID = socket(AF_INET,SOCK_STREAM,PROTOCOL)) < 0)
   {
#ifdef LOG4CXX
      LOG4CXX_ERROR(_logger, "DD_Client::GetSocket - Socket error ");
#endif
      perror("Socket:"); return(-1);
   }

/* Filling full internet address for socket "name"
 * this address will be used to get communication point */

   struct sockaddr_in IntAFAddr;

   if (getInfoFromHostName(RemSerName,IntAFAddr) != 0)
   		return NOHOST;

   IntAFAddr.sin_port = htons((uint16_t)normaddr); /* Conversion of the port number to
                                                         universal net form */
#ifdef LOG4CXX
   //LOG4CXX_DEBUG(_logger, "DD_Client::GetSocket - HostName : " << RemSerName << " - IP : " << inet_ntoa(IntAFAddr.sin_addr) << " - Port : " << IntAFAddr.sin_port);
#endif

   /* Connection to server socket on remote computer */
   int errnum = connect(SocketID,(struct sockaddr *)&IntAFAddr,sizeof(struct sockaddr_in));
   if(errnum < 0)
   {
#ifdef LOG4CXX
	   LOG4CXX_ERROR(_logger, "DD_Client::GetSocket - Connection to server socket error - " << strerror (errnum));
#endif
	   perror("connect");
	   return(-1);
   }
         
/*
 * Get Host name and Host ID for security application
 */
   if((UserID = GetUserHost()) < 0)
   {
#ifdef LOG4CXX
	   LOG4CXX_ERROR(_logger, "DD_Client::GetSocket - NOHOST error");
#endif
	   return(NOHOST);
   }

   return SocketID;
}
/*------------------- end of GetSocket ---------------------*/

/*==================== Receive From Net ======================*/
/*
 * Smart buffered receiver
 */
int DD_Client::ReceiveFromNet(char *buf, int PacketSize)
{
   int CurLength = 0;

   do
   {
      int i = 0;
      int cc = 0;
      while(( (cc = recv(SocketID,buf+ CurLength,PacketSize - CurLength,0)) < 0) && (i < TRY)) i++;
b4f3419a   Benjamin Renard   Quit properly whe...
279
      if(cc <= 0) return -1;
a952e350   Benjamin Renard   First commit of D...
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
      CurLength = CurLength + cc;
   } while(CurLength < PacketSize);
   return 1;
}

/*------------------ Open Virtual Instrument -----------------------*/
/*
 * If no connection, connect to server, then try to order data set and return
 * ID if OK or ErrorNumber if not
 */
int DD_Client::DD_SetVariable(char *InstrName)
{
   int InstrID; /* Instrumnet ID to return */
   int Request = OPENINSREQ;
   int hostlen,userlen;
   char *PUserHost = UserHost, *PUserName = UserName;
493d59cf   Elena.Budnik   set UserName from...
296
297
   char *pDDuser;
   
a952e350   Benjamin Renard   First commit of D...
298
   /* We need this because XDR works with adresses of pointers */
493d59cf   Elena.Budnik   set UserName from...
299

a952e350   Benjamin Renard   First commit of D...
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
/* If there is no connection, try to get it */
   if(SocketID < 0)
       if((SocketID = GetSocket()) < 0)
    	   {
#ifdef LOG4CXX
    	   	   LOG4CXX_ERROR(_logger, "DD_Client::DD_SetVariable - No connection");
#endif
    	   	   return(NOCONNECTION);
    	   }

/* Encoding request by XDR to buf */
/* Buffer and stream allocation */
   buffSetVarialbe = (caddr_t)calloc(REQUESTLENGTH, 1);

   xdrmem_create(&xdrs, buffSetVarialbe, REQUESTLENGTH, XDR_ENCODE);

   xdr_int(&xdrs,&Request);
   xdr_string(&xdrs, &InstrName, strlen(InstrName));

/* Send Open Virtual Instrument request */

   if( send(SocketID,buffSetVarialbe,REQUESTLENGTH,0) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetVariable - Cannot open virtual instrument");
#endif
      perror("DD_SetVariable:");
      free(buffSetVarialbe);
      xdr_destroy(&xdrs);
      return(REQSENDERR);
   }
   xdrmem_create(&xdrs, buffSetVarialbe, REQUESTLENGTH, XDR_FREE);

/*--------  preparation an authorization request ----------------*/
c027acc9   Elena.Budnik   added username t...
334
   if(UserName[0] == '\0') {
493d59cf   Elena.Budnik   set UserName from...
335
336
337
338
339
340
	   
	   pDDuser = getenv ("DDUSER");
	 
	   if (pDDuser != NULL) strcpy(UserName, pDDuser);
	   else {
		   strcpy(UserName,NONAME);
c027acc9   Elena.Budnik   added username t...
341
342
343
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetVariable - UserName is undefined");
#endif
493d59cf   Elena.Budnik   set UserName from...
344
	   }
c027acc9   Elena.Budnik   added username t...
345
   }
a952e350   Benjamin Renard   First commit of D...
346
347
348
349
350
351
352
353
   hostlen = strlen(UserHost);
   userlen = strlen(UserName);
   
   xdrmem_create(&xdrs, buffSetVarialbe,REQUESTLENGTH, XDR_ENCODE);

   xdr_int(&xdrs,&UserID);
   xdr_string(&xdrs, &PUserHost, hostlen);
   xdr_string(&xdrs, &PUserName, userlen);
c027acc9   Elena.Budnik   added username t...
354
   //fprintf(stderr,"userid %d host %s DD_name %s\n",UserID,UserHost,UserName);  
a952e350   Benjamin Renard   First commit of D...
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
  
/* Send request */
   if( send(SocketID,buffSetVarialbe,REQUESTLENGTH,0) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetVariable - Cannot send request");
#endif
      perror("DD_Set_Variable:");
      free(buffSetVarialbe);
      xdr_destroy(&xdrs);
      return(REQSENDERR);
   }

   free(buffSetVarialbe);
   xdr_destroy(&xdrs);

/* Get reply */
   buffSetVarialbe = (caddr_t)malloc(REPLYLENGTH);
/*
   i=0;
   while(((cc = recv(SocketID,buff,REPLYLENGTH,0)) < 0) && (i < TRY)) i++;
*/
   if( ReceiveFromNet(buffSetVarialbe, REPLYLENGTH) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetVariable - Cannot receive from net");
#endif
      perror("DD_SET_Variable:");
      free(buffSetVarialbe);
      return(REPLYRECERR);
   }

   xdrmem_create(&xdrs, buffSetVarialbe, REPLYLENGTH, XDR_DECODE);
   xdr_int(&xdrs,&InstrID);

/* Free all */
   free(buffSetVarialbe);
   xdr_destroy(&xdrs);

   return InstrID;
}

/*----------------------- DD_GetInform -----------------------------*/
/*
 * Returns "OK" if OK, fill DD_Data structure
 * Return negative value if error
 */

int DD_Client::DD_GetInform(int VarID,char *AttrName,DD_data_t **data)
{
   XDR xdrs;
   caddr_t bufDD_GetInform = NULL;
   int length;
   int op = DATAINFOREQ;
   int type;               /* type of information or error */
   int DimNumbers;
   int PacketSize;
   u_int count;
   u_int MaxNumber;

/*------------------- Empty static data ------------------------*/
   if(idd.Dimensions != NULL)
   {
      free(idd.Dimensions);
      idd.Dimensions = NULL;
   }
   if(idd.Variables[0] != NULL)
   {
      free(idd.Variables[0]);
      idd.Variables[0] = NULL;
   }

/*------------------ Check the Name length -----------------------*/
   if(strlen(AttrName) > MAXVARLENGTH) length = MAXVARLENGTH;
   else length = strlen(AttrName);

/*----------- Allocation of memory and stream --------------------*/
   bufDD_GetInform = (caddr_t)calloc(REQUESTLENGTH,1);
   xdrmem_create(&xdrs, bufDD_GetInform, REQUESTLENGTH, XDR_ENCODE);

/*------------------- Encoding the request ----------------------*/
   xdr_int(&xdrs,&op);
   xdr_int(&xdrs,&VarID);
   xdr_string(&xdrs, &AttrName, length);

/*------------------------ Send request ---------------------------*/
   if( send(SocketID,bufDD_GetInform,REQUESTLENGTH,0) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_GetInform - Cannot send request");
#endif
      perror("DD_GetInform:");
      free(bufDD_GetInform);
      xdr_destroy(&xdrs);
      return(REQSENDERR);
   }
   free(bufDD_GetInform);
   xdr_destroy(&xdrs);

/*------------------------ Get reply header ------------------------*/

   bufDD_GetInform = (caddr_t)malloc(REPLYLENGTH);
/*
   i=0;
   while(((cc = recv(SocketID,buf,REPLYLENGTH,0)) < 0) && (i < TRY)) i++;
   if(cc < 0)
*/
   if(( ReceiveFromNet(bufDD_GetInform, REPLYLENGTH)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_GetInform - Cannot receive from net");
#endif
      perror("DD_GetInform:");
      free(bufDD_GetInform);
      return(REPLYRECERR);
   }

   xdrmem_create(&xdrs, bufDD_GetInform, REPLYLENGTH, XDR_DECODE);
   xdr_int(&xdrs,&type);
   if(type < 0)
   {
      free(bufDD_GetInform);
      xdr_destroy(&xdrs);
      return(type);
   }
   xdr_int(&xdrs,&DimNumbers);
   xdr_int(&xdrs,&PacketSize);
   free(bufDD_GetInform);
   xdr_destroy(&xdrs);

   idd.DimNumber = DimNumbers;
   idd.type = type;

/*---------------------------- Get Data Packet ----------------------*/
   if(PacketSize > 0) bufDD_GetInform = (caddr_t)malloc(PacketSize);
   else
   {
#ifdef LOG4CXX
	   LOG4CXX_ERROR(_logger, "DD_Client::DD_GetInform - Cannot Cannot get data packet");
#endif
	   return(REPLYRECERR);
   }

   if(( ReceiveFromNet(bufDD_GetInform, PacketSize)) < 0)
   {
#ifdef LOG4CXX
      LOG4CXX_ERROR(_logger, "DD_Client::DD_GetInform - Cannot receive from net");
#endif
      perror("DD_GetInform:");
      free(bufDD_GetInform);
      return(REPLYRECERR);
   }

/*--------------------- Decoding data packet ------------------------*/
   if(DimNumbers > 0)
   {
/*----------- Memory allocation and xdr creating -----------------*/
      xdrmem_create(&xdrs, bufDD_GetInform, (u_int)PacketSize, XDR_DECODE);

/*----------------- Dimensions decoding -------------------------*/
      if(idd.Dimensions !=NULL) free(idd.Dimensions);
      idd.Dimensions = (int *)malloc(DimNumbers*sizeof(int));

      xdr_array(&xdrs, (caddr_t *)&(idd.Dimensions),
                       &count,
                       (u_int )DimNumbers,
                       unixlen[DD_INT],
                       (xdrproc_t)xdr_int);

      count = 1;
      for(int i=0; i < DimNumbers;i++)
         count = count*idd.Dimensions[i];
      MaxNumber = count;
   }
   else
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_GetInform - Cannot decoding data packet");
#endif
      free(bufDD_GetInform);
      return(REPLYRECERR);
   }

/*---------------- Allocate memory for Variables and decoding ------------------*/
   if(idd.Variables[0] != NULL) free(idd.Variables[0]);
   idd.Variables[0] = (int *)malloc(unixlen[type] * MaxNumber);

   xdr_array(&xdrs,((caddr_t*)(&idd.Variables[0])),&count,
             MaxNumber, unixlen[type], ConvFunc[type]);

/*-------------------------- Free all ------------------------------*/
   free(bufDD_GetInform);
   xdr_destroy(&xdrs);

   *data = &idd;
   return OK;
}

/*------------------- DD_SETTIME ------------------------------------*/
/*
 * VarID - ID of Data Set
 * Time - string in DD type
 * Returns 1 if OK and negative in case of err
 */

int DD_Client:: DD_SetTime(int VarID,char *Time)
{
   int type;
   int DoneFlag = 0;

   while(DoneFlag == 0)
   {
/* Allocatein memory and stream */
   bufDD_SetTime = (caddr_t)calloc(REQUESTLENGTH, 1);
   xdrmem_create(&xdrsDD_SetTime, bufDD_SetTime, REQUESTLENGTH, XDR_ENCODE);

/* Encoding the request */
   xdr_int(&xdrsDD_SetTime,&op);
   xdr_int(&xdrsDD_SetTime,&VarID);
   xdr_string(&xdrsDD_SetTime, &Time, TIMELENGTH);

/* Send request */
   if(( send(SocketID,bufDD_SetTime,REQUESTLENGTH,0)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetTime - Cannot send request");
#endif
      perror("DD_SetTime:");
      free(bufDD_SetTime);
      xdr_destroy(&xdrsDD_SetTime);
      return(REQSENDERR);
   }
   free(bufDD_SetTime);
   xdr_destroy(&xdrsDD_SetTime);

/* Get reply header */

   bufDD_SetTime = (caddr_t)malloc(REPLYLENGTH);

   if(( ReceiveFromNet(bufDD_SetTime, REPLYLENGTH)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_SetTime - Cannot receive from net");
#endif
      perror("DD_SetTime:");
      free(bufDD_SetTime);
      return(REPLYRECERR);
   }

   xdrmem_create(&xdrsDD_SetTime, bufDD_SetTime, REPLYLENGTH, XDR_DECODE);
   xdr_int(&xdrsDD_SetTime,&type);

   free(bufDD_SetTime);
   xdr_destroy(&xdrsDD_SetTime);
       
   if(type < 0) 
   {
      if(type == CACHTOOREC) sleep((unsigned )(FILEACCMARG));
      else return type;
   }
   else DoneFlag = 1;
   } 
   return 1 ;
}

/*------------------- DD_SETTIMEINFO ------------------------------------*/
/*
 * VarID - ID of Data Set
 * Time - string in DD type
 * RealTime - double : time value pointer points to
 * Returns 1 if OK and negative in case of err
 */

int DD_Client:: DD_SetTimeInfo(int VarID, char *Time, double *RealTime)
{
    int err;

    DD_data_t *data; 
    
    if ((err = DD_SetTime(VarID, Time)) < 0)
    {
    	while ((err == WAITEXTCALL) || (err == TRYAGAIN))
    	{
    		sleep(2);
    		err = DD_SetTime(VarID, Time);
    	}
    }

    if (err < 1)
    {
#ifdef LOG4CXX
    	LOG4CXX_ERROR(_logger, "DD_Client::DD_SetTimeInfo - Cannot set time " << Time);
#endif
    	return err;
    }
    
    if ((err = DD_GetData(VarID, (char *)"Time", TimeInt, &data)) < 0)
    {
    	while ((err == WAITEXTCALL) || (err == TRYAGAIN))
        {
    		sleep(2);
        	err = DD_GetData(VarID, (char *)"Time", TimeInt, &data);
        }
    }

    if (err < 0)
    {
#ifdef LOG4CXX
    	LOG4CXX_ERROR(_logger, "DD_Client::DD_SetTimeInfo - Cannot get data " << Time);
#endif
    	return err;
    }
    if (data->VarNumber < 1)
    {
#ifdef LOG4CXX
    	LOG4CXX_ERROR(_logger, "DD_Client::DD_SetTimeInfo - OUTOFTIME error " << Time);
#endif
    	return OUTOFTIME;
    }

    *RealTime = DD_Time2Double((char *)data->Variables[0]);

    //BRE - When the corresponding time is the last one of a file, MOREDATA is returned by DDServer.
    // => force recall of DD_GetData to open the next file and finish correctly the request
    if (err == MOREDATA)
    {
    	if ((err = DD_GetData(VarID, (char *)"Time", TimeInt, &data)) < 0)
    	{
    		while ((err == WAITEXTCALL) || (err == TRYAGAIN))
    	    {
    			sleep(2);
    	        err = DD_GetData(VarID, (char *)"Time", TimeInt, &data);
    	    }
    	}
    }

   return 1 ;
}

/*------------------------- DD_GETDATA --------------------------------*/
/*
 * VarID - ID of open virtual instrument
 * VarName - Variable name associated with this virtual instrument
 * TimeInt - Time interval in DD_time style
 * data - returned data
 * Return values:
 *    positives:
 *    MOREDELAY - call this function again after delay
 *    MOREDATA - call this function again to complete request
 *    OK       - all data received
 *    negative value - error (see DD.h)
 */

int DD_Client::DD_GetData(int VarID,char *VarName,char *TimeInt,DD_data_t **data)
{
	   char *xxx=VarName;
	   int err = DD_GetMultiData(VarID, 1, &xxx, TimeInt, data, 1);
	   return err;
	}

/*------------------------- DD_GetMultiData() --------------------------------*/
/*---------------------------------------------------------
 * VarID - ID of open virtual instrument
 * VarSize - the size of the array names
 * VarNames - array of the variables names
 * TimeInt - Time interval in DD_time style
 * data - returned data
 * Return values:
 *    positives:
 *    MOREDELAY - call this function again after delay
 *    MOREDATA - call this function again to complete request
 *    OK       - all data received
 *    negative value - error (see DD.h)
 */
int DD_Client::DD_GetMultiData(int VarID,size_t VarSize, char **VarNames,char *TimeInt,DD_data_t **data, int BackFlag)
{
	size_t id;
	int *NameLength = NULL; /* Array of lengths */
	int XDRStrLen;          /* xdr length of a string */
	int XDRReqlength;  // Length in bytes the XDR stream
	int op = DATAGETREQ;
	int type;  /* type of information or error */
	int DimNumbers;
	int PacketSize;
	u_int count, MaxSize=0;
	int i;

	/*--------------------------------------
	 * Create a new Current Data empty array
	 *-------------------------------------*/
	for( int i = 0; i < _varNumber; ++i) {
		CurrentData[i].clear();
	}
	delete[] CurrentData;
	_varNumber = VarSize;
	CurrentData = new DD_data_t[_varNumber];

	/*--------------------------------------------------------------
	 * The follows request preparation and send is performed only
	 * if the priveous data packed is completely received
	 *--------------------------------------------------------------*/
	if((LastPacketFlag == OK) || (LastPacketFlag == MOREDELAY))
	{
		/*---------------------------------------
		 * Preparation of the array the name lengths
		 * Note that the names are cut down to the MAXVARLENGTH
		 * Calculation the packet size
		 *---------------------------------------*/
		NameLength = (int *)malloc(sizeof(int)*VarSize);
		XDRReqlength = 8; /* the length of the first+last arguments */
		for(id = 0; id < VarSize; id++)
		{
			if(strlen(VarNames[id]) > MAXVARLENGTH) NameLength[id] = MAXVARLENGTH;
			else NameLength[id] = strlen(VarNames[id]);
			XDRStrLen = (NameLength[id] / 4) * 4;
			if((NameLength[id] % 4) > 0) XDRStrLen += 4;
			XDRReqlength += XDRStrLen + 4; // String length + 4 bytes length coding
			//fprintf(stderr,"Variable %s, length %d, total %d\n",VarNames[id],XDRStrLen,XDRReqlength);
		}
		/*--------------------------------
		 * The first packet of the request of the standard size
		 * Allocation corresponding memory and stream
		 *------------------------------*/
		bufDD_GetData = (caddr_t)calloc(REQUESTLENGTH, 1);
		xdrmem_create(&xdrsDD_GetData, bufDD_GetData, REQUESTLENGTH, XDR_ENCODE);

		/* Encoding the request */
		xdr_int(&xdrsDD_GetData,&op);
		xdr_int(&xdrsDD_GetData,&VarID);
		xdr_string(&xdrsDD_GetData,&TimeInt,TIMELENGTH);
		xdr_int(&xdrsDD_GetData,&XDRReqlength);

		/* Send the first request */
		if(( send(SocketID,bufDD_GetData,REQUESTLENGTH,0)) < 0)
		{
#ifdef LOG4CXX
			LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Cannot send the first request");
#endif
			perror("DD_GetData: First Request");
			free(bufDD_GetData);
			free(NameLength);
			xdr_destroy(&xdrsDD_GetData);
			return(REQSENDERR);
		}
		free(bufDD_GetData);
		xdr_destroy(&xdrsDD_GetData);

		/*--------------------------------
		 * The Second packet of XDRReqlength size
		 * Allocation corresponding memory and stream
		 *------------------------------*/
		bufDD_GetData = (caddr_t)malloc(XDRReqlength);
		xdrmem_create(&xdrsDD_GetData, bufDD_GetData, XDRReqlength, XDR_ENCODE);
		xdr_int(&xdrsDD_GetData,(int *)(&VarSize));
		for(id = 0; id < VarSize; id++) xdr_string(&xdrsDD_GetData, &VarNames[id], NameLength[id]);

		free(NameLength);
		NameLength = NULL;
		xdr_int(&xdrsDD_GetData,&BackFlag);

		/* Send the second request */
		if(( send(SocketID,bufDD_GetData,XDRReqlength,0)) < 0)
		{
#ifdef LOG4CXX
			LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Cannot send the second request");
#endif
			perror("DD_GetData:Second Packet");
			free(bufDD_GetData);
			xdr_destroy(&xdrsDD_GetData);
			return(REQSENDERR);
		}
		free(bufDD_GetData);
		xdr_destroy(&xdrsDD_GetData);
	}

	/*-----------------------------------------------------------
	 * Get the VarSize reply headers and VarSize data
	 *----------------------------------------------------------*/
	for(id = 0; id < VarSize; id++)
	{
		/*-------------------
		 * The header
		 *-----------------*/
		bufDD_GetData = (caddr_t)malloc(REPLYLENGTH);
		if(( ReceiveFromNet(bufDD_GetData, REPLYLENGTH)) < 0)
		{
#ifdef LOG4CXX
			LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Cannot receive header");
#endif
			perror("DD_GetData:Error while header receive");
			free(bufDD_GetData);
			return(REPLYRECERR);
		}

		xdrmem_create(&xdrsDD_GetData, bufDD_GetData, REPLYLENGTH, XDR_DECODE);
		xdr_int(&xdrsDD_GetData,&type);
		xdr_int(&xdrsDD_GetData,&DimNumbers);
		xdr_int(&xdrsDD_GetData,&PacketSize);
		free(bufDD_GetData);
		xdr_destroy(&xdrsDD_GetData);

		if (type < 0) /* Server returns unrecoverable error */
		{
#ifdef LOG4CXX
			LOG4CXX_DEBUG(_logger, "DD_Client::DD_GetMultiData - Server returns " << type << ", no data\n");
#endif
			fprintf(stderr, "DD_GetData: Server returns %d, no data\n", type);
			return type;
		}

		/*----------- Header is received ----------------------*/
		CurrentData[id].DimNumber = DimNumbers - 1;
		CurrentData[id].type = type;

		/*--------------- Receive Data Packet ------------------------------*/
		if(PacketSize > 0) bufDD_GetData = (caddr_t)malloc(PacketSize);
		else
		{
#ifdef LOG4CXX
			LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Cannot receive data packet");
#endif
			return(REPLYRECERR);
		}
		if((ReceiveFromNet(bufDD_GetData, PacketSize)) < 0)
		{
#ifdef LOG4CXX
			LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Cannot receive data packet from web");
#endif
			perror("DD_GetData: Error while data packet receive");
			free(bufDD_GetData);
			return(REPLYRECERR);
		}
		/*----------------- Decoding data packet --------------------*/
		if(DimNumbers > 1)
		{
			xdrmem_create(&xdrsDD_GetData, bufDD_GetData, (u_int)PacketSize, XDR_DECODE);
			count = DimNumbers-1;
			/* allocation memory for dimensions */
			CurrentData[id].Dimensions = (int *)malloc((DimNumbers-1)*sizeof(int));

			xdr_int(&xdrsDD_GetData,&LastPacketFlag);        /* Last Paket Indicatort*/
			xdr_int(&xdrsDD_GetData,&CurrentData[id].VarNumber); /* Variables number */

			if(LastPacketFlag > 2)
			{
				LastPacketFlag = OK;
				CurrentData[id].VarNumber = 0;
				free(bufDD_GetData);
#ifdef LOG4CXX
				LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Reply received error");
#endif
				return(REPLYRECERR);
			}

			/*----- Decoding dimensions array -------------------*/
			xdr_array(&xdrsDD_GetData, (caddr_t *)&(CurrentData[id].Dimensions),
					&count,
					(u_int )DimNumbers-1,
					unixlen[DD_INT],
					(xdrproc_t)xdr_int);

			count = 1;
			for(i=0; i < DimNumbers-1;i++)
			{
				count = count*CurrentData[id].Dimensions[i];
			}
			MaxSize = count;
		}
		else {
			if (type != NOVAR) {
#ifdef LOG4CXX
				LOG4CXX_ERROR(_logger, "DD_Client::DD_GetMultiData - Reply received error");
#endif
				free (bufDD_GetData);
				return (REPLYRECERR);
			} else {
				CurrentData[id].VarNumber = 0;
			}
		}

		/*---------- Decoding variables -------------------------*/
		if (CurrentData[id].VarNumber != 0) {
			CurrentData[id].Variables = (void **) malloc(CurrentData[id].VarNumber * sizeof(void *));
		} else {
			CurrentData[id].Variables = NULL;
		}

		for(i = 0; i < CurrentData[id].VarNumber; i++)
		{
			CurrentData[id].Variables[i] = (void *)malloc(unixlen[type]*MaxSize);
			count = MaxSize;
			xdr_array(&xdrsDD_GetData,(caddr_t *)(&(CurrentData[id].Variables[i])),&count,MaxSize,unixlen[type], (xdrproc_t)ConvFunc[type]);
		}

		/* Free all */
		free(bufDD_GetData);
		xdr_destroy(&xdrsDD_GetData);
	}
	*data = CurrentData;
	return(LastPacketFlag);
}

/*===================================================================*/

/*-------------------------- DD_CLOSE --------------------------------*/
/*
 *
 * VarID - entry point of ID table
 * Returns 1 if OK or negative err
 * Close Socket if no VarID more ( this information supplyed by server )
 */

int DD_Client:: DD_Close(int VarID)
{
   int RemainedID;                 /* Server returns number of remained ID */
/* Allocatein memory and stream */
   bufDD_Close = (caddr_t)calloc(REQUESTLENGTH, 1);
   xdrmem_create(&xdrsDD_Close, bufDD_Close, REQUESTLENGTH, XDR_ENCODE);

/* Encoding the request */
   xdr_int(&xdrsDD_Close,&opDD_Close);
   xdr_int(&xdrsDD_Close,&VarID);

/* Send request */
   if(( send(SocketID,bufDD_Close,REQUESTLENGTH,0)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_Close - Cannot send request " << VarID);
#endif
      perror("DD_Close:");
      free(bufDD_Close);
      xdr_destroy(&xdrsDD_Close);
      return(REQSENDERR);
   }
   free(bufDD_Close);
   xdr_destroy(&xdrsDD_Close);

/* Get reply header */

   bufDD_Close = (caddr_t)malloc(REPLYLENGTH);
/*
   i = 0;
   while(((cc = recv(SocketID,buf,REPLYLENGTH,0)) < 0) && (i < TRY)) i++;
   if(cc < 0)
*/
   if(( ReceiveFromNet(bufDD_Close, REPLYLENGTH)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_Close - Cannot receive from net " << VarID);
#endif
      perror("DD_Close:");
      free(bufDD_Close);
      return(REPLYRECERR);
   }

   xdrmem_create(&xdrsDD_Close, bufDD_Close, REPLYLENGTH, XDR_DECODE);
   xdr_int(&xdrsDD_Close,&RemainedID);
   if(RemainedID< 0)
   {
      free(bufDD_Close);
      xdr_destroy(&xdrsDD_Close);
      return(RemainedID);
   }
   free(bufDD_Close);
   xdr_destroy(&xdrsDD_Close);

   if(RemainedID == 0) 
   {
     shutdown(SocketID,2);
     close(SocketID);
     SocketID = -1;
/*     
       UserHost[0] = '\0';
       UserName[0] = '\0';
*/
   }

   return(1);
}

DD_Client::~DD_Client() {

	   for( int i = 0; i < _varNumber; ++i) {
		   CurrentData[i].clear();
	   }
	   delete[] CurrentData;
}

/*------------------------------------------------------------------------------*/

/*=============== DATABASE UPDATE FUNCTIONS ====================================*/
/*------------------ DD_AddDataSet() -------------------------------------------*/
int DD_Client:: DD_AddDataSet(char *DataSetName, char *RemSetID, char *BaseName)
{

   int Err;                      /* Server returns OK or NOEXEC */
   int length;
   int CloseFlag = 0;
   
/* If there is no connection, try to get it */
   if(SocketID < 0)
   {
       if((SocketID = GetSocket()) < 0)
       {
#ifdef LOG4CXX
    	   LOG4CXX_ERROR(_logger, "DD_Client::DD_AddDataSet - No connection");
#endif
    	   return(NOCONNECTION);
       }
       CloseFlag = 1; // To close Connection at the end
   }

/* Allocatein memory and stream */
   bufDD_AddDataSet = (caddr_t)malloc(REQUESTLENGTH);
   xdrmem_create(&xdrsDD_AddDataSet, bufDD_AddDataSet, REQUESTLENGTH, XDR_ENCODE);

/* Encoding the request */
   xdr_int(&xdrsDD_AddDataSet,&opDD_AddDataSet);

/* Coding DataSetName */
      if((length = strlen(DataSetName)) > MAXSETLENGTH) length = MAXSETLENGTH;
      xdr_string(&xdrsDD_AddDataSet, &DataSetName, length);
/* Coding RemSetID */
      if((length = strlen(RemSetID)) > MAXVARLENGTH) length = MAXVARLENGTH;
      xdr_string(&xdrsDD_AddDataSet,   &RemSetID, length);
/* Coding BaseName */
      if((length = strlen(BaseName)) > MAXVARLENGTH) length = MAXVARLENGTH;
      xdr_string(&xdrsDD_AddDataSet, &BaseName, length);

/* Send request */
   if(( send(SocketID,bufDD_AddDataSet,REQUESTLENGTH,0)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_AddDataSet - Cannot send request");
#endif
      perror("DD_AddDataSet:");
      free(bufDD_AddDataSet);
      xdr_destroy(&xdrsDD_AddDataSet);
      return(REQSENDERR);
   }
   free(bufDD_AddDataSet);
   xdr_destroy(&xdrsDD_AddDataSet);

/* Get reply header */
   bufDD_AddDataSet = (caddr_t)malloc(REPLYLENGTH);
   if(( ReceiveFromNet(bufDD_AddDataSet, REPLYLENGTH)) < 0)
   {
#ifdef LOG4CXX
	  LOG4CXX_ERROR(_logger, "DD_Client::DD_AddDataSet - Cannot receive from net");
#endif
      perror("DD_AddDataSet:");
      free(bufDD_AddDataSet);
      return(REPLYRECERR);
   }

   xdrmem_create(&xdrsDD_AddDataSet, bufDD_AddDataSet, REPLYLENGTH, XDR_DECODE);
   xdr_int(&xdrsDD_AddDataSet,&Err);
   
   if(CloseFlag)  // Close everything if function established connection
   {
     shutdown(SocketID,2);
     close(SocketID);
     SocketID = -1;
/*   Session with DD Server was closed, but User Session continues !!!!! */
  /*   UserHost[0] = '\0';
       UserName[0] = '\0';  */
   }
   return Err;
}
/*-----------------------------------------------------------------------------*/

/*---------------------- DD GET VERSION ---------------------------------------*/
const char *DD_Client:: DD_GetVersion()
/*
 * return static pointer to internal string with the DDLIB-SERVER package version
 */
{
    return Version;
}
/*------------------------- End Library -------------------------------*/