summaryrefslogtreecommitdiff
path: root/indra/newview/llsrv.cpp
blob: 7669eb994a9741e0a032c952cdbb5444fcdf4db8 (plain)
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
/** 
 * @file llsrv.cpp
 * @brief Wrapper for DNS SRV record lookups
 *
 * Copyright (c) 2007-$CurrentYear$, Linden Research, Inc.
 * $License$
 */

#include "llviewerprecompiledheaders.h"

#include "llsrv.h"

using namespace std;

#if LL_WINDOWS

#undef UNICODE
#include <winsock2.h>
#include <windns.h>

vector<LLSRVRecord> LLSRV::query(const string& name)
{
	vector<LLSRVRecord> recs;
	DNS_RECORD *rec;
	DNS_STATUS status;

	status = DnsQuery(name.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &rec, NULL);
	if (!status)
	{
		for (DNS_RECORD *cur = rec; cur != NULL; cur = cur->pNext)
		{
			if (cur->wType != DNS_TYPE_SRV)
			{
				continue;
			}
			recs.push_back(LLSRVRecord(cur->Data.Srv.wPriority,
									   cur->Data.Srv.wWeight,
									   cur->Data.Srv.pNameTarget,
									   cur->Data.Srv.wPort));
		}
		DnsRecordListFree(rec, DnsFreeRecordListDeep);
	}

	return recs;
}

#else // !LL_WINDOWS

#include <netinet/in.h>
#include <arpa/nameser.h>
#include <arpa/nameser_compat.h>
#include <resolv.h>

#include <netdb.h>

#ifdef HOMEGROWN_RESPONSE_PARSER

// We ought to be using libresolv's ns_initparse and ns_parserr to
// parse the result of our query.  However, libresolv isn't packaged
// correctly on Linux (as of BIND 9), so neither of these functions is
// available without statically linking against libresolv.  Ugh!  This
// fallback function is available if we need to parse the response
// ourselves without relying too much on libresolv.  It is NOT THE
// DEFAULT.

vector<LLSRVRecord> LLSRV::parseResponse(const unsigned char *response,
										 int resp_len)
{
	vector<LLSRVRecord> recs;

	const unsigned char *pos = response + sizeof(HEADER);
	const unsigned char *end = response + resp_len;
	const HEADER *hdr = (const HEADER *) response;
	char name[1024];

	// Skip over the query embedded in the response.

	for (int q = ntohs(hdr->qdcount); q > 0; --q)
	{
		int len = dn_expand(response, end, pos, name, sizeof(name));

		if (len == -1)
		{
			llinfos << "Could not expand queried name in RR response"
					<< llendl;
			goto bail;
		}
		
		pos += len + NS_QFIXEDSZ;
	}
	
	for (int a = ntohs(hdr->ancount); a > 0; --a)
	{
		static const ns_rr *rr;

		int len = dn_expand(response, end, pos, name, sizeof(name) - 1);
		if (len == -1)
		{
			llinfos << "Could not expand response name in RR response"
					<< llendl;
			goto bail;
		}

		// Skip over the resource name and headers we don't care about.

		pos += len + sizeof(rr->type) + sizeof(rr->rr_class) +
			sizeof(rr->ttl) + sizeof(rr->rdlength);
		
		U16 prio;
		U16 weight;
		U16 port;

		NS_GET16(prio, pos);
		NS_GET16(weight, pos);
		NS_GET16(port, pos);
		
		len = dn_expand(response, end, pos, name, sizeof(name) - 1);

		if (len == -1)
		{
			llinfos << "Could not expand name in RR response" << llendl;
			goto bail;
		}

		recs.push_back(LLSRVRecord(prio, weight, name, port));
	}

	// There are likely to be more records in the response, but we
	// don't care about those, at least for now.
bail:
	return reorder(recs);
}

#else // HOMEGROWN_RESPONSE_PARSER

// This version of the response parser is the one to use if libresolv
// is available and behaving itself.

vector<LLSRVRecord> LLSRV::parseResponse(const unsigned char *response,
										 int resp_len)
{
	vector<LLSRVRecord> recs;
	ns_msg hdr;

	if (ns_initparse(response, resp_len, &hdr))
	{
		llinfos << "Could not parse response" << llendl;
		goto bail;
	}
	
	for (int i = 0; i < ns_msg_count(hdr, ns_s_an); i++)
	{
		ns_rr rr;
		
		if (ns_parserr(&hdr, ns_s_an, i, &rr))
		{
			llinfos << "Could not parse RR" << llendl;
			goto bail;
		}

		if (ns_rr_type(rr) != ns_t_srv)
		{
			continue;
		}

		const unsigned char *pos = ns_rr_rdata(rr);
		U16 prio, weight, port;
		char name[1024];
		int ret;
		
		NS_GET16(prio, pos);
		NS_GET16(weight, pos);
		NS_GET16(port, pos);
		
		ret = dn_expand(ns_msg_base(hdr), ns_msg_end(hdr), pos,
						name, sizeof(name));

		if (ret == -1)
		{
			llinfos << "Could not decompress name" << llendl;
			goto bail;
		}

		recs.push_back(LLSRVRecord(prio, weight, name, port));
	}
	
bail:
	return reorder(recs);
}

#endif // HOMEGROWN_RESPONSE_PARSER

vector<LLSRVRecord> LLSRV::query(const string& queryName)
{
	unsigned char response[16384];
	vector<LLSRVRecord> recs;
	int len;
	
	len = res_query(queryName.c_str(), ns_c_in, ns_t_srv, response,
					sizeof(response));

	if (len == -1)
	{
		llinfos << "Query failed for " << queryName << llendl;
		goto bail;
	}
	else if (len > (int) sizeof(response))
	{
		llinfos << "Response too big for " << queryName
				<< " (capacity " << sizeof(response)
				<< ", response " << len << ")" << llendl;
		goto bail;
	}

	recs = parseResponse(response, len);
bail:
	return reorder(recs);
}

#endif // LL_WINDOWS

// Implement the algorithm specified in RFC 2782 for dealing with RRs
// of differing priorities and weights.
vector<LLSRVRecord> LLSRV::reorder(vector<LLSRVRecord>& recs)
{
	typedef list<const LLSRVRecord *> reclist_t;
	typedef map<U16, reclist_t> bucket_t;
	vector<LLSRVRecord> newRecs;
	bucket_t buckets;

	// Don't rely on the DNS server to shuffle responses.
	
	random_shuffle(recs.begin(), recs.end());

	for (vector<LLSRVRecord>::const_iterator iter = recs.begin();
		 iter != recs.end(); ++iter)
	{
		buckets[iter->priority()].push_back(&*iter);
	}
	
	// Priorities take precedence over weights.

	for (bucket_t::iterator iter = buckets.begin();
		 iter != buckets.end(); ++iter)
	{
		reclist_t& myPrio = iter->second;
		reclist_t r;

		// RRs with weight zero go to the front of the intermediate
		// list, so they'll have little chance of being chosen.
		// Larger weights have a higher likelihood of selection.

		for (reclist_t::iterator i = myPrio.begin(); i != myPrio.end(); )
		{
			if ((*i)->weight() == 0)
			{
				r.push_back(*i);
				i = myPrio.erase(i);
			} else {
				++i;
			}
		}

		r.insert(r.end(), myPrio.begin(), myPrio.end());
		
		while (!r.empty())
		{
			U32 total = 0;

			for (reclist_t::const_iterator i = r.begin(); i != r.end(); ++i)
			{
				total += (*i)->weight();
			}

			U32 target = total > 1 ? (rand() % total) : 0;
			U32 partial = 0;
			
			for (reclist_t::iterator i = r.begin(); i != r.end(); )
			{
				partial += (*i)->weight();
				if (partial >= target)
				{
					newRecs.push_back(**i);
					i = r.erase(i);
				} else {
					++i;
				}
			}
		}
	}
	
	// Order RRs by lowest numeric priority.  The stable sort
	// preserves the weight choices we made above.

	stable_sort(newRecs.begin(), newRecs.end(),
				LLSRVRecord::ComparePriorityLowest());

	return newRecs;
}

vector<string> LLSRV::rewriteURI(const string& uriStr)
{
	LLURI uri(uriStr);
	const string& scheme = uri.scheme();
	llinfos << "Rewriting " << uriStr << llendl;
	string serviceName("_" + scheme + "._tcp." + uri.hostName());
	llinfos << "Querying for " << serviceName << llendl;
	vector<LLSRVRecord> srvs(LLSRV::query(serviceName));
	vector<string> rewritten;

	if (srvs.empty())
	{
		llinfos << "No query results; using " << uriStr << llendl;
		rewritten.push_back(uriStr);
	}
	else
	{
		vector<LLSRVRecord>::const_iterator iter;
		size_t maxSrvs = 3;
		size_t i;

		llinfos << "Got " << srvs.size() << " results" << llendl;
		for (iter = srvs.begin(); iter != srvs.end(); ++iter)
		{
			lldebugs << "host " << iter->target() << ':' << iter->port()
					 << " prio " << iter->priority()
					 << " weight " << iter->weight()
					 << llendl;
		}

		if (srvs.size() > maxSrvs)
		{
			llinfos << "Clamping to " << maxSrvs << llendl;
		}

		for (iter = srvs.begin(), i = 0;
			 iter != srvs.end() && i < maxSrvs; ++iter, ++i)
		{
			LLURI newUri(scheme,
						 uri.userName(),
						 uri.password(),
						 iter->target(),
						 uri.defaultPort() ? iter->port() : uri.hostPort(),
						 uri.escapedPath(),
						 uri.escapedQuery());
			string newUriStr(newUri.asString());

			llinfos << "Rewrite[" << i << "] " << newUriStr << llendl;

			rewritten.push_back(newUriStr);
		}
	}

	return rewritten;
}