summaryrefslogtreecommitdiff
path: root/indra/llmessage/llhttpnode.cpp
blob: 440b91fcfadc8ed10bec1b1b248427873302ce05 (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
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
/** 
 * @file llhttpnode.cpp
 * @brief Implementation of classes for generic HTTP/LSL/REST handling.
 *
 * $LicenseInfo:firstyear=2006&license=viewergpl$
 * 
 * Copyright (c) 2006-2009, Linden Research, Inc.
 * 
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 * 
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 * 
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 * 
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "linden_common.h"
#include "llhttpnode.h"

#include <boost/tokenizer.hpp>

#include "llstl.h"
#include "lliohttpserver.h" // for string constants

static const std::string CONTEXT_WILDCARD("wildcard");

/**
 * LLHTTPNode
 */
 
class LLHTTPNode::Impl
{
public:
	typedef std::map<std::string, LLHTTPNode*> ChildMap;
	
	ChildMap mNamedChildren;
	LLHTTPNode* mWildcardChild;
	std::string mWildcardName;
	std::string mWildcardKey;
	LLHTTPNode* mParentNode;
	
	Impl() : mWildcardChild(NULL), mParentNode(NULL) { }
	
	LLHTTPNode* findNamedChild(const std::string& name) const;
};


LLHTTPNode* LLHTTPNode::Impl::findNamedChild(const std::string& name) const
{
	LLHTTPNode* child = get_ptr_in_map(mNamedChildren, name);

	if (!child  &&  ((name[0] == '*') || (name == mWildcardName)))
	{
		child = mWildcardChild;
	}
	
	return child;
}


LLHTTPNode::LLHTTPNode()
	: impl(* new Impl)
{
}

// virtual
LLHTTPNode::~LLHTTPNode()
{
	std::for_each(impl.mNamedChildren.begin(), impl.mNamedChildren.end(),
		DeletePairedPointer());

	delete impl.mWildcardChild;
	
	delete &impl;
}


namespace {
	class NotImplemented
	{
	};
}

// virtual
LLSD LLHTTPNode::simpleGet() const
{
	throw NotImplemented();
}

// virtual
LLSD LLHTTPNode::simplePut(const LLSD& input) const
{
	throw NotImplemented();
}

// virtual
LLSD LLHTTPNode::simplePost(const LLSD& input) const
{
	throw NotImplemented();
}


// virtual
void LLHTTPNode::get(LLHTTPNode::ResponsePtr response, const LLSD& context) const
{
	try
	{
		response->result(simpleGet());
	}
	catch (NotImplemented)
	{
		response->methodNotAllowed();
	}
}

// virtual
void LLHTTPNode::put(LLHTTPNode::ResponsePtr response, const LLSD& context, const LLSD& input) const
{
	try
	{
		response->result(simplePut(input));
	}
	catch (NotImplemented)
	{
		response->methodNotAllowed();
	}
}

// virtual
void LLHTTPNode::post(LLHTTPNode::ResponsePtr response, const LLSD& context, const LLSD& input) const
{
	try
	{
		response->result(simplePost(input));
	}
	catch (NotImplemented)
	{
		response->methodNotAllowed();
	}
}

// virtual
void LLHTTPNode::del(LLHTTPNode::ResponsePtr response, const LLSD& context) const
{
    try
    {
	response->result(simpleDel(context));
    }
    catch (NotImplemented)
    {
	response->methodNotAllowed();
    }

}

// virtual
LLSD LLHTTPNode::simpleDel(const LLSD&) const
{
	throw NotImplemented();
}

// virtual
void  LLHTTPNode::options(ResponsePtr response, const LLSD& context) const
{
	//llinfos << "options context: " << context << llendl;

	// default implementation constructs an url to the documentation.
	std::string host(
		context[CONTEXT_REQUEST][CONTEXT_HEADERS]["host"].asString());
	if(host.empty())
	{
		response->status(400, "Bad Request -- need Host header");
		return;
	}
	std::ostringstream ostr;
	ostr << "http://" << host << "/web/server/api";
	ostr << context[CONTEXT_REQUEST]["path"].asString();
	static const std::string DOC_HEADER("X-Documentation-URL");
	response->addHeader(DOC_HEADER, ostr.str());
	response->status(200, "OK");
}


// virtual
LLHTTPNode* LLHTTPNode::getChild(const std::string& name, LLSD& context) const
{
	LLHTTPNode* namedChild = get_ptr_in_map(impl.mNamedChildren, name);
	if (namedChild)
	{
		return namedChild;
	}
	
	if (impl.mWildcardChild
	&&  impl.mWildcardChild->validate(name, context))
	{
		context[CONTEXT_REQUEST][CONTEXT_WILDCARD][impl.mWildcardKey] = name;
		return impl.mWildcardChild;
	}
	
	return NULL;
}


// virtual
bool LLHTTPNode::handles(const LLSD& remainder, LLSD& context) const
{
	return remainder.size() == 0;
}

// virtual
bool LLHTTPNode::validate(const std::string& name, LLSD& context) const
{
	return false;
}

const LLHTTPNode* LLHTTPNode::traverse(
	const std::string& path, LLSD& context) const
{
	typedef boost::tokenizer< boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
	tokenizer tokens(path, sep);
	tokenizer::iterator iter = tokens.begin();
	tokenizer::iterator end = tokens.end();

	const LLHTTPNode* node = this;
	for(; iter != end; ++iter)
	{
		LLHTTPNode* child = node->getChild(*iter, context);
		if(!child) 
		{
			lldebugs << "LLHTTPNode::traverse: Couldn't find '" << *iter << "'" << llendl;
			break; 
		}
		lldebugs << "LLHTTPNode::traverse: Found '" << *iter << "'" << llendl;

		node = child;
	}

	LLSD& remainder = context[CONTEXT_REQUEST]["remainder"];
	for(; iter != end; ++iter)
	{
		remainder.append(*iter);
	}

	return node->handles(remainder, context) ? node : NULL;
}



void LLHTTPNode::addNode(const std::string& path, LLHTTPNode* nodeToAdd)
{
	typedef boost::tokenizer< boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
	tokenizer tokens(path, sep);
	tokenizer::iterator iter = tokens.begin();
	tokenizer::iterator end = tokens.end();

	LLHTTPNode* node = this;
	for(; iter != end; ++iter)
	{
		LLHTTPNode* child = node->impl.findNamedChild(*iter);
		if (!child) { break; }
		node = child;
	}
	
	if (iter == end)
	{
		llwarns << "LLHTTPNode::addNode: already a node that handles "
			<< path << llendl;
		return;
	}
	
	while (true)
	{
		std::string pathPart = *iter;
		
		++iter;
		bool lastOne = iter == end;
		
		LLHTTPNode* nextNode = lastOne ? nodeToAdd : new LLHTTPNode();
		
		switch (pathPart[0])
		{
			case '<':
				// *NOTE: This should really validate that it is of
				// the proper form: <wildcardkey> so that the substr()
				// generates the correct key name.
				node->impl.mWildcardChild = nextNode;
				node->impl.mWildcardName = pathPart;
				if(node->impl.mWildcardKey.empty())
				{
					node->impl.mWildcardKey = pathPart.substr(
						1,
						pathPart.size() - 2);
				}
				break;
			case '*':
				node->impl.mWildcardChild = nextNode;
				if(node->impl.mWildcardName.empty())
				{
					node->impl.mWildcardName = pathPart;
				}
				break;
			
			default:
				node->impl.mNamedChildren[pathPart] = nextNode;
		}
		nextNode->impl.mParentNode = node;

		if (lastOne) break;
		node = nextNode;
	}
}

static void append_node_paths(LLSD& result,
	const std::string& name, const LLHTTPNode* node)
{
	result.append(name);
	
	LLSD paths = node->allNodePaths();
	LLSD::array_const_iterator i = paths.beginArray();
	LLSD::array_const_iterator end = paths.endArray();
	
	for (; i != end; ++i)
	{
		result.append(name + "/" + (*i).asString());
	}
}

LLSD LLHTTPNode::allNodePaths() const
{
	LLSD result;
	
	Impl::ChildMap::const_iterator i = impl.mNamedChildren.begin();
	Impl::ChildMap::const_iterator end = impl.mNamedChildren.end();
	for (; i != end; ++i)
	{
		append_node_paths(result, i->first, i->second);
	}
	
	if (impl.mWildcardChild)
	{
		append_node_paths(result, impl.mWildcardName, impl.mWildcardChild);
	}
	
	return result;
}


const LLHTTPNode* LLHTTPNode::rootNode() const
{
	const LLHTTPNode* node = this;
	
	while (true)
	{
		const LLHTTPNode* next = node->impl.mParentNode;
		if (!next)
		{
			return node;
		}
		node = next;
	}
}


const LLHTTPNode* LLHTTPNode::findNode(const std::string& name) const
{
	return impl.findNamedChild(name);
}

LLHTTPNode::Response::~Response()
{
}

void LLHTTPNode::Response::statusUnknownError(S32 code)
{
	status(code, "Unknown Error");
}

void LLHTTPNode::Response::notFound(const std::string& message)
{
	status(404, message);
}

void LLHTTPNode::Response::notFound()
{
	status(404, "Not Found");
}

void LLHTTPNode::Response::methodNotAllowed()
{
	status(405, "Method Not Allowed");
}

void LLHTTPNode::Response::addHeader(
	const std::string& name,
	const std::string& value)
{
	mHeaders[name] = value;
}

void LLHTTPNode::describe(Description& desc) const
{
	desc.shortInfo("unknown service (missing describe() method)");
}


const LLChainIOFactory* LLHTTPNode::getProtocolHandler() const
{
	return NULL;
}



namespace
{
    typedef std::map<std::string, LLHTTPRegistrar::NodeFactory*>  FactoryMap;
    
    FactoryMap& factoryMap()
    {
        static FactoryMap theMap;
        return theMap;
    }
}

LLHTTPRegistrar::NodeFactory::~NodeFactory() { }

void LLHTTPRegistrar::registerFactory(
    const std::string& path, NodeFactory& factory)
{
	factoryMap()[path] = &factory;
}

void LLHTTPRegistrar::buildAllServices(LLHTTPNode& root)
{
    const FactoryMap& map = factoryMap();
    
    FactoryMap::const_iterator i = map.begin();
    FactoryMap::const_iterator end = map.end();
    for (; i != end; ++i)
    {
		LL_DEBUGS("AppInit") << "LLHTTPRegistrar::buildAllServices adding node for path "
			<< i->first << LL_ENDL;
		
        root.addNode(i->first, i->second->build());
    }
}

LLPointer<LLSimpleResponse> LLSimpleResponse::create()
{
	return new LLSimpleResponse();
}

LLSimpleResponse::~LLSimpleResponse()
{
}

void LLSimpleResponse::result(const LLSD& result)
{
	status(200, "OK");
}

void LLSimpleResponse::extendedResult(S32 code, const std::string& body, const LLSD& headers)
{
	status(code,body);
}

void LLSimpleResponse::status(S32 code, const std::string& message)
{
	mCode = code;
	mMessage = message;
}

void LLSimpleResponse::print(std::ostream& out) const
{
	out << mCode << " " << mMessage;
}


std::ostream& operator<<(std::ostream& out, const LLSimpleResponse& resp)
{
	resp.print(out);
	return out;
}