ObjXMPP  Diff

Differences From Artifact [4fe9779194]:

To Artifact [1b3191e9e7]:


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
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

+




















+
+
+






-




+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+









-
-
-
-
+
+
+
+
-
-
-
-
-







-
-
-
-
-





-
+

+
+
-
+
+
+
+







-
-
-
-
-
-
-


-
+












+
+
-
-
+
+
+
+
+
+






-
+

+




-
-
-
-
-
-
-
-


+
+
-
-
+
+
+
+
+
+
+
+

+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
-
-
-
-
-
+
+
+
+

-
+
-
-
-
+
+
+
+

-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
-

+
-
+




-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

/*
 * Copyright (c) 2011, Jonathan Schleifer <js@webkeks.org>
 * Copyright (c) 2011, Florian Zeitz <florob@babelmonkeys.de>
 *
 * https://webkeks.org/hg/objxmpp/
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice is present in all copies.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <assert.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <resolv.h>
#include <sys/types.h>
#include <openssl/rand.h>
#include <assert.h>

#import "XMPPSRVEnumerator.h"

@implementation XMPPSRVEntry
+ entryWithPriority: (uint16_t)priority
	     weight: (uint16_t)weight
	       port: (uint16_t)port
	     target: (OFString*)target
{
	return [[[self alloc] initWithPriority: priority
					weight: weight
					  port: port
					target: target] autorelease];
}

+ entryWithResourceRecord: (ns_rr)resourceRecord
		   handle: (ns_msg)handle
{
	return [[[self alloc] initWithResourceRecord: resourceRecord
					      handle: handle] autorelease];
}

- init
{
	Class c = isa;
	[self release];
	@throw [OFNotImplementedException newWithClass: c
					      selector: _cmd];
}

- initWithPriority: (uint16_t)priority_
	    weight: (uint16_t)weight_
	      port: (uint16_t)port_
	    target: (OFString*)target_
{
	self = [super init];

	@try {
		priority = priority_;
		weight = weight_;
		port = port_;
		target = [target_ copy];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- initWithResourceRecord: (ns_rr)resourceRecord
		  handle: (ns_msg)handle
{
	self = [super init];

	@try {
		const uint16_t *rdata;
		char buffer[NS_MAXDNAME];

		rdata = (const uint16_t*)(void*)ns_rr_rdata(resourceRecord);
		priority = ntohs(rdata[0]);
		weight = ntohs(rdata[1]);
		port = ntohs(rdata[2]);

		if (dn_expand(ns_msg_base(handle), ns_msg_end(handle),
		    (uint8_t*)&rdata[3], buffer, NS_MAXDNAME) < 1)
			@throw [OFInitializationFailedException
			    newWithClass: isa];

		target = [[OFString alloc] initWithCString: buffer];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[target release];

	[super dealloc];
}

- (OFString*)description
{
	return [OFString stringWithFormat: @"priority: %" PRIu16
				@" weight: %" PRIu16
				@" target: %@:%" PRIu16, priority, weight,
				target, port];
	return [OFString stringWithFormat: @"<%@ priority: %" PRIu16
					   @", weight: %" PRIu16
					   @", target: %@:%" PRIu16 @">",
					   isa, priority, weight, target, port];
}

- (void)setPriority: (uint16_t)priority_
{
	priority = priority_;
}

- (uint16_t)priority
{
	return priority;
}

- (void)setWeight: (uint16_t)weight_
{
	weight = weight_;
}

- (uint16_t)weight
{
	return weight;
}

- (void)setPort: (uint16_t)port_
- (void)setAccumulatedWeight: (uint16_t)accumulatedWeight_
{
	accumulatedWeight = accumulatedWeight_;
}
	port = port_;

- (uint16_t)accumulatedWeight
{
	return accumulatedWeight;
}

- (uint16_t)port
{
	return port;
}

- (void)setTarget: (OFString*)target_
{
	OFString *old = target;
	target = [target_ copy];
	[old release];
}

- (OFString*)target
{
	return [[target copy] autorelease];
	OF_GETTER(target, YES)
}
@end

@implementation XMPPSRVEnumerator
+ enumeratorWithDomain: (OFString*)domain_
{
	return [[[self alloc] initWithDomain: domain_] autorelease];
}

- initWithDomain: (OFString*)domain_
{
	self = [super init];

	@try {
	priorityList = [[OFList alloc] init];
	[self setDomain: domain_];
		list = [[OFList alloc] init];
		domain = [domain_ copy];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	[priorityList release];
	[list release];
	[domain release];
	[subListCopy release];

	[super dealloc];
}

- (void)setDomain: (OFString*)domain_
{
	OFString *old = domain;
	domain = [domain_ copy];
	[old release];
	[self reset];
}

- (OFString*)domain;
{
	OF_GETTER(domain, YES)
}
	return [[domain copy] autorelease];
}

- (void)lookUpEntries
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	unsigned char *answer = NULL;
	OFString *request;

	request = [OFString stringWithFormat: @"_xmpp-client._tcp.%@", domain];

	@try {
		int answerLen, resourceRecordCount, i;
		ns_rr resourceRecord;
		ns_msg handle;
- (void)XMPP_parseSRVRRWithHandle: (const ns_msg)handle
			       RR: (const ns_rr)rr
			   result: (XMPPSRVEntry*)result
{
	const uint16_t *rdata = (uint16_t*) ns_rr_rdata(rr);
	char target[NS_MAXDNAME];
	[result setPriority: ntohs(rdata[0])];
	[result setWeight: ntohs(rdata[1])];
	[result setPort: ntohs(rdata[2])];
	dn_expand(ns_msg_base(handle), ns_msg_end(handle),
			(uint8_t*) &rdata[3], target, NS_MAXDNAME);
	[result setTarget: [OFString stringWithCString: target]];

		if (res_ninit(&resState))
			@throw [OFAddressTranslationFailedException
			    newWithClass: isa
				  socket: nil
				    host: domain];

		answer = [self allocMemoryWithSize: of_pagesize];
		answerLen = res_nsearch(&resState, [request cString], ns_c_in,
		    ns_t_srv, answer, (int)of_pagesize);

		if (answerLen < 1 || answerLen > of_pagesize)
			@throw [OFAddressTranslationFailedException
			    newWithClass: isa
				  socket: nil
				    host: domain];

		if (ns_initparse(answer, answerLen, &handle))
			@throw [OFAddressTranslationFailedException
			    newWithClass: isa
				  socket: nil
				    host: domain];

		resourceRecordCount = ns_msg_count(handle, ns_s_an);
		for (i = 0; i < resourceRecordCount; i++) {
			if (ns_parserr(&handle, ns_s_an, i, &resourceRecord))
				continue;

			if (ns_rr_type(resourceRecord) != ns_t_srv ||
			    ns_rr_class(resourceRecord) != ns_c_in)
				continue;

			[self XMPP_addEntry: [XMPPSRVEntry
			    entryWithResourceRecord: resourceRecord
					     handle: handle]];
		}
	} @finally {
		[self freeMemory: answer];
		res_ndestroy(&resState);
	}

	[pool release];
}

- (void)XMPP_addEntry: (XMPPSRVEntry*)entry
{
	OFAutoreleasePool *pool;
	OFList *subList;
	of_list_object_t *iter;

	/* Look if there already is a list with the priority */
	for (iter = [list firstListObject]; iter != NULL; iter = iter->next) {
		if ([[iter->object firstObject] priority] == [entry priority]) {
			/*
			 * RFC 2782 says those with weight 0 should be at the
			 * beginning of the list.
			 */
			if ([entry weight] > 0)
				[iter->object appendObject: entry];
			else
				[iter->object prependObject: entry];

			return;
		}

		/* We can't have one if the priority is already bigger */
		if ([[iter->object firstObject] priority] > [entry priority])
			break;
	}

	/* No list with the priority -> create one at the correct place */
	for (iter = [list firstListObject]; iter != NULL; iter = iter->next) {
		if ([[iter->object firstObject] priority] > [entry priority]) {
			OFAutoreleasePool *pool;

			pool = [[OFAutoreleasePool alloc] init];

			subList = [OFList list];

			/*
			 * RFC 2782 says those with weight 0 should be at the
			 * beginning of the list.
			 */
			if ([entry weight] > 0)
				[subList appendObject: entry];
			else
				[subList prependObject: entry];

			[list insertObject: subList
			  beforeListObject: iter];

			[pool release];

			return;
		}
	}

	/* There is no list with a bigger priority -> append */
	pool = [[OFAutoreleasePool alloc] init];

	subList = [OFList list];

	/*
	 * RFC 2782 says those with weight 0 should be at the beginning of the
	 * list.
	 */
	if ([entry weight] > 0)
		[subList appendObject: entry];
	else
		[subList prependObject: entry];

	[list appendObject: subList];

	[pool release];
}

- (id)nextObject
{
	if ([priorityList firstListObject]) {
		uint16_t weight = 0;
		of_list_object_t *iter;
		XMPPSRVEntry *ret;
		OFList *weightList = [priorityList firstObject];
		uint16_t maximumWeight = [[weightList lastObject] weight];
	XMPPSRVEntry *ret;
	of_list_object_t *iter;
	uint32_t totalWeight = 0;
	BOOL found = NO;

		if (maximumWeight) {
	if (done)
			RAND_pseudo_bytes((unsigned char *)&weight, 2);
			weight %= maximumWeight;
		}
		return nil;

	if (listIter == NULL)
		listIter = [list lastListObject];

		iter = [weightList firstListObject];
		while (iter) {
			if (weight <= [iter->object weight]) {
				ret = [iter->object retain];
	if (listIter == NULL)
		return nil;

	if (subListCopy == nil)
		subListCopy = [listIter->object copy];
				[weightList removeListObject: iter];
				if (![weightList firstListObject])
					[priorityList removeListObject:
						[priorityList firstListObject]];
				return [ret autorelease];
			}
			iter = iter->next;
		}
		assert(0);
	}

	/* FIXME: Handle empty subListCopy */
	for (iter = [subListCopy firstListObject]; iter != NULL;
	     iter = iter->next) {
		totalWeight += [iter->object weight];
		[iter->object setAccumulatedWeight: totalWeight];
	}

	while (!found) {
		uint32_t randomWeight;

		RAND_pseudo_bytes((uint8_t*)&randomWeight, sizeof(uint32_t));
		randomWeight %= (totalWeight + 1);

		for (iter = [subListCopy firstListObject]; iter != NULL;
		     iter = iter->next) {
			if ([iter->object accumulatedWeight] >= randomWeight) {
				ret = [[iter->object retain] autorelease];
	return nil;
}

- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t*)state

				[subListCopy removeListObject: iter];

				found = YES;
				break;
			}
		}
	}

			   objects: (id*)objects
			     count: (int)count
{
	int len = 0;
	XMPPSRVEntry *entry = [self nextObject];
	state->itemsPtr = objects;
	if ([subListCopy count] == 0) {
		[subListCopy release];
		subListCopy = nil;

		listIter = listIter->previous;

		if (listIter == NULL)
	while ((len < count) && entry) {
		state->mutationsPtr = (unsigned long *)self;
		objects[len++] = entry;
			done = YES;
		entry = [self nextObject];
	}

	return len;
	return ret;
}

- (void)reset
{
	int i, rrCount;
	unsigned char *answer;
	OFString *request;
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];

	listIter = NULL;
	request = [OFString stringWithFormat: @"_xmpp-client._tcp.%@", domain];
	answer = [self allocMemoryWithSize: NS_MAXMSG];

	res_ninit(&_res);
	if (!(res_nsearch(&_res, [request cString], ns_c_in, ns_t_srv, answer,
				NS_MAXMSG) < 0)) {
		ns_rr rr;
		ns_msg handle;

		ns_initparse(answer, NS_MAXMSG, &handle);
		rrCount = ns_msg_count(handle, ns_s_an);
		for (i = 0; i < rrCount ; i++) {
			XMPPSRVEntry *result = [[XMPPSRVEntry alloc] init];
			ns_parserr(&handle, ns_s_an, i, &rr);
			if ((ns_rr_type(rr) != ns_t_srv)
					|| ns_rr_class(rr) != ns_c_in)
				@throw [OFInvalidServerReplyException
					newWithClass: isa];

			[self XMPP_parseSRVRRWithHandle: handle
						     RR: rr
						 result: result];

			[self XMPP_addSRVEntry: result
			  toSortedPriorityList: priorityList];
		}
	}
	[self freeMemory: answer];
	[pool release];


	[subListCopy release];
	subListCopy = nil;
	done = NO;
}

- (void)XMPP_addSRVEntry: (XMPPSRVEntry*)item
    toSortedPriorityList: (OFList*)list
{
	of_list_object_t *priorityIter =
		[list firstListObject];
	while (1) {
		if (priorityIter == NULL ||
				[[priorityIter->object firstObject]
					priority] > [item priority]) {
			OFList *newList = [OFList list];
			[newList appendObject: item];
			if (priorityIter)
				[list insertObject: newList
				  beforeListObject: priorityIter];
			else
				[list appendObject: newList];
			break;
		}
		if ([[priorityIter->object firstObject] priority]
				== [item priority]) {
			if ([item weight] == 0)
				[priorityIter->object prependObject: item];
			else {
				[item setWeight: [item weight] +
				    [[priorityIter->object lastObject] weight]];
				[priorityIter->object appendObject: item];
			}
			break;
		}
		priorityIter = priorityIter->next;
	}
}
@end