llhttpnode.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /**
  2. * @file llhttpnode.cpp
  3. * @brief Implementation of classes for generic HTTP/LSL/REST handling.
  4. *
  5. * $LicenseInfo:firstyear=2006&license=viewergpl$
  6. *
  7. * Copyright (c) 2006-2009, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "linden_common.h"
  33. #include "boost/tokenizer.hpp"
  34. #include "llhttpnode.h"
  35. #include "llhttpconstants.h"
  36. #include "llstl.h"
  37. /**
  38. * LLHTTPNode
  39. */
  40. class LLHTTPNode::Impl
  41. {
  42. public:
  43. typedef std::map<std::string, LLHTTPNode*> ChildMap;
  44. ChildMap mNamedChildren;
  45. LLHTTPNode* mWildcardChild;
  46. std::string mWildcardName;
  47. std::string mWildcardKey;
  48. LLHTTPNode* mParentNode;
  49. Impl() : mWildcardChild(NULL), mParentNode(NULL) {}
  50. LLHTTPNode* findNamedChild(const std::string& name) const;
  51. };
  52. LLHTTPNode* LLHTTPNode::Impl::findNamedChild(const std::string& name) const
  53. {
  54. LLHTTPNode* child = get_ptr_in_map(mNamedChildren, name);
  55. if (!child && (name[0] == '*' || name == mWildcardName))
  56. {
  57. child = mWildcardChild;
  58. }
  59. return child;
  60. }
  61. LLHTTPNode::LLHTTPNode()
  62. : impl(*new Impl)
  63. {
  64. }
  65. // virtual
  66. LLHTTPNode::~LLHTTPNode()
  67. {
  68. std::for_each(impl.mNamedChildren.begin(), impl.mNamedChildren.end(),
  69. DeletePairedPointer());
  70. impl.mNamedChildren.clear();
  71. delete impl.mWildcardChild;
  72. delete &impl;
  73. }
  74. namespace
  75. {
  76. class NotImplemented
  77. {
  78. };
  79. }
  80. // virtual
  81. LLSD LLHTTPNode::simpleGet() const
  82. {
  83. throw NotImplemented();
  84. }
  85. // virtual
  86. LLSD LLHTTPNode::simplePut(const LLSD& input) const
  87. {
  88. throw NotImplemented();
  89. }
  90. // virtual
  91. LLSD LLHTTPNode::simplePost(const LLSD& input) const
  92. {
  93. throw NotImplemented();
  94. }
  95. // virtual
  96. void LLHTTPNode::get(LLHTTPNode::ResponsePtr response,
  97. const LLSD& context) const
  98. {
  99. try
  100. {
  101. response->result(simpleGet());
  102. }
  103. catch (NotImplemented)
  104. {
  105. response->methodNotAllowed();
  106. }
  107. }
  108. // virtual
  109. void LLHTTPNode::put(LLHTTPNode::ResponsePtr response, const LLSD& context,
  110. const LLSD& input) const
  111. {
  112. try
  113. {
  114. response->result(simplePut(input));
  115. }
  116. catch (NotImplemented)
  117. {
  118. response->methodNotAllowed();
  119. }
  120. }
  121. // virtual
  122. void LLHTTPNode::post(LLHTTPNode::ResponsePtr response, const LLSD& context,
  123. const LLSD& input) const
  124. {
  125. try
  126. {
  127. response->result(simplePost(input));
  128. }
  129. catch (NotImplemented)
  130. {
  131. response->methodNotAllowed();
  132. }
  133. }
  134. // virtual
  135. void LLHTTPNode::del(LLHTTPNode::ResponsePtr response,
  136. const LLSD& context) const
  137. {
  138. try
  139. {
  140. response->result(simpleDel(context));
  141. }
  142. catch (NotImplemented)
  143. {
  144. response->methodNotAllowed();
  145. }
  146. }
  147. // virtual
  148. LLSD LLHTTPNode::simpleDel(const LLSD&) const
  149. {
  150. throw NotImplemented();
  151. }
  152. // virtual
  153. void LLHTTPNode::options(ResponsePtr response, const LLSD& context) const
  154. {
  155. LL_DEBUGS("LLHTTPNode") << "context: " << context << LL_ENDL;
  156. // default implementation constructs an url to the documentation.
  157. // *TODO: Check for 'Host' header instead of 'host' header?
  158. std::string host;
  159. host = context[CONTEXT_REQUEST][CONTEXT_HEADERS][HTTP_IN_HEADER_HOST].asString();
  160. if (host.empty())
  161. {
  162. response->status(HTTP_BAD_REQUEST, "Bad Request -- need Host header");
  163. return;
  164. }
  165. std::ostringstream ostr;
  166. ostr << "http://" << host << "/web/server/api";
  167. ostr << context[CONTEXT_REQUEST][CONTEXT_PATH].asString();
  168. static const std::string DOC_HEADER("X-Documentation-URL");
  169. response->addHeader(DOC_HEADER, ostr.str());
  170. response->status(HTTP_OK, "OK");
  171. }
  172. // virtual
  173. LLHTTPNode* LLHTTPNode::getChild(const std::string& name, LLSD& context) const
  174. {
  175. LLHTTPNode* namedChild = get_ptr_in_map(impl.mNamedChildren, name);
  176. if (namedChild)
  177. {
  178. return namedChild;
  179. }
  180. if (impl.mWildcardChild && impl.mWildcardChild->validate(name, context))
  181. {
  182. context[CONTEXT_REQUEST][CONTEXT_WILDCARD][impl.mWildcardKey] = name;
  183. return impl.mWildcardChild;
  184. }
  185. return NULL;
  186. }
  187. // virtual
  188. bool LLHTTPNode::handles(const LLSD& remainder, LLSD& context) const
  189. {
  190. return remainder.size() == 0;
  191. }
  192. // virtual
  193. bool LLHTTPNode::validate(const std::string& name, LLSD& context) const
  194. {
  195. return false;
  196. }
  197. const LLHTTPNode* LLHTTPNode::traverse(const std::string& path,
  198. LLSD& context) const
  199. {
  200. typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
  201. boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
  202. tokenizer tokens(path, sep);
  203. tokenizer::iterator iter = tokens.begin();
  204. tokenizer::iterator end = tokens.end();
  205. const LLHTTPNode* node = this;
  206. for ( ; iter != end; ++iter)
  207. {
  208. LLHTTPNode* child = node->getChild(*iter, context);
  209. if (!child)
  210. {
  211. LL_DEBUGS("HTTPNode") << "LLHTTPNode::traverse: Couldn't find '"
  212. << *iter << "'" << LL_ENDL;
  213. break;
  214. }
  215. LL_DEBUGS("HTTPNode") << "LLHTTPNode::traverse: Found '" << *iter
  216. << "'" << LL_ENDL;
  217. node = child;
  218. }
  219. LLSD& remainder = context[CONTEXT_REQUEST]["remainder"];
  220. for ( ; iter != end; ++iter)
  221. {
  222. remainder.append(*iter);
  223. }
  224. return node->handles(remainder, context) ? node : NULL;
  225. }
  226. void LLHTTPNode::addNode(const std::string& path, LLHTTPNode* nodeToAdd)
  227. {
  228. typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
  229. boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
  230. tokenizer tokens(path, sep);
  231. tokenizer::iterator iter = tokens.begin();
  232. tokenizer::iterator end = tokens.end();
  233. LLHTTPNode* node = this;
  234. for ( ; iter != end; ++iter)
  235. {
  236. LLHTTPNode* child = node->impl.findNamedChild(*iter);
  237. if (!child) break;
  238. node = child;
  239. }
  240. if (iter == end)
  241. {
  242. llwarns << "There is already a node handling " << path << llendl;
  243. return;
  244. }
  245. while (true)
  246. {
  247. std::string pathPart = *iter++;
  248. bool lastOne = iter == end;
  249. LLHTTPNode* nextNode = lastOne ? nodeToAdd : new LLHTTPNode();
  250. switch (pathPart[0])
  251. {
  252. case '<':
  253. {
  254. // *NOTE: This should really validate that it is of
  255. // the proper form: <wildcardkey> so that the substr()
  256. // generates the correct key name.
  257. node->impl.mWildcardChild = nextNode;
  258. node->impl.mWildcardName = pathPart;
  259. if (node->impl.mWildcardKey.empty())
  260. {
  261. node->impl.mWildcardKey = pathPart.substr(1,
  262. pathPart.size() - 2);
  263. }
  264. break;
  265. }
  266. case '*':
  267. {
  268. node->impl.mWildcardChild = nextNode;
  269. if (node->impl.mWildcardName.empty())
  270. {
  271. node->impl.mWildcardName = pathPart;
  272. }
  273. break;
  274. }
  275. default:
  276. {
  277. node->impl.mNamedChildren[pathPart] = nextNode;
  278. }
  279. }
  280. nextNode->impl.mParentNode = node;
  281. if (lastOne) break;
  282. node = nextNode;
  283. }
  284. }
  285. static void append_node_paths(LLSD& result, const std::string& name,
  286. const LLHTTPNode* node)
  287. {
  288. result.append(name);
  289. LLSD paths = node->allNodePaths();
  290. for (LLSD::array_const_iterator i = paths.beginArray(),
  291. end = paths.endArray();
  292. i != end; ++i)
  293. {
  294. result.append(name + "/" + i->asString());
  295. }
  296. }
  297. LLSD LLHTTPNode::allNodePaths() const
  298. {
  299. LLSD result;
  300. Impl::ChildMap::const_iterator i = impl.mNamedChildren.begin();
  301. Impl::ChildMap::const_iterator end = impl.mNamedChildren.end();
  302. for ( ; i != end; ++i)
  303. {
  304. append_node_paths(result, i->first, i->second);
  305. }
  306. if (impl.mWildcardChild)
  307. {
  308. append_node_paths(result, impl.mWildcardName, impl.mWildcardChild);
  309. }
  310. return result;
  311. }
  312. const LLHTTPNode* LLHTTPNode::rootNode() const
  313. {
  314. const LLHTTPNode* node = this;
  315. while (true)
  316. {
  317. const LLHTTPNode* next = node->impl.mParentNode;
  318. if (!next)
  319. {
  320. return node;
  321. }
  322. node = next;
  323. }
  324. }
  325. const LLHTTPNode* LLHTTPNode::findNode(const std::string& name) const
  326. {
  327. return impl.findNamedChild(name);
  328. }
  329. void LLHTTPNode::Response::statusUnknownError(S32 code)
  330. {
  331. status(code, "Unknown Error");
  332. }
  333. void LLHTTPNode::Response::notFound(const std::string& message)
  334. {
  335. status(HTTP_NOT_FOUND, message);
  336. }
  337. void LLHTTPNode::Response::notFound()
  338. {
  339. status(HTTP_NOT_FOUND, "Not Found");
  340. }
  341. void LLHTTPNode::Response::methodNotAllowed()
  342. {
  343. status(HTTP_METHOD_NOT_ALLOWED, "Method Not Allowed");
  344. }
  345. void LLHTTPNode::Response::addHeader(const std::string& name,
  346. const std::string& value)
  347. {
  348. mHeaders[name] = value;
  349. }
  350. void LLHTTPNode::describe(Description& desc) const
  351. {
  352. desc.shortInfo("unknown service (missing describe() method)");
  353. }
  354. const LLChainIOFactory* LLHTTPNode::getProtocolHandler() const
  355. {
  356. return NULL;
  357. }
  358. namespace
  359. {
  360. typedef std::map<std::string, LLHTTPRegistrar::NodeFactory*> FactoryMap;
  361. FactoryMap& factoryMap()
  362. {
  363. static FactoryMap theMap;
  364. return theMap;
  365. }
  366. }
  367. void LLHTTPRegistrar::registerFactory(const std::string& path,
  368. NodeFactory& factory)
  369. {
  370. factoryMap()[path] = &factory;
  371. }
  372. void LLHTTPRegistrar::buildAllServices(LLHTTPNode& root)
  373. {
  374. const FactoryMap& map = factoryMap();
  375. for (FactoryMap::const_iterator i = map.begin(), end = map.end();
  376. i != end; ++i)
  377. {
  378. LL_DEBUGS("AppInit") << "Adding node for path " << i->first << LL_ENDL;
  379. root.addNode(i->first, i->second->build());
  380. }
  381. }
  382. LLPointer<LLSimpleResponse> LLSimpleResponse::create()
  383. {
  384. return new LLSimpleResponse();
  385. }
  386. void LLSimpleResponse::result(const LLSD& result)
  387. {
  388. status(HTTP_OK, "OK");
  389. }
  390. void LLSimpleResponse::extendedResult(S32 code, const std::string& body,
  391. const LLSD& headers)
  392. {
  393. status(code, body);
  394. }
  395. void LLSimpleResponse::extendedResult(S32 code, const LLSD& r,
  396. const LLSD& headers)
  397. {
  398. status(code, "(LLSD)");
  399. }
  400. void LLSimpleResponse::status(S32 code, const std::string& message)
  401. {
  402. mCode = code;
  403. mMessage = message;
  404. }
  405. void LLSimpleResponse::print(std::ostream& out) const
  406. {
  407. out << mCode << " " << mMessage;
  408. }
  409. std::ostream& operator<<(std::ostream& out, const LLSimpleResponse& resp)
  410. {
  411. resp.print(out);
  412. return out;
  413. }