File: register.c

package info (click to toggle)
nws 2.11-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,700 kB
  • ctags: 2,820
  • sloc: ansic: 28,849; sh: 3,289; java: 1,205; makefile: 697; perl: 12
file content (1121 lines) | stat: -rw-r--r-- 26,754 bytes parent folder | download
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
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
/* $Id: register.c,v 1.104 2004/11/09 22:24:06 graziano Exp $ */

#include "config_nws.h"

#include <stdlib.h>
#include <string.h>         /* memcpy() strchr() strnlen() strstr() */

#include "diagnostic.h"     /* ERROR() FAIL() WARN() */
#include "strutil.h"        /* SAFESTRCPY() strmatch() vstrncpy() */
#include "messages.h"       /* Recv*() Send*() */
#include "osutil.h"         /* CurrentTime() */
#include "nws_messages.h" /* Nameserver-specific messages */
#include "register.h"

/*
** Note: We hold object sets in the format used by the name server: an object
** is a tab-delimited, tab-pair-terminated list of attribute:value pairs.  An
** object set is simply a list of these.
*/

/*
** Values returned from NwsAttribute{Name,Value}.  We switched from static, fixed-
** size arrays to allocated items because the potential length (of values, at
** least) is unbounded.  This could cause a memory leak, but, since attributes
** only exist within objects, we can be assured of freeing the memory by
** checking the variable values within Free{Object,ObjectSet}.
*/
static char *currentName = NULL;
static char *currentValue = NULL;

/* it should be thread safe (given you are not overlapping memory used by
 * the parameters) */
void
AddNwsAttribute(	Object *toObject,
			const char *addName,
			const char *addValue) {

	Object expanded;
	size_t expandedLen, objectLen;
	const char *separator; 

	/* sanity check */
	if (addName == NULL || addValue == NULL || toObject == NULL) {
		return;
	}

	objectLen = strlen(*toObject);
	separator = (objectLen == (OBJECT_TERMINATOR_LEN)) ? "" : ATTRIBUTE_TERMINATOR;

	expandedLen = objectLen + strlen(separator) + strlen(addName) +
			(NAME_TERMINATOR_LEN) + strlen(addValue) + 1;

	expanded = (Object)REALLOC(*toObject, expandedLen);
	if(expanded == NULL) {
		ABORT("AddNwsAttribute: out of memory\n");
	}
	
	/* Overwrite the existing object terminator. */
	vstrncpy(expanded + objectLen - (OBJECT_TERMINATOR_LEN),
		expandedLen - objectLen + (OBJECT_TERMINATOR_LEN), 5,
		separator, addName, NAME_TERMINATOR, addValue, 
		OBJECT_TERMINATOR);
	*toObject = expanded;
}


void
AddOptionToObject(	Object *toObject,
			const char *options) {
	char *name, *value, *next;
                                                                           
	for (next = NextNwsAttribute((Object)options, NO_ATTRIBUTE); next != NO_ATTRIBUTE; next = NextNwsAttribute((Object)options, next)) {
		name = NwsAttributeName_r(next);
		value = NwsAttributeValue_r(next);
		if (name == NULL || value == NULL) {
			INFO("AddOptionToObject: cannot get options\n");
		} else {
			AddNwsAttribute(toObject, name, value);
		}
		FREE(name);
		FREE(value);
	}
}


/* 
 * delete an NwsAttribute/NwsValue pair from an object 
 */
int
DeleteNwsAttribute(	Object *fromObject,
			const char *attr) {

	char *tmp, *tmp1;
	Object shrunk;

	/* is the attribute in object? */
	tmp = FindNwsAttribute(*fromObject, attr);
	if (tmp == NULL) {
		return 0;
	}

	/* let's remove it from the object */
	tmp1 = strstr(tmp, ATTRIBUTE_TERMINATOR);
	if (tmp1 == NULL) {
		/* something happended! */
		ERROR("DeleteNwsAttribute: couldn't find endOfAttribute!\n");
		return 0;
	}
	memmove(tmp, tmp1+1, strlen(tmp1+1)+1);	/* copy the \0 too */
	shrunk = (Object)REALLOC(*fromObject, sizeof(char)*(strlen(*fromObject)+1));
	if (shrunk == NULL) {
		ERROR("DeleteNwsAttribute: realloc failed\n");
		return 0;
	}
	*fromObject = shrunk;
	
	return 1;
}

/* 
 * check if 2 objects are "equivalent". It should be thread safe (uses _r
 * version of NwsAttributeValue).
 *
 * returns 0 if they are different
 * 	   1 if they are equivalent
 */
int
AreObjectsEquivalent(	const Object lhs,
			const Object rhs) {

	const char *names[] = {"name", "objectclass", "activity", "port",
		"owner", "hostType", "controlName", "skillName", "option",
		"resource", "size", "period", "memory", NULL};
	char *val, *val1;
	int i, done = 1;

	/* sanity check */
	if (lhs == NO_OBJECT && rhs == NO_OBJECT) {
		return 1;
	}
	if (lhs == NO_OBJECT || rhs == NO_OBJECT) {
		return 0;
	}

	/* let's compare them */
	for (i=0; done == 1 && names[i] != NULL; i++) {
		val = NwsAttributeValue_r(FindNwsAttribute(lhs, names[i]));
		val1 = NwsAttributeValue_r(FindNwsAttribute(rhs, names[i]));
		if (val == NULL && val1 == NULL) 
			/* no such attribute in both objects */
			continue;
		if (val == NULL || val1 == NULL || strcmp(val, val1) != 0) {
			/* they are different */
			done = 0; 
		}
		FREE(val);
		FREE(val1);
	}
	return done;
}

/*
 * add an object to the the object set iff it's not already there.
 * Returns 1 upon success 0 otherwise.
 */
int
AddObject(ObjectSet *toSet,
          const Object addObject) {

	const char *endObject;
	ObjectSet expanded;
	size_t objectLen;
	size_t setLen;

	/* sanity checks */
	if (toSet == NULL || *toSet == NULL || addObject == NULL) {
		ERROR("AddObject: NULL parameter\n");
		return 0;
	}
	setLen = strlen(*toSet);
	endObject = strstr(addObject, OBJECT_TERMINATOR);
	if (endObject == NULL) {
		ERROR1("AddObject: %s doesn't have Object terminator\n", addObject);
		return 0;
	}
	objectLen = endObject - addObject + OBJECT_TERMINATOR_LEN;

	/* let's go on and add the object */
	expanded = (ObjectSet)REALLOC(*toSet, setLen + objectLen + 1);
	if(expanded == NULL) {
		ERROR("AddObject: out of memory\n");
		return 0;
	}

	strncat(expanded, addObject, objectLen);
	*toSet = expanded;

	return 1;
}



char *
NwsAttributeName_r(const NwsAttribute ofNwsAttribute) {
	const char *endOfName;
	size_t nameLen;
	char *name = NULL;

	/* sanity check */
	if (ofNwsAttribute == NULL)
		return NULL;

	endOfName = strstr(ofNwsAttribute, NAME_TERMINATOR);

	if(endOfName != NULL) {
		nameLen = endOfName - ofNwsAttribute;
		name = (char *)MALLOC(nameLen + 1);
		if(name == NULL) {
			ABORT("NwsAttributeName: out of memory\n");
		} else {
			memcpy(name, ofNwsAttribute, nameLen);
			name[nameLen] = '\0';
		}
	}
	return(name);
}

char *
NwsAttributeValue_r(const NwsAttribute ofNwsAttribute) {

	const char *endOfName;
	const char *endOfValue;
	size_t valueLen;
	char *value = NULL;

	/* sanity check */
	if (ofNwsAttribute == NULL)
		return NULL;

	endOfName = strstr(ofNwsAttribute, NAME_TERMINATOR);
	if(endOfName == NULL) {
		return NULL;
	}

	endOfValue = strstr(endOfName + 1, ATTRIBUTE_TERMINATOR);
	if(endOfValue == NULL) {
		/* there is no terminator: let's get to the end of the
		 * string */
		endOfValue = endOfName + strlen(endOfName);
	}

	valueLen = endOfValue - endOfName - 1;
	value = (char *)MALLOC(valueLen + 1);
	if(value == NULL) {
		ABORT("NwsAttributeValue_r: out of memory\n");
	} else {
		memcpy(value, endOfName + 1, valueLen);
		value[valueLen] = '\0';
	}

	return(value);

}


/* it should be thread safe */
NwsAttribute
FindNwsAttribute(const Object ofObject,
                 const char *name) {
	size_t nameLen;
	NwsAttribute nextAttr;

	/* some sanity check */
	if (name == NULL || ofObject == NO_OBJECT) {
		return NULL;
	}

	nameLen = strlen(name);

	for(nextAttr = NextNwsAttribute(ofObject, NO_ATTRIBUTE); nextAttr != NO_ATTRIBUTE; nextAttr = NextNwsAttribute(ofObject, nextAttr)) {
		if((strncasecmp(nextAttr, name, nameLen) == 0) &&
				(*(nextAttr + nameLen) == ':')) {
			break;
		}
	}
	return nextAttr;
}


/* it should be thread safe */
NwsAttribute
NextNwsAttribute(	const Object ofObject,
			const NwsAttribute preceding) {
	char *nextOne;
	
	/* sanity check */
	if (ofObject == NO_OBJECT || ofObject[0] == '\0') {
		return NO_ATTRIBUTE;
	}

	/* if there is no preceding returns the pointer to the object
	 * itself */
	if (preceding == NULL) {
		nextOne = ofObject;
	} else {
		nextOne = strstr(preceding, ATTRIBUTE_TERMINATOR);
		if (nextOne == NULL) {
			return NO_ATTRIBUTE;
		}
		nextOne += ATTRIBUTE_TERMINATOR_LEN;
	}

	return((*nextOne == '\t') ? NO_ATTRIBUTE : nextOne);
}


/* thread safe: just playing with pointer inside an Object itself */
Object
NextObject(const ObjectSet ofSet,
           const Object preceding) {
	char *nextOne, *tmp;
	
	/* sanity check */
	if (ofSet == NULL)  {
		return NO_OBJECT;
	}
	
	/* if no preceding, return the object itself */
	if (preceding == NO_OBJECT) {
		nextOne = ofSet;
	} else {
		tmp = strstr(preceding, OBJECT_TERMINATOR);
		if (tmp == NULL) {
			return NO_OBJECT;
		}
		nextOne = tmp + (OBJECT_TERMINATOR_LEN);
	}

	return((*nextOne == '\0') ? NO_OBJECT : nextOne);
}

void
FreeObject(Object *toBeFreed) {
	if(*toBeFreed != NO_OBJECT) {
		FREE(*toBeFreed);
	}
}


void
FreeObjectSet(ObjectSet *toBeFreed) {
	FREE(*toBeFreed);
}


Object
NewObject(void) {
	return(strdup(OBJECT_TERMINATOR));
}


ObjectSet
NewObjectSet(void) {
	return(strdup(""));
}

void
MakeHostCookie(	const char *host_name,
		short host_port,
		struct host_cookie *host_c) {
	SAFESTRCPY(host_c->name, host_name);
	host_c->port = host_port;
	host_c->sd = NO_SOCKET;
}

const char *
HostCImage(const struct host_cookie *host_c) {
	static char returnValue[255];

	sprintf(returnValue, "%s:%d", host_c->name, host_c->port);
	return &returnValue[0];
}

int
Host2Cookie(const char *image,
           unsigned short defaultPort,
           struct host_cookie *cookie) {

	char *c;
	char *fullName = NULL;
	IPAddress hostAddress;

	/* sanity check */
	if (image == NULL || cookie == NULL) {
		WARN("Host2Cookie: invalid parameters\n");
		return 0;
	}

	if (cookie->name != image) {
		SAFESTRCPY(cookie->name, image);
	}
	cookie->port = defaultPort;

	c = strchr(cookie->name, ':');
	if (c != NULL) {
		/* remove the port part ... */
		*c = '\0';
		/* ... and override the default port */
		cookie->port = (unsigned short)strtol(c + 1, NULL, 10);
	}

	/* Normalize to an all-lowercase, fully-qualified DNS name. */
	if(IPAddressValue(cookie->name, &hostAddress)) {
		/* we got an IP address: let's convert to a name */
		fullName = IPAddressMachine_r(hostAddress);
		if (fullName && *fullName == '\0') {
			FREE(fullName);
		}
	}
	if (fullName == NULL) {
		WARN1("Host2Cookie: couldn't resolve %s\n", cookie->name);
	} else {
		/* we got something useful */
		SAFESTRCPY(cookie->name, fullName);
		FREE(fullName);
	}
	strcase(cookie->name, ALL_LOWER);

	/* no socket yet */
	cookie->sd = NO_SOCKET;

	return 1;
}

int
ConnectToHost(	struct host_cookie *host_c,
		int *sd) {

	int addrCount;
	IPAddress addrs[MAX_ADDRESSES], addr;
	int i, ret;
	char *tmp;

	/* sanity check */
	if (host_c == NULL) {
		ERROR("ConnectToHost: NULL cookie\n");
		if (sd != NULL) {
			*sd = NO_SOCKET;
		}
		return 0;
	}

	/* we use strlen so we put a EOS at the end (should already be
	 * terminated anyway */
	host_c->name[sizeof(host_c->name) - 1] = '\0';

	/* now it gets somethwat weird: we are getting all the possible
	 * inet address we can find for this host. We then check if the
	 * socket belongs to the right host. 
	 */
	addrCount = IPAddressValues(host_c->name, addrs, MAX_ADDRESSES);
	if(addrCount == 0) {
		WARN1("ConnectToHost: failed to resolve %s\n", host_c->name);
	}

	ret = 0;
	if(IsOkay(host_c->sd)) {
		/* did we resolve the name? */
		if (addrCount > 0) {
			/* let's check if the socket is indeed the for
			 * the right peer */
			addr = Peer(host_c->sd);
			for (i = 0; i < addrCount; i++) {
				if (addr.addr != 0 && addrs[i].addr == addr.addr) {
					ret = 1;
					break;
				}
			}
		} else if (addrCount == 0) {
			/* addCount is 0, so we have no idea what is the
			 * inet address of this host: we hope this is
			 * a good socket */
			ret = 1;
		}
	}

	/* do we have a good socket? */
	if (ret == 0) {
		/* nope: trying to get a new one.  let's drop a possibly
		 * old socket */
		DROP_SOCKET(&host_c->sd);
		for(i = 0; i < addrCount; i++) {
			if(CallAddr(addrs[i], host_c->port, &host_c->sd, -1)) {
				/* got a good socket */
				ret = 1;
				break;
			}
		}
	}

	if (ret == 1) {
		/* assign the socket */
		if (sd != NULL) {
			*sd = host_c->sd;
		}

		/* we have a good socket: let's check if the cookie is
		 * good (name and port are set that is) */
		if (host_c->name[0] == '\0') {
			/* name */
			tmp = PeerName_r(host_c->sd);
			SAFESTRCPY(host_c->name, tmp);
			FREE(tmp);
			/* port */
			host_c->port = PeerNamePort(host_c->sd);
		}
	} else {
		/* no socket here */
		ERROR1("ConnectToHost: connect to %s failed\n", HostCImage(host_c));
	}

	return ret;
}

int
ConnectToObject(Object reg, struct host_cookie *cookie) {
	const char *ip;
	char *name, tmp[64];
	int ret;
	struct host_cookie tmpCookie;

	/* sanity check */
	if (reg == NULL || cookie == NULL) {
		ERROR("ConnectToObject: registration or cookie is NULL\n");
		return 0;
	}

	/* let's get the port */
	name = NwsAttributeValue_r(FindNwsAttribute(reg, "port"));
	if (name == NULL) {
		ERROR("ConnectToObject: object doesn't have 'port'\n");
		return 0;
	}
	tmpCookie.port = (unsigned short)strtol(name, NULL, 10);
	FREE(name);
	
	/* we can have multiple IPs so let's try to connect to all of
	 * them: we take the first one to be succesfull */
	name = NwsAttributeValue_r(FindNwsAttribute(reg, "ipAddress"));
	if (name == NULL) {
		ERROR("ConnectToObject: object doesn't have 'ipAddress'\n");
		return 0;
	}
	ret = 0;
	for (ip = name; GETTOK(tmp, ip, ",", &ip) != 0; ) {
		/* let's see if we talk to this IP */
		SAFESTRCPY(tmpCookie.name, tmp);
		tmpCookie.sd = cookie->sd;

		if (ConnectToHost(&tmpCookie, NULL)) {
			/* got it: we have a connection */
			SAFESTRCPY(cookie->name, tmpCookie.name);
			cookie->port = tmpCookie.port;
			
			/* did we get a new socket? */
			if (cookie->sd != tmpCookie.sd) {
				/* let's drop a possibly old socket */
				DROP_SOCKET(&cookie->sd);

				/* and get the new one in */
				cookie->sd = tmpCookie.sd;
			}
			ret = 1;
			break;
		}
	}
	FREE(name);

	if (ret == 0) {
		 /* no socket here */
		name = NwsAttributeValue_r(FindNwsAttribute(reg, "name"));
		if (name != NULL) {
			ERROR1("ConnectToObject: failed to connect to %s\n", name);
		} else {
			ERROR1("ConnectToObject: failed to connect to %s\n", reg);
		}
		FREE(name);
	}
	
	return ret;
}

int
Register(struct host_cookie *withWho,
         const Object object,
         double forHowLong) {

	unsigned long expiration;
	DataDescriptor objectDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	Socket sd;
	DataDescriptor timeDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
	char *tmp;

	/* sanity check */
	tmp = strstr(object, OBJECT_TERMINATOR);
	if (tmp == NULL) {
		ERROR1("Register: 'object' is not terminated (%s)\n", object);
		return (0);
	}

	/* we pick only the first object (in case there are multiple) */
	objectDescriptor.repetitions = tmp - object + (OBJECT_TERMINATOR_LEN);
	if(!ConnectToHost(withWho, &sd)) {
		FAIL1("Register: failed to connect to %s\n", HostCImage(withWho));
	}

	expiration = (unsigned long)forHowLong;

	if(!SendMessageAndDatas(sd,
                          NS_REGISTER,
                          object,
                          &objectDescriptor,
                          1,
                          &expiration,
                          &timeDescriptor,
                          1,
                          -1)) {
		DROP_SOCKET(&withWho->sd);
		FAIL("Register: send message failed\n");
	}

	/* we don't check for the ack here anymore: look in
	 * host_protcol.c */

	return(1);
}

int
RetrieveObjects(struct host_cookie *whoFrom,
                const char *filter,
                ObjectSet *retrieved,
		int timeout) {

	DataDescriptor filterDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	ObjectSet filtered;
	DataDescriptor objectsDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	size_t replySize;
	Socket sd;

	/* sanity check */
	if (whoFrom == NULL || filter == NULL || retrieved == NULL) {
		WARN("RetrieveObjects: NULL parameter(s)\n");
		return 0;
	}

	if(!ConnectToHost(whoFrom, &sd)) {
		FAIL("RetrieveObject: unable to contact name server.\n");
	}

	filterDescriptor.repetitions = strlen(filter) + 1;
	if(!SendMessageAndData(sd,
                         NS_SEARCH,
                         filter,
                         &filterDescriptor,
                         1,
                         timeout)) {
		DROP_SOCKET(&whoFrom->sd);
		FAIL("RetrieveObjects: send failed\n");
	} else if(!RecvMessage(sd,
                       NS_SEARCHED,
                       &replySize,
                       timeout)) {
		DROP_SOCKET(&whoFrom->sd);
		FAIL("RetrieveObjects: message receive failed\n");
	}

	filtered = (ObjectSet)MALLOC(replySize + 1);
	if(filtered == NULL) {
		FAIL("RetrieveObjects: out of memory\n");
	}

	objectsDescriptor.repetitions = replySize;
	if(!RecvData(sd,
			filtered,
			&objectsDescriptor,
			1,
			timeout)) {
		FREE(filtered);
		DROP_SOCKET(&whoFrom->sd);
		FAIL("RetrieveObjects: data receive failed\n");
	}
	filtered[objectsDescriptor.repetitions] = '\0';
	*retrieved = filtered;

	return(1);
}


int
Unregister(struct host_cookie *withWho,
           const char *filter) {

	DataDescriptor filterDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	Socket sd;

	if(!ConnectToHost(withWho, &sd)) {
		FAIL("Unregister: unable to contact name server.\n");
	}

	filterDescriptor.repetitions = strlen(filter) + 1;
	if(!SendMessageAndData(sd,
                         NS_UNREGISTER,
                         filter,
                         &filterDescriptor,
                         1,
                         -1)) {
		DROP_SOCKET(&withWho->sd);
		FAIL("Unregister: send failed\n");
	}

	/* we don't check for the ack here anymore: look in
	 * host_protcol.c */

	return 1;
}


/* DEPRECATED: the following functions are not thread safe: use the _r
 * version */
const char *
NwsAttributeName(const NwsAttribute ofNwsAttribute) {

	const char *endOfName;
	size_t nameLen;

	/* sanity check */
	if (ofNwsAttribute == NULL)
		return NULL;

  if(currentName != NULL) {
    FREE(currentName);
  }

  endOfName = strstr(ofNwsAttribute, NAME_TERMINATOR);

  if(endOfName != NULL) {
    nameLen = endOfName - ofNwsAttribute;
    currentName = (char *)MALLOC(nameLen + 1);
    if(currentName != NULL) {
      memcpy(currentName, ofNwsAttribute, nameLen);
      currentName[nameLen] = '\0';
    }
  }

  return(currentName);

}
const char *
NwsAttributeValue(const NwsAttribute ofNwsAttribute) {

	const char *endOfName;
	const char *endOfValue;
	size_t valueLen;

	/* sanity check */
	if (ofNwsAttribute == NULL)
		return NULL;

  if(currentValue != NULL) {
    FREE(currentValue);
  }

  endOfName = strstr(ofNwsAttribute, NAME_TERMINATOR);
  if(endOfName == NULL) {
    return NULL;
  }

  endOfValue = strstr(endOfName + 1, ATTRIBUTE_TERMINATOR);
  if(endOfValue == NULL) {
    return NULL;
  }

  valueLen = endOfValue - endOfName - 1;
  currentValue = (char *)MALLOC(valueLen + 1);
  if(currentValue != NULL) {
    memcpy(currentValue, endOfName + 1, valueLen);
    currentValue[valueLen] = '\0';
  }

  return(currentValue);

}

/*-------------- struct registrations functions ---------*/
/* the following functions operates on elements of struct registrations */

/*
 * initialize a registrations structure, Returns 0 on failure (out of
 * memory).
 */
int
InitRegistrations(registrations **r) {
	*r = (registrations *) MALLOC(sizeof(registrations));
	if (*r == NULL) {
		return 0;
	}
	(*r)->howMany = 0;
	(*r)->dirty = 0;
	(*r)->vals = NULL;
	(*r)->expirations = NULL;

	return 1;
}
	

/* 
 * simply check if there is enough space for an extra element in #r#
 * (registrations). If not, adds REG_CHUNCK elelments to it
 */
#define REG_CHUNK (512)
void
CheckRegistrations(registrations *r) {

	/* do we have extra elements handy? */
	if (r->dirty <= 0) {
		/* we don't have extra one: we have to realloc */
		r->vals = (char **)REALLOC((void *)r->vals, sizeof(char *)*(r->howMany+REG_CHUNK));
		/* let's make room for the expirations */
		r->expirations = (unsigned long *)REALLOC((void*)r->expirations, sizeof(long)*(r->howMany+REG_CHUNK));
		/* check */
		if (r->vals == NULL || r->expirations == NULL) {
			ABORT("CheckRegistrations: out of memory\n");
		}

		/* let's zeroes the pointers */
		memset(&(r->vals[r->howMany]), 0, sizeof(char *)*REG_CHUNK);
		r->dirty += REG_CHUNK;
	}
}

/* insert #registration# with #expiration# in #r#. It keeps the list ordered:
 * objects that AreObjectsEquivalent will be substituted with the new
 * one. If there is no such object, it will be added in the right place.
 * Returns 0 on failure, on success returns 1. */
int
InsertRegistration(	registrations *r,
			const Object object,
			unsigned long expiration,
			int i) {
	char *name, *newName, *obj;
	char **tmp;
	unsigned long *tmp_l;

	/* sanity check */
	if (r == NULL || object == NULL) {
		ERROR("InsertRegistration: wrong parameter\n");
		return 0;
	}
	name = strstr(object, OBJECT_TERMINATOR);
	if (name == NULL) {
		ERROR("InsertRegistration: object with no termination\n");
		return 0;
	}

	/* we get only the first object (in case there are more then one) */
	obj = (char *)MALLOC(name - object + OBJECT_TERMINATOR_LEN + 1);
	if (obj == NULL) {
		ABORT("InsertRegistration: out of memory\n");
	}
	memcpy(obj, object, name - object + OBJECT_TERMINATOR_LEN);
	obj[name - object + OBJECT_TERMINATOR_LEN] = '\0';
	newName = NwsAttributeValue_r(FindNwsAttribute(obj, "name"));
	if (newName == NULL) {
		FREE(obj);
		ERROR("InsertRegistration: registration with no name!\n");
		return 0;
	}
	FREE(newName);

	/* let's check we have enough room for an extra registration */
	CheckRegistrations(r);

	/* let's move the pointers one up to make room for the
	 * new registration */
	tmp = r->vals;
	tmp += i;
	memmove(tmp + 1, tmp, sizeof(char*)*(r->howMany - i));
	/* move the expirations */
	tmp_l = r->expirations;
	tmp_l += i;
	memmove(tmp_l + 1, tmp_l, sizeof(long)*(r->howMany - i));

	/* we have an extra registration */
	r->howMany++;
	r->dirty--;

	/* let's copy the registration */
	r->vals[i] = obj;
	r->expirations[i] = expiration;

	return 1;
}

/* delete the registration at #ind# from #r#. Returns 0 on failure */
int
DeleteRegistration(	registrations *r,
			int ind) {
	char **tmp;
	unsigned long *tmp_l;

	/* sanity check */
	if (r == NULL || ind >= r->howMany) {
		ERROR("DeleteRegistration: wrong parameters\n");
		return 0;
	}

	/* free the memory */
	FREE(r->vals[ind]);

	/* move all the registrations */
	tmp = r->vals;
	tmp += ind;
	memmove(tmp, tmp + 1, sizeof(char *)*(r->howMany - ind - 1));
	/* moved the expirations */
	tmp_l = r->expirations;
	tmp_l += ind;
	memmove(tmp_l, tmp_l + 1, sizeof(long)*(r->howMany - ind - 1));

	/* adjust the numbers of current registrations */
	r->howMany--;
	r->dirty++;

	return 1;
}




/* it looks for #name# in the values of the 'name' attribute in the
 * registrations #r#. It returns the positions where the #name# belongs
 * in #r# in #index# (it can returns r->howMany!): it returns 1 if at
 * least an objects was found (and the higher index if more than one was
 * present) or 0 if the objects would need to be inserted. If
 * #matchExact# is not set, returns success when matching up to
 * strlen(name), not the length of the registration's name.
 */
int 
SearchForName(	registrations *r,
		const char *name,
		int matchExact,
		int *ind) {
	int i, ln, done, len;
	double offset;
	char *tmp;

	/* sanity check */
	if (name == NULL || r == NULL || ind == NULL) {
		WARN("SearchForName: NULL parameters\n");
		return 0;
	}
	len = strlen(name);
	if (len == 0) {
		WARN("SearchForName: empty parameters\n");
		return 0;
	}

	offset = (double)r->howMany/2;
	done = -1;
	for (tmp = NULL, i = -1; (int)(offset + 0.5) != 0; ) {
		/* adjust the element we are going to check */
		if (done < 0) {
			/* we have to sum offset */
			i += (int)(offset + 0.5);
		} else if (done > 0) {
			/* we have to subtract the offset */
			i -= (int)(offset + 0.5);
		}

		/* let's check the limits */
		if (i < 0) {
			/* done here */
			offset = 0;
			i = 0;
		} else if (i >= r->howMany) {
			/* same here */
			offset = 0;
			i = r->howMany;
		}

		/* pick the name of the element */
		tmp = NwsAttributeValue_r(FindNwsAttribute(r->vals[i], "name"));
		if (tmp == NULL) {
			ABORT("SearchForName: out of memory\n");
		}
		if (matchExact) {
			done = strcmp(tmp, name);
		} else {
			done = strncmp(tmp, name, len);
		}
		FREE(tmp);
		if (done == 0) {
			/* found it */
			break;
		}

		/* halve the distance we are using */
		offset = offset/2;
	}

	/* now let's look for the higher index (if we found a
	 * registration) of the same name registration (ie series may
	 * have the same name) */
	if (done == 0) {
		while ((i + 1) < r->howMany) {
			tmp = NwsAttributeValue_r(FindNwsAttribute(r->vals[i+1], "name"));
			if (tmp == NULL) {
				ABORT("SearchForName: out of memory\n");
			}
			if (matchExact) {
				ln =  strcmp(tmp, name);
			} else {
				ln =  strncmp(tmp, name, len);
			}
			FREE(tmp);
			if (ln == 0) {
				/* another similar registration */
				i++;
			} else {
				/* we are done: no more same name 
				 * registrations */
				break;
			}
		}
	} else if (done < 0) {
		/* we are down one */
		i++;
	}
	*ind = i;

	return (done == 0);
}

/*
 * Searches for an object equivalent to #obj#. Returns 1 on success and
 * the position #ind# in registration #r#, 0 otherwise and #ind# contains
 * the index into which the object should be inserted to keep the #r#
 * ordered.
 */
int
SearchForObject(	registrations *r,
			Object obj,
			int *ind) {
	char *name, *newName;
	int i, ret;

	/* sanity check */
	if (ind == NULL) { 
		ERROR("SearchForObject: null parameters\n");
		return 0;
	}
	*ind = -1;		/* we default to error */
	if (r == NULL || obj == NULL) {
		ERROR("SearchForObject: null parameters\n");
		return 0;
	}

	/* let's get the name and search for it */
	newName = NwsAttributeValue_r(FindNwsAttribute(obj, "name"));
	if (newName == NULL) {
		ERROR("SearchForObject: object with no name\n");
		return 0;
	}
	if (!SearchForName(r, newName, 1, &i)) {
		FREE(newName);
		/* nope, there is no such a beast */
		*ind = i;
		return 0;
	}

	/* we need to look if they are equivalent */
	name = NwsAttributeValue_r(FindNwsAttribute(r->vals[i],"name"));
	if (name == NULL) {
		FREE(newName);
		ERROR("SearchForObject: out of memory\n");
		return 0;
	}
	*ind = i;	/* this is a good spot to insert :) */
	/* now we walk down looking for the same (similar)
	 * registration and reuse its slot if we find it */
	ret = 0;
	while (strcmp(name, newName) == 0) {
		if (AreObjectsEquivalent(r->vals[i], obj)) {
			/* found a similar registration */
			*ind = i;
			ret = 1;
			break;
		}
		/* nope: let's get lower if we can */
		if (i == 0) {
			/* we are at the beginning of the list */
			break;
		}
		i--;

		/* get the next name */
		FREE(name);
		name = NwsAttributeValue_r(FindNwsAttribute(r->vals[i],"name"));
		if (name == NULL) {
			ERROR("SearchForObject: out of memory\n");
			break;
		}
	}

	/* nope, we didn't find the beast */
	FREE(name);
	FREE(newName);

	return ret;
}