llcorehttputil.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. /**
  2. * @file llcorehttputil.cpp
  3. * @date 2014-08-25
  4. * @brief Implementation of adapter and utility classes expanding the llcorehttp interfaces.
  5. *
  6. * $LicenseInfo:firstyear=2014&license=viewerlgpl$
  7. * Second Life Viewer Source Code
  8. * Copyright (C) 2014, Linden Research, Inc.
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation;
  13. * version 2.1 of the License only.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. *
  24. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  25. * $/LicenseInfo$
  26. */
  27. #include "linden_common.h"
  28. #include <algorithm>
  29. #include <iterator>
  30. #include <sstream>
  31. #include "llcorehttputil.h"
  32. #include "llfilesystem.h"
  33. #include "llhttpconstants.h"
  34. #include "llsdjson.h"
  35. #include "llsdserialize.h"
  36. #include "llmessage.h" // For getting the port
  37. using namespace LLCore;
  38. namespace LLCoreHttpUtil
  39. {
  40. void logMessageSuccess(const std::string& log_auth, const std::string& url,
  41. const std::string& message)
  42. {
  43. llinfos << log_auth << ": Success '" << message << "' for: " << url
  44. << llendl;
  45. }
  46. void logMessageFail(const std::string& log_auth, const std::string& url,
  47. const std::string& message)
  48. {
  49. llwarns << log_auth << ": Failure '" << message << "' for: " << url
  50. << llendl;
  51. }
  52. ///////////////////////////////////////////////////////////////////////////////
  53. // HttpRequestPumper class
  54. ///////////////////////////////////////////////////////////////////////////////
  55. // The HttpRequestPumper is a utility class. When constructed it will poll the
  56. // supplied HttpRequest once per frame until it is destroyed.
  57. class HttpRequestPumper
  58. {
  59. public:
  60. HttpRequestPumper(const LLCore::HttpRequest::ptr_t& request);
  61. ~HttpRequestPumper();
  62. private:
  63. bool pollRequest();
  64. private:
  65. LLBoundListener mBoundListener;
  66. LLCore::HttpRequest::ptr_t mHttpRequest;
  67. };
  68. HttpRequestPumper::HttpRequestPumper(const LLCore::HttpRequest::ptr_t& request)
  69. : mHttpRequest(request)
  70. {
  71. LLEventPump& pump = gEventPumps.obtain("mainloop");
  72. mBoundListener = pump.listen(LLEventPump::ANONYMOUS,
  73. boost::bind(&HttpRequestPumper::pollRequest,
  74. this));
  75. }
  76. HttpRequestPumper::~HttpRequestPumper()
  77. {
  78. if (mBoundListener.connected())
  79. {
  80. mBoundListener.disconnect();
  81. }
  82. }
  83. bool HttpRequestPumper::pollRequest()
  84. {
  85. if (mHttpRequest && !mHttpRequest->isCancelled() &&
  86. mHttpRequest->getStatus() != gStatusCancelled)
  87. {
  88. mHttpRequest->update(0L);
  89. }
  90. // No point to keep pumping once the request is cancelled or destroyed...
  91. else if (mBoundListener.connected())
  92. {
  93. mBoundListener.disconnect();
  94. }
  95. return false;
  96. }
  97. ///////////////////////////////////////////////////////////////////////////////
  98. // *TODO: Currently converts only from XML content. A mode to convert using
  99. // fromBinary() might be useful as well. Mesh headers could use it.
  100. bool responseToLLSD(HttpResponse* response, bool log, LLSD& out_llsd)
  101. {
  102. // Convert response to LLSD
  103. BufferArray* body = response ? response->getBody() : NULL;
  104. if (!body || !body->size())
  105. {
  106. return false;
  107. }
  108. LLCore::BufferArrayStream bas(body);
  109. LLSD body_llsd;
  110. S32 parse_status(LLSDSerialize::fromXML(body_llsd, bas, log));
  111. if (LLSDParser::PARSE_FAILURE == parse_status)
  112. {
  113. return false;
  114. }
  115. out_llsd = body_llsd;
  116. return true;
  117. }
  118. HttpHandle requestPostWithLLSD(HttpRequest* request,
  119. HttpRequest::policy_t policy_id,
  120. const std::string& url, const LLSD& body,
  121. const HttpOptions::ptr_t& options,
  122. const HttpHeaders::ptr_t& headers,
  123. const HttpHandler::ptr_t& handler)
  124. {
  125. HttpHandle handle = LLCORE_HTTP_HANDLE_INVALID;
  126. if (!request) return handle;
  127. BufferArray* ba = new BufferArray();
  128. BufferArrayStream bas(ba);
  129. LLSDSerialize::toXML(body, bas);
  130. handle = request->requestPost(policy_id, url, ba, options, headers,
  131. handler);
  132. ba->release();
  133. return handle;
  134. }
  135. HttpHandle requestPutWithLLSD(HttpRequest* request,
  136. HttpRequest::policy_t policy_id,
  137. const std::string& url, const LLSD& body,
  138. const HttpOptions::ptr_t& options,
  139. const HttpHeaders::ptr_t& headers,
  140. const HttpHandler::ptr_t& handler)
  141. {
  142. HttpHandle handle = LLCORE_HTTP_HANDLE_INVALID;
  143. if (!request) return handle;
  144. BufferArray* ba = new BufferArray();
  145. BufferArrayStream bas(ba);
  146. LLSDSerialize::toXML(body, bas);
  147. handle = request->requestPut(policy_id, url, ba, options, headers,
  148. handler);
  149. ba->release();
  150. return handle;
  151. }
  152. HttpHandle requestPatchWithLLSD(HttpRequest* request,
  153. HttpRequest::policy_t policy_id,
  154. const std::string& url, const LLSD& body,
  155. const HttpOptions::ptr_t& options,
  156. const HttpHeaders::ptr_t& headers,
  157. const HttpHandler::ptr_t& handler)
  158. {
  159. HttpHandle handle = LLCORE_HTTP_HANDLE_INVALID;
  160. if (!request) return handle;
  161. BufferArray* ba = new BufferArray();
  162. BufferArrayStream bas(ba);
  163. LLSDSerialize::toXML(body, bas);
  164. handle = request->requestPatch(policy_id, url, ba, options, headers,
  165. handler);
  166. ba->release();
  167. return handle;
  168. }
  169. std::string responseToString(LLCore::HttpResponse* response)
  170. {
  171. static const std::string empty = "[Empty]";
  172. if (!response)
  173. {
  174. return empty;
  175. }
  176. BufferArray* body = response->getBody();
  177. if (!body || !body->size())
  178. {
  179. return empty;
  180. }
  181. // Attempt to parse as LLSD regardless of content-type
  182. LLSD body_llsd;
  183. if (responseToLLSD(response, false, body_llsd))
  184. {
  185. std::ostringstream tmp;
  186. LLSDSerialize::toPrettyNotation(body_llsd, tmp);
  187. size_t temp_len = tmp.tellp();
  188. if (temp_len)
  189. {
  190. return tmp.str().substr(0, llmin(temp_len, (size_t)1024));
  191. }
  192. }
  193. else
  194. {
  195. // *TODO: More elaborate forms based on Content-Type as needed.
  196. char content[1024];
  197. size_t len = body->read(0, content, sizeof(content));
  198. if (len)
  199. {
  200. return std::string(content, 0, len);
  201. }
  202. }
  203. // Default
  204. return empty;
  205. }
  206. ///////////////////////////////////////////////////////////////////////////////
  207. // HttpCoroHandler class
  208. ///////////////////////////////////////////////////////////////////////////////
  209. HttpCoroHandler::HttpCoroHandler(LLEventStream& reply)
  210. : mReplyPump(reply)
  211. {
  212. }
  213. void HttpCoroHandler::onCompleted(LLCore::HttpHandle handle,
  214. LLCore::HttpResponse* response)
  215. {
  216. if (!response)
  217. {
  218. llwarns << "NULL response pointer passed !" << llendl;
  219. return;
  220. }
  221. static const LLCore::HttpStatus bad_handle(LLCore::HttpStatus::LLCORE,
  222. LLCore::HE_HANDLE_NOT_FOUND);
  223. LLCore::HttpStatus status = response->getStatus();
  224. if (status == bad_handle)
  225. {
  226. // A response came in for a cancelled request and we have not processed
  227. // the cancel yet. Patience !
  228. return;
  229. }
  230. LLSD result;
  231. if (!status)
  232. {
  233. bool parse_success = false;
  234. result = LLSD::emptyMap();
  235. LLCore::HttpStatus::type_enum_t error = status.getType();
  236. LL_DEBUGS("CoreHttp") << "Error " << status.toTerseString()
  237. << " - Cannot access url: "
  238. << response->getRequestURL()
  239. << " - Reason: " << status.toString() << LL_ENDL;
  240. if (error >= 400 && error < 500)
  241. {
  242. LLSD body = parseBody(response, parse_success);
  243. if (!body.isUndefined())
  244. {
  245. if (!body.isMap())
  246. {
  247. result[HttpCoroutineAdapter::HTTP_RESULTS_CONTENT] = body;
  248. }
  249. else
  250. {
  251. result = body;
  252. }
  253. }
  254. }
  255. }
  256. else
  257. {
  258. result = handleSuccess(response, status);
  259. }
  260. buildStatusEntry(response, status, result);
  261. if (!status)
  262. {
  263. LLSD& status_llsd = result[HttpCoroutineAdapter::HTTP_RESULTS];
  264. bool parse_success = false;
  265. LLSD error_body = parseBody(response, parse_success);
  266. if (parse_success)
  267. {
  268. status_llsd["error_body"] = error_body;
  269. LL_DEBUGS("CoreHttp") << "Returned body:\n";
  270. std::stringstream str;
  271. LLSDSerialize::toPrettyXML(error_body, str);
  272. LL_CONT << str.str() << LL_ENDL;
  273. }
  274. else
  275. {
  276. LLCore::BufferArray* body = response->getBody();
  277. LLCore::BufferArrayStream bas(body);
  278. LLSD::String bodydata;
  279. bodydata.reserve(response->getBodySize());
  280. bas >> std::noskipws;
  281. bodydata.assign(std::istream_iterator<U8>(bas),
  282. std::istream_iterator<U8>());
  283. status_llsd["error_body"] = LLSD(bodydata);
  284. LL_DEBUGS("CoreHttp") << "Returned body:" << std::endl
  285. << status_llsd["error_body"].asString()
  286. << LL_ENDL;
  287. }
  288. }
  289. mReplyPump.post(result);
  290. }
  291. void HttpCoroHandler::buildStatusEntry(LLCore::HttpResponse* response,
  292. LLCore::HttpStatus status, LLSD& result)
  293. {
  294. if (!response)
  295. {
  296. llwarns << "NULL response pointer passed !" << llendl;
  297. return;
  298. }
  299. LLSD httpresults = LLSD::emptyMap();
  300. writeStatusCodes(status, response->getRequestURL(), httpresults);
  301. LLSD httpheaders = LLSD::emptyMap();
  302. LLCore::HttpHeaders::ptr_t hdrs = response->getHeaders();
  303. if (hdrs)
  304. {
  305. for (LLCore::HttpHeaders::iterator it = hdrs->begin(),
  306. end = hdrs->end();
  307. it != end; ++it)
  308. {
  309. if (!it->second.empty())
  310. {
  311. httpheaders[it->first] = it->second;
  312. }
  313. else
  314. {
  315. httpheaders[it->first] = LLSD::Boolean(true);
  316. }
  317. }
  318. }
  319. httpresults[HttpCoroutineAdapter::HTTP_RESULTS_HEADERS] = httpheaders;
  320. result[HttpCoroutineAdapter::HTTP_RESULTS] = httpresults;
  321. }
  322. void HttpCoroHandler::writeStatusCodes(LLCore::HttpStatus status,
  323. const std::string& url, LLSD& result)
  324. {
  325. result[HttpCoroutineAdapter::HTTP_RESULTS_SUCCESS] = LLSD::Boolean(status);
  326. result[HttpCoroutineAdapter::HTTP_RESULTS_TYPE] = LLSD::Integer(status.getType());
  327. result[HttpCoroutineAdapter::HTTP_RESULTS_STATUS] = LLSD::Integer(status.getStatus());
  328. result[HttpCoroutineAdapter::HTTP_RESULTS_MESSAGE] = LLSD::String(status.getMessage());
  329. result[HttpCoroutineAdapter::HTTP_RESULTS_URL] = LLSD::String(url);
  330. }
  331. ///////////////////////////////////////////////////////////////////////////////
  332. // HttpCoroLLSDHandler class
  333. ///////////////////////////////////////////////////////////////////////////////
  334. // HttpCoroLLSDHandler is a specialization of the LLCore::HttpHandler for
  335. // interacting with coroutines. When the request is completed the response will
  336. // be posted onto the supplied Event Pump.
  337. //
  338. // If the LLSD retrieved from through the HTTP connection is not in the form of
  339. // a LLSD::map it will be returned as in an llsd["content"] element.
  340. //
  341. // The LLSD posted back to the coroutine will have the following additions:
  342. // llsd["http_result"] -+- ["message"] An error message returned from the HTTP
  343. // status.
  344. // +- ["status"] The status code associated with the
  345. // HTTP call.
  346. // +- ["success"] Success of failure of the HTTP call and
  347. // LLSD parsing.
  348. // +- ["type"] The LLCore::HttpStatus type associted
  349. // with the HTTP call.
  350. // +- ["url"] The URL used to make the call.
  351. // +- ["headers"] A map of name name value pairs with the
  352. // HTTP headers.
  353. class HttpCoroLLSDHandler final : public HttpCoroHandler
  354. {
  355. public:
  356. HttpCoroLLSDHandler(LLEventStream& reply)
  357. : HttpCoroHandler(reply)
  358. {
  359. }
  360. protected:
  361. LLSD handleSuccess(LLCore::HttpResponse* response,
  362. LLCore::HttpStatus& status) override;
  363. LLSD parseBody(LLCore::HttpResponse* response, bool& success) override;
  364. };
  365. LLSD HttpCoroLLSDHandler::handleSuccess(LLCore::HttpResponse* response,
  366. LLCore::HttpStatus& status)
  367. {
  368. LLSD result;
  369. if (!response)
  370. {
  371. llwarns << "NULL response pointer passed !" << llendl;
  372. return result;
  373. }
  374. bool success = false;
  375. result = parseBody(response, success);
  376. if (!success)
  377. {
  378. // Only emit a warning if we failed to parse when 'content-type' ==
  379. // 'application/llsd+xml'
  380. LLCore::HttpHeaders::ptr_t headers(response->getHeaders());
  381. const std::string* content_type =
  382. headers ? headers->find(HTTP_IN_HEADER_CONTENT_TYPE) : NULL;
  383. if (content_type && *content_type == HTTP_CONTENT_LLSD_XML)
  384. {
  385. std::string thebody = LLCoreHttpUtil::responseToString(response);
  386. llwarns << "Failed to deserialize: " << response->getRequestURL()
  387. << " - Status: " << response->getStatus().toString()
  388. << " - Body: " << thebody << llendl;
  389. // Replace the status with a new one indicating the failure.
  390. status = LLCore::HttpStatus(499, "Failed to deserialize LLSD.");
  391. }
  392. // If we have gotten to this point and the result LLSD is still
  393. // undefined either there was an issue deserializing the body or the
  394. // response was blank. Create an empty map to hold the result either
  395. // way.
  396. result = LLSD::emptyMap();
  397. }
  398. else if (!result.isMap() && result.isDefined())
  399. {
  400. // The results are not themselves a map. Move them down so that this
  401. // method can return a map to the caller.
  402. // *TODO: Should it always do this ?
  403. // HB: probably not... It causes issues with callbacks expecting either
  404. // a map or an empty LLSD (e.g. path finding routines). This is why I
  405. // added a result.isDefined() condition...
  406. LLSD new_result = LLSD::emptyMap();
  407. new_result[HttpCoroutineAdapter::HTTP_RESULTS_CONTENT] = result;
  408. result = new_result;
  409. }
  410. return result;
  411. }
  412. LLSD HttpCoroLLSDHandler::parseBody(LLCore::HttpResponse* response,
  413. bool& success)
  414. {
  415. LLSD result;
  416. if (!response)
  417. {
  418. llwarns << "NULL response pointer passed !" << llendl;
  419. success = false;
  420. return result;
  421. }
  422. if (response->getBodySize() == 0 ||
  423. LLCoreHttpUtil::responseToLLSD(response, false, result))
  424. {
  425. success = true;
  426. return result;
  427. }
  428. success = false;
  429. return LLSD();
  430. }
  431. ///////////////////////////////////////////////////////////////////////////////
  432. // HttpCoroRawHandler class
  433. ///////////////////////////////////////////////////////////////////////////////
  434. // HttpCoroRawHandler is a specialization of the LLCore::HttpHandler for
  435. // interacting with coroutines.
  436. //
  437. // In addition to the normal "http_results" the returned LLSD will contain an
  438. // entry keyed with "raw" containing the unprocessed results of the HTTP call.
  439. class HttpCoroRawHandler final : public HttpCoroHandler
  440. {
  441. public:
  442. HttpCoroRawHandler(LLEventStream& reply)
  443. : HttpCoroHandler(reply)
  444. {
  445. }
  446. LLSD handleSuccess(LLCore::HttpResponse* response,
  447. LLCore::HttpStatus& status) override;
  448. LLSD parseBody(LLCore::HttpResponse* response, bool& success) override;
  449. };
  450. LLSD HttpCoroRawHandler::handleSuccess(LLCore::HttpResponse* response,
  451. LLCore::HttpStatus& status)
  452. {
  453. LLSD result = LLSD::emptyMap();
  454. BufferArray* body = response ? response->getBody() : NULL;
  455. if (!body || !body->size())
  456. {
  457. return result;
  458. }
  459. size_t size = body->size();
  460. LLCore::BufferArrayStream bas(body);
  461. LLSD::Binary data;
  462. data.reserve(size);
  463. bas >> std::noskipws;
  464. data.assign(std::istream_iterator<U8>(bas), std::istream_iterator<U8>());
  465. result[HttpCoroutineAdapter::HTTP_RESULTS_RAW] = data;
  466. return result;
  467. }
  468. LLSD HttpCoroRawHandler::parseBody(LLCore::HttpResponse* response,
  469. bool& success)
  470. {
  471. success = true;
  472. return LLSD();
  473. }
  474. ///////////////////////////////////////////////////////////////////////////////
  475. // HttpCoroJSONHandler class
  476. ///////////////////////////////////////////////////////////////////////////////
  477. // HttpCoroJSONHandler is a specialization of the LLCore::HttpHandler for
  478. // interacting with coroutines.
  479. //
  480. // In addition to the normal "http_results" the returned LLSD will contain JSON
  481. // entries will be converted into an LLSD map. All results are considered
  482. // strings
  483. class HttpCoroJSONHandler final : public HttpCoroHandler
  484. {
  485. public:
  486. HttpCoroJSONHandler(LLEventStream& reply)
  487. : HttpCoroHandler(reply)
  488. {
  489. }
  490. LLSD handleSuccess(LLCore::HttpResponse* response,
  491. LLCore::HttpStatus& status) override;
  492. LLSD parseBody(LLCore::HttpResponse* response, bool& success) override;
  493. };
  494. LLSD HttpCoroJSONHandler::handleSuccess(LLCore::HttpResponse* response,
  495. LLCore::HttpStatus& status)
  496. {
  497. LLSD result = LLSD::emptyMap();
  498. BufferArray* body = response ? response->getBody() : NULL;
  499. if (!body || !body->size())
  500. {
  501. return result;
  502. }
  503. LLCore::BufferArrayStream bas(body);
  504. lljson jsonroot;
  505. try
  506. {
  507. bas >> jsonroot;
  508. }
  509. catch (std::runtime_error& e)
  510. {
  511. // Deserialization failed. Record the reason and pass back an empty map
  512. // for markup.
  513. status = LLCore::HttpStatus(499, std::string(e.what()));
  514. return result;
  515. }
  516. // Convert the JSON structure to LLSD
  517. result = llsd_from_json(jsonroot);
  518. return result;
  519. }
  520. LLSD HttpCoroJSONHandler::parseBody(LLCore::HttpResponse* response,
  521. bool& success)
  522. {
  523. success = true;
  524. BufferArray* body = response ? response->getBody() : NULL;
  525. if (!body || !body->size())
  526. {
  527. return LLSD();
  528. }
  529. LLCore::BufferArrayStream bas(body);
  530. lljson jsonroot;
  531. try
  532. {
  533. bas >> jsonroot;
  534. }
  535. catch (std::runtime_error& e)
  536. {
  537. success = false;
  538. return LLSD();
  539. }
  540. // Convert the JSON structure to LLSD
  541. return llsd_from_json(jsonroot);
  542. }
  543. ///////////////////////////////////////////////////////////////////////////////
  544. // HttpCoroutineAdapter class
  545. ///////////////////////////////////////////////////////////////////////////////
  546. const std::string HttpCoroutineAdapter::HTTP_RESULTS("http_result");
  547. const std::string HttpCoroutineAdapter::HTTP_RESULTS_SUCCESS("success");
  548. const std::string HttpCoroutineAdapter::HTTP_RESULTS_TYPE("type");
  549. const std::string HttpCoroutineAdapter::HTTP_RESULTS_STATUS("status");
  550. const std::string HttpCoroutineAdapter::HTTP_RESULTS_MESSAGE("message");
  551. const std::string HttpCoroutineAdapter::HTTP_RESULTS_URL("url");
  552. const std::string HttpCoroutineAdapter::HTTP_RESULTS_HEADERS("headers");
  553. const std::string HttpCoroutineAdapter::HTTP_RESULTS_CONTENT("content");
  554. const std::string HttpCoroutineAdapter::HTTP_RESULTS_RAW("raw");
  555. //static
  556. HttpCoroutineAdapter::instances_list_t HttpCoroutineAdapter::sInstances;
  557. HttpCoroutineAdapter::HttpCoroutineAdapter(const std::string& name,
  558. LLCore::HttpRequest::ptr_t& request,
  559. LLCore::HttpRequest::policy_t polid)
  560. : mAdapterName(name),
  561. mPolicyId(polid),
  562. mYieldingHandle(LLCORE_HTTP_HANDLE_INVALID),
  563. mRequest(request)
  564. {
  565. sInstances.insert(this);
  566. }
  567. HttpCoroutineAdapter::HttpCoroutineAdapter(const std::string& name,
  568. LLCore::HttpRequest::policy_t polid)
  569. : mAdapterName(name),
  570. mPolicyId(polid),
  571. mYieldingHandle(LLCORE_HTTP_HANDLE_INVALID),
  572. mRequest(DEFAULT_HTTP_REQUEST)
  573. {
  574. sInstances.insert(this);
  575. }
  576. HttpCoroutineAdapter::~HttpCoroutineAdapter()
  577. {
  578. sInstances.erase(this);
  579. cancelSuspendedOperation();
  580. }
  581. //static
  582. void HttpCoroutineAdapter::cleanup()
  583. {
  584. if (sInstances.empty())
  585. {
  586. return;
  587. }
  588. llinfos << "Cancelling suspended operations on remaining adapters..."
  589. << llendl;
  590. // Note: just in case calling cancelSuspendedOperation() on one adapter
  591. // instance would destroy another instance, we consider that sInstances
  592. // could get modified during the loop, and thus copy it beforehand and
  593. // check each time that the adapter still exists in sInstances before
  594. // attempting to cancel its operation...
  595. instances_list_t copy = sInstances;
  596. for (instances_list_t::const_iterator it = copy.begin(), end = copy.end();
  597. it != end; ++it)
  598. {
  599. HttpCoroutineAdapter* adapter = *it;
  600. if (sInstances.count(adapter))
  601. {
  602. adapter->cancelSuspendedOperation();
  603. }
  604. }
  605. }
  606. LLSD HttpCoroutineAdapter::postAndSuspend(const std::string& url,
  607. const LLSD& body,
  608. LLCore::HttpOptions::ptr_t options,
  609. LLCore::HttpHeaders::ptr_t headers)
  610. {
  611. if (!mRequest)
  612. {
  613. llwarns << "Invalid request !" << llendl;
  614. return LLSD();
  615. }
  616. LLEventStream reply_pump(mAdapterName, true);
  617. HttpCoroHandler::ptr_t http_handler =
  618. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  619. return postAndSuspend_(url, body, options, headers, http_handler);
  620. }
  621. LLSD HttpCoroutineAdapter::postAndSuspend_(const std::string& url,
  622. const LLSD& body,
  623. LLCore::HttpOptions::ptr_t& options,
  624. LLCore::HttpHeaders::ptr_t& headers,
  625. HttpCoroHandler::ptr_t& handler)
  626. {
  627. checkDefaultHeaders(headers);
  628. // The HTTPCoroHandler does not self delete, so retrieval of a the
  629. // contained pointer from the smart pointer is safe in this case.
  630. LLCore::HttpHandle hhandle = requestPostWithLLSD(mRequest, mPolicyId,
  631. url, body, options,
  632. headers, handler);
  633. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  634. {
  635. return buildImmediateErrorResult(url);
  636. }
  637. saveState(url, hhandle, handler);
  638. HttpRequestPumper pumper(mRequest);
  639. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  640. cleanState();
  641. return results;
  642. }
  643. LLSD HttpCoroutineAdapter::postAndSuspend(const std::string& url,
  644. LLCore::BufferArray::ptr_t rawbody,
  645. LLCore::HttpOptions::ptr_t options,
  646. LLCore::HttpHeaders::ptr_t headers)
  647. {
  648. if (!mRequest)
  649. {
  650. llwarns << "Invalid request !" << llendl;
  651. return LLSD();
  652. }
  653. LLEventStream reply_pump(mAdapterName, true);
  654. HttpCoroHandler::ptr_t http_handler =
  655. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  656. return postAndSuspend_(url, rawbody, options, headers, http_handler);
  657. }
  658. LLSD HttpCoroutineAdapter::postRawAndSuspend(const std::string& url,
  659. LLCore::BufferArray::ptr_t rawbody,
  660. LLCore::HttpOptions::ptr_t options,
  661. LLCore::HttpHeaders::ptr_t headers)
  662. {
  663. if (!mRequest)
  664. {
  665. llwarns << "Invalid request !" << llendl;
  666. return LLSD();
  667. }
  668. LLEventStream reply_pump(mAdapterName, true);
  669. HttpCoroHandler::ptr_t http_handler =
  670. std::make_shared<HttpCoroRawHandler>(reply_pump);
  671. return postAndSuspend_(url, rawbody, options, headers, http_handler);
  672. }
  673. // *TODO: This functionality could be moved into the LLCore::Http library
  674. // itself by having the CURL layer read the file directly.
  675. LLSD HttpCoroutineAdapter::postFileAndSuspend(const std::string& url,
  676. std::string filename,
  677. LLCore::HttpOptions::ptr_t options,
  678. LLCore::HttpHeaders::ptr_t headers)
  679. {
  680. if (!mRequest)
  681. {
  682. llwarns << "Invalid request !" << llendl;
  683. return LLSD();
  684. }
  685. LLCore::BufferArray::ptr_t filedata(new LLCore::BufferArray);
  686. // Scoping for our streams so that they go away when we no longer need them
  687. {
  688. LLCore::BufferArrayStream outs(filedata.get());
  689. llifstream ins(filename.c_str(),
  690. std::iostream::binary | std::iostream::out);
  691. if (ins.is_open())
  692. {
  693. ins.seekg(0, std::ios::beg);
  694. ins >> std::noskipws;
  695. std::copy(std::istream_iterator<U8>(ins),
  696. std::istream_iterator<U8>(),
  697. std::ostream_iterator<U8>(outs));
  698. ins.close();
  699. }
  700. }
  701. return postAndSuspend(url, filedata, options, headers);
  702. }
  703. // *TODO: This functionality could be moved into the LLCore::Http library
  704. // itself by having the CURL layer read the file directly.
  705. LLSD HttpCoroutineAdapter::postFileAndSuspend(const std::string& url,
  706. const LLUUID& assetid,
  707. LLAssetType::EType assetType,
  708. LLCore::HttpOptions::ptr_t options,
  709. LLCore::HttpHeaders::ptr_t headers)
  710. {
  711. if (!mRequest)
  712. {
  713. llwarns << "Invalid request !" << llendl;
  714. return LLSD();
  715. }
  716. LLCore::BufferArray::ptr_t filedata(new LLCore::BufferArray);
  717. // Scoping for our streams so that they go away when we no longer need them
  718. {
  719. LLCore::BufferArrayStream outs(filedata.get());
  720. LLFileSystem vfile(assetid);
  721. S32 file_size = vfile.getSize();
  722. U8* file_buffer = new U8[file_size];
  723. vfile.read(file_buffer, file_size);
  724. outs.write((char*)file_buffer, file_size);
  725. delete[] file_buffer;
  726. }
  727. return postAndSuspend(url, filedata, options, headers);
  728. }
  729. LLSD HttpCoroutineAdapter::postJsonAndSuspend(const std::string& url,
  730. const LLSD& body,
  731. LLCore::HttpOptions::ptr_t options,
  732. LLCore::HttpHeaders::ptr_t headers)
  733. {
  734. if (!mRequest)
  735. {
  736. llwarns << "Invalid request !" << llendl;
  737. return LLSD();
  738. }
  739. LLEventStream reply_pump(mAdapterName, true);
  740. HttpCoroHandler::ptr_t http_handler =
  741. std::make_shared<HttpCoroJSONHandler>(reply_pump);
  742. LLCore::BufferArray::ptr_t rawbody(new LLCore::BufferArray);
  743. {
  744. LLCore::BufferArrayStream outs(rawbody.get());
  745. lljson root = llsd_to_json(body);
  746. LL_DEBUGS("CoreHttp") << "JSON Generates: " << root << LL_ENDL;
  747. outs << root;
  748. }
  749. return postAndSuspend_(url, rawbody, options, headers, http_handler);
  750. }
  751. LLSD HttpCoroutineAdapter::postAndSuspend_(const std::string& url,
  752. LLCore::BufferArray::ptr_t& rawbody,
  753. LLCore::HttpOptions::ptr_t& options,
  754. LLCore::HttpHeaders::ptr_t& headers,
  755. HttpCoroHandler::ptr_t& handler)
  756. {
  757. checkDefaultHeaders(headers);
  758. // The HTTPCoroHandler does not self delete, so retrieval of a the
  759. // contained pointer from the smart pointer is safe in this case.
  760. LLCore::HttpHandle hhandle = mRequest->requestPost(mPolicyId, url,
  761. rawbody.get(), options,
  762. headers, handler);
  763. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  764. {
  765. return buildImmediateErrorResult(url);
  766. }
  767. saveState(url, hhandle, handler);
  768. HttpRequestPumper pumper(mRequest);
  769. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  770. cleanState();
  771. return results;
  772. }
  773. LLSD HttpCoroutineAdapter::putAndSuspend(const std::string& url,
  774. const LLSD& body,
  775. LLCore::HttpOptions::ptr_t options,
  776. LLCore::HttpHeaders::ptr_t headers)
  777. {
  778. if (!mRequest)
  779. {
  780. llwarns << "Invalid request !" << llendl;
  781. return LLSD();
  782. }
  783. LLEventStream reply_pump(mAdapterName + "Reply", true);
  784. HttpCoroHandler::ptr_t http_handler =
  785. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  786. return putAndSuspend_(url, body, options, headers, http_handler);
  787. }
  788. LLSD HttpCoroutineAdapter::putJsonAndSuspend(const std::string& url,
  789. const LLSD& body,
  790. LLCore::HttpOptions::ptr_t options,
  791. LLCore::HttpHeaders::ptr_t headers)
  792. {
  793. if (!mRequest)
  794. {
  795. llwarns << "Invalid request !" << llendl;
  796. return LLSD();
  797. }
  798. LLEventStream reply_pump(mAdapterName, true);
  799. HttpCoroHandler::ptr_t http_handler =
  800. std::make_shared<HttpCoroJSONHandler>(reply_pump);
  801. LLCore::BufferArray::ptr_t rawbody(new LLCore::BufferArray);
  802. {
  803. LLCore::BufferArrayStream outs(rawbody.get());
  804. lljson root = llsd_to_json(body);
  805. LL_DEBUGS("CoreHttp") << "JSON Generates: " << root << LL_ENDL;
  806. outs << root;
  807. }
  808. return putAndSuspend_(url, rawbody, options, headers, http_handler);
  809. }
  810. LLSD HttpCoroutineAdapter::putAndSuspend_(const std::string& url,
  811. const LLSD& body,
  812. LLCore::HttpOptions::ptr_t& options,
  813. LLCore::HttpHeaders::ptr_t& headers,
  814. HttpCoroHandler::ptr_t& handler)
  815. {
  816. checkDefaultHeaders(headers);
  817. // The HTTPCoroHandler does not self delete, so retrieval of a the
  818. // contained pointer from the smart pointer is safe in this case.
  819. LLCore::HttpHandle hhandle = requestPutWithLLSD(mRequest, mPolicyId, url,
  820. body, options, headers,
  821. handler);
  822. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  823. {
  824. return buildImmediateErrorResult(url);
  825. }
  826. saveState(url, hhandle, handler);
  827. HttpRequestPumper pumper(mRequest);
  828. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  829. cleanState();
  830. return results;
  831. }
  832. LLSD HttpCoroutineAdapter::putAndSuspend_(const std::string& url,
  833. const LLCore::BufferArray::ptr_t& rawbody,
  834. LLCore::HttpOptions::ptr_t& options,
  835. LLCore::HttpHeaders::ptr_t& headers,
  836. HttpCoroHandler::ptr_t& handler)
  837. {
  838. checkDefaultHeaders(headers);
  839. // The HTTPCoroHandler does not self delete, so retrieval of a the
  840. // contained pointer from the smart pointer is safe in this case.
  841. LLCore::HttpHandle hhandle = mRequest->requestPut(mPolicyId, url,
  842. rawbody.get(), options,
  843. headers, handler);
  844. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  845. {
  846. return buildImmediateErrorResult(url);
  847. }
  848. saveState(url, hhandle, handler);
  849. HttpRequestPumper pumper(mRequest);
  850. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  851. cleanState();
  852. return results;
  853. }
  854. LLSD HttpCoroutineAdapter::getAndSuspend(const std::string& url,
  855. LLCore::HttpOptions::ptr_t options,
  856. LLCore::HttpHeaders::ptr_t headers)
  857. {
  858. if (!mRequest)
  859. {
  860. llwarns << "Invalid request !" << llendl;
  861. return LLSD();
  862. }
  863. LLEventStream reply_pump(mAdapterName + "Reply", true);
  864. HttpCoroHandler::ptr_t http_handler =
  865. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  866. return getAndSuspend_(url, options, headers, http_handler);
  867. }
  868. LLSD HttpCoroutineAdapter::getRawAndSuspend(const std::string& url,
  869. LLCore::HttpOptions::ptr_t options,
  870. LLCore::HttpHeaders::ptr_t headers)
  871. {
  872. if (!mRequest)
  873. {
  874. llwarns << "Invalid request !" << llendl;
  875. return LLSD();
  876. }
  877. LLEventStream reply_pump(mAdapterName + "Reply", true);
  878. HttpCoroHandler::ptr_t http_handler =
  879. std::make_shared<HttpCoroRawHandler>(reply_pump);
  880. return getAndSuspend_(url, options, headers, http_handler);
  881. }
  882. LLSD HttpCoroutineAdapter::getJsonAndSuspend(const std::string& url,
  883. LLCore::HttpOptions::ptr_t options,
  884. LLCore::HttpHeaders::ptr_t headers)
  885. {
  886. if (!mRequest)
  887. {
  888. llwarns << "Invalid request !" << llendl;
  889. return LLSD();
  890. }
  891. LLEventStream reply_pump(mAdapterName + "Reply", true);
  892. HttpCoroHandler::ptr_t http_handler =
  893. std::make_shared<HttpCoroJSONHandler>(reply_pump);
  894. return getAndSuspend_(url, options, headers, http_handler);
  895. }
  896. LLSD HttpCoroutineAdapter::getAndSuspend_(const std::string& url,
  897. LLCore::HttpOptions::ptr_t& options,
  898. LLCore::HttpHeaders::ptr_t& headers,
  899. HttpCoroHandler::ptr_t& handler)
  900. {
  901. checkDefaultHeaders(headers);
  902. // The HTTPCoroHandler does not self delete, so retrieval of a the
  903. // contained pointer from the smart pointer is safe in this case.
  904. LLCore::HttpHandle hhandle = mRequest->requestGet(mPolicyId, url, options,
  905. headers, handler);
  906. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  907. {
  908. return buildImmediateErrorResult(url);
  909. }
  910. saveState(url, hhandle, handler);
  911. HttpRequestPumper pumper(mRequest);
  912. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  913. cleanState();
  914. return results;
  915. }
  916. LLSD HttpCoroutineAdapter::deleteAndSuspend(const std::string& url,
  917. LLCore::HttpOptions::ptr_t options,
  918. LLCore::HttpHeaders::ptr_t headers)
  919. {
  920. if (!mRequest)
  921. {
  922. llwarns << "Invalid request !" << llendl;
  923. return LLSD();
  924. }
  925. LLEventStream reply_pump(mAdapterName + "Reply", true);
  926. HttpCoroHandler::ptr_t http_handler =
  927. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  928. return deleteAndSuspend_(url, options, headers, http_handler);
  929. }
  930. LLSD HttpCoroutineAdapter::deleteJsonAndSuspend(const std::string& url,
  931. LLCore::HttpOptions::ptr_t options,
  932. LLCore::HttpHeaders::ptr_t headers)
  933. {
  934. if (!mRequest)
  935. {
  936. llwarns << "Invalid request !" << llendl;
  937. return LLSD();
  938. }
  939. LLEventStream reply_pump(mAdapterName + "Reply", true);
  940. HttpCoroHandler::ptr_t http_handler =
  941. std::make_shared<HttpCoroJSONHandler>(reply_pump);
  942. return deleteAndSuspend_(url, options, headers, http_handler);
  943. }
  944. LLSD HttpCoroutineAdapter::deleteAndSuspend_(const std::string& url,
  945. LLCore::HttpOptions::ptr_t& options,
  946. LLCore::HttpHeaders::ptr_t& headers,
  947. HttpCoroHandler::ptr_t& handler)
  948. {
  949. checkDefaultHeaders(headers);
  950. // The HTTPCoroHandler does not self delete, so retrieval of a the
  951. // contained pointer from the smart pointer is safe in this case.
  952. LLCore::HttpHandle hhandle = mRequest->requestDelete(mPolicyId, url,
  953. options, headers,
  954. handler);
  955. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  956. {
  957. return buildImmediateErrorResult(url);
  958. }
  959. saveState(url, hhandle, handler);
  960. HttpRequestPumper pumper(mRequest);
  961. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  962. cleanState();
  963. return results;
  964. }
  965. LLSD HttpCoroutineAdapter::patchAndSuspend(const std::string& url,
  966. const LLSD& body,
  967. LLCore::HttpOptions::ptr_t options,
  968. LLCore::HttpHeaders::ptr_t headers)
  969. {
  970. if (!mRequest)
  971. {
  972. llwarns << "Invalid request !" << llendl;
  973. return LLSD();
  974. }
  975. LLEventStream reply_pump(mAdapterName + "Reply", true);
  976. HttpCoroHandler::ptr_t http_handler =
  977. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  978. return patchAndSuspend_(url, body, options, headers, http_handler);
  979. }
  980. LLSD HttpCoroutineAdapter::patchAndSuspend_(const std::string& url,
  981. const LLSD& body,
  982. LLCore::HttpOptions::ptr_t& options,
  983. LLCore::HttpHeaders::ptr_t& headers,
  984. HttpCoroHandler::ptr_t& handler)
  985. {
  986. checkDefaultHeaders(headers);
  987. // The HTTPCoroHandler does not self delete, so retrieval of a the
  988. // contained pointer from the smart pointer is safe in this case.
  989. LLCore::HttpHandle hhandle = requestPatchWithLLSD(mRequest, mPolicyId, url,
  990. body, options, headers,
  991. handler);
  992. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  993. {
  994. return buildImmediateErrorResult(url);
  995. }
  996. saveState(url, hhandle, handler);
  997. HttpRequestPumper pumper(mRequest);
  998. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  999. cleanState();
  1000. return results;
  1001. }
  1002. LLSD HttpCoroutineAdapter::copyAndSuspend(const std::string& url,
  1003. const std::string dest,
  1004. LLCore::HttpOptions::ptr_t options,
  1005. LLCore::HttpHeaders::ptr_t headers)
  1006. {
  1007. if (!mRequest)
  1008. {
  1009. llwarns << "Invalid request !" << llendl;
  1010. return LLSD();
  1011. }
  1012. LLEventStream reply_pump(mAdapterName + "Reply", true);
  1013. HttpCoroHandler::ptr_t http_handler =
  1014. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  1015. if (!headers)
  1016. {
  1017. headers.reset(new LLCore::HttpHeaders);
  1018. }
  1019. headers->append(HTTP_OUT_HEADER_DESTINATION, dest);
  1020. return copyAndSuspend_(url, options, headers, http_handler);
  1021. }
  1022. LLSD HttpCoroutineAdapter::copyAndSuspend_(const std::string& url,
  1023. LLCore::HttpOptions::ptr_t& options,
  1024. LLCore::HttpHeaders::ptr_t& headers,
  1025. HttpCoroHandler::ptr_t& handler)
  1026. {
  1027. checkDefaultHeaders(headers);
  1028. // The HTTPCoroHandler does not self delete, so retrieval of a the
  1029. // contained pointer from the smart pointer is safe in this case.
  1030. LLCore::HttpHandle hhandle = mRequest->requestCopy(mPolicyId, url, options,
  1031. headers, handler);
  1032. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  1033. {
  1034. return buildImmediateErrorResult(url);
  1035. }
  1036. saveState(url, hhandle, handler);
  1037. HttpRequestPumper pumper(mRequest);
  1038. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  1039. cleanState();
  1040. return results;
  1041. }
  1042. LLSD HttpCoroutineAdapter::moveAndSuspend(const std::string& url,
  1043. const std::string dest,
  1044. LLCore::HttpOptions::ptr_t options,
  1045. LLCore::HttpHeaders::ptr_t headers)
  1046. {
  1047. if (!mRequest)
  1048. {
  1049. llwarns << "Invalid request !" << llendl;
  1050. return LLSD();
  1051. }
  1052. LLEventStream reply_pump(mAdapterName + "Reply", true);
  1053. HttpCoroHandler::ptr_t http_handler =
  1054. std::make_shared<HttpCoroLLSDHandler>(reply_pump);
  1055. if (!headers)
  1056. {
  1057. headers.reset(new LLCore::HttpHeaders);
  1058. }
  1059. headers->append(HTTP_OUT_HEADER_DESTINATION, dest);
  1060. return moveAndSuspend_(url, options, headers, http_handler);
  1061. }
  1062. LLSD HttpCoroutineAdapter::moveAndSuspend_(const std::string& url,
  1063. LLCore::HttpOptions::ptr_t& options,
  1064. LLCore::HttpHeaders::ptr_t& headers,
  1065. HttpCoroHandler::ptr_t& handler)
  1066. {
  1067. if (!mRequest)
  1068. {
  1069. llwarns << "Invalid request !" << llendl;
  1070. return LLSD();
  1071. }
  1072. checkDefaultHeaders(headers);
  1073. // The HTTPCoroHandler does not self delete, so retrieval of a the
  1074. // contained pointer from the smart pointer is safe in this case.
  1075. LLCore::HttpHandle hhandle = mRequest->requestMove(mPolicyId, url, options,
  1076. headers, handler);
  1077. if (hhandle == LLCORE_HTTP_HANDLE_INVALID)
  1078. {
  1079. return buildImmediateErrorResult(url);
  1080. }
  1081. saveState(url, hhandle, handler);
  1082. HttpRequestPumper pumper(mRequest);
  1083. LLSD results = llcoro::suspendUntilEventOn(handler->getReplyPump());
  1084. cleanState();
  1085. return results;
  1086. }
  1087. void HttpCoroutineAdapter::checkDefaultHeaders(LLCore::HttpHeaders::ptr_t& headers)
  1088. {
  1089. if (!headers)
  1090. {
  1091. headers.reset(new LLCore::HttpHeaders);
  1092. }
  1093. if (!headers->find(HTTP_OUT_HEADER_ACCEPT))
  1094. {
  1095. headers->append(HTTP_OUT_HEADER_ACCEPT, HTTP_CONTENT_LLSD_XML);
  1096. }
  1097. if (!headers->find(HTTP_OUT_HEADER_CONTENT_TYPE))
  1098. {
  1099. headers->append(HTTP_OUT_HEADER_CONTENT_TYPE, HTTP_CONTENT_LLSD_XML);
  1100. }
  1101. if (gMessageSystemp && !headers->find("X-SecondLife-UDP-Listen-Port"))
  1102. {
  1103. headers->append("X-SecondLife-UDP-Listen-Port",
  1104. llformat("%d", gMessageSystemp->mPort));
  1105. }
  1106. }
  1107. void HttpCoroutineAdapter::cancelSuspendedOperation()
  1108. {
  1109. LLCore::HttpRequest::ptr_t request = mWeakRequest.lock();
  1110. HttpCoroHandler::ptr_t handler = mWeakHandler.lock();
  1111. if (request && handler && mYieldingHandle != LLCORE_HTTP_HANDLE_INVALID)
  1112. {
  1113. llinfos << "Cancelling yielding request for " << mAdapterName
  1114. << llendl;
  1115. request->requestCancel(mYieldingHandle, handler);
  1116. cleanState();
  1117. // We now need to wake up the coroutine, else it might keep sitting
  1118. // there for a while, which would be a problem on viewer exit. HB
  1119. // First, create a fake result LLSD with cancelled operation as the
  1120. // error status.
  1121. LLSD status = LLSD::emptyMap();
  1122. HttpCoroHandler::writeStatusCodes(gStatusCancelled, mURL, status);
  1123. LLSD result = LLSD::emptyMap();
  1124. result["http_result"] = status;
  1125. // Then, post to the associated pump, passing the fake result LLSD.
  1126. // IMPORTANT: since this call shall result in the exit of the coroutine
  1127. // and likely the destruction of our adapter instance, it *must* be
  1128. // immediately followed by a return.
  1129. handler->getReplyPump().post(result);
  1130. return;
  1131. }
  1132. LL_DEBUGS("CoreHttp") << "Operation for " << mAdapterName;
  1133. if (!handler)
  1134. {
  1135. LL_CONT << " already finished";
  1136. }
  1137. else if (!request)
  1138. {
  1139. LL_CONT << " got a NULL request pointer";
  1140. }
  1141. else
  1142. {
  1143. LL_CONT << " not yielding";
  1144. }
  1145. LL_CONT << LL_ENDL;
  1146. }
  1147. void HttpCoroutineAdapter::saveState(const std::string& url,
  1148. LLCore::HttpHandle yielding_handle,
  1149. HttpCoroHandler::ptr_t& handler)
  1150. {
  1151. mURL = url;
  1152. mWeakRequest = mRequest;
  1153. mWeakHandler = handler;
  1154. mYieldingHandle = yielding_handle;
  1155. }
  1156. void HttpCoroutineAdapter::cleanState()
  1157. {
  1158. mURL.clear();
  1159. mWeakRequest.reset();
  1160. mWeakHandler.reset();
  1161. mYieldingHandle = LLCORE_HTTP_HANDLE_INVALID;
  1162. }
  1163. LLSD HttpCoroutineAdapter::buildImmediateErrorResult(const std::string& url)
  1164. {
  1165. if (!mRequest)
  1166. {
  1167. llwarns << "Invalid request !" << llendl;
  1168. return LLSD();
  1169. }
  1170. LLCore::HttpStatus status = mRequest->getStatus();
  1171. llwarns << "Error posting to: " << url << " - Status: "
  1172. << status.getStatus() << " - Message: " << status.getMessage()
  1173. << llendl;
  1174. // Mimic the status results returned from an http error that we had to wait
  1175. // on
  1176. LLSD httpresults = LLSD::emptyMap();
  1177. HttpCoroHandler::writeStatusCodes(status, url, httpresults);
  1178. LLSD errors = LLSD::emptyMap();
  1179. errors["http_result"] = httpresults;
  1180. return errors;
  1181. }
  1182. //static
  1183. LLCore::HttpStatus HttpCoroutineAdapter::getStatusFromLLSD(const LLSD& results)
  1184. {
  1185. const LLSD* resp;
  1186. if (results.has(HttpCoroutineAdapter::HTTP_RESULTS))
  1187. {
  1188. resp = &results[HttpCoroutineAdapter::HTTP_RESULTS];
  1189. }
  1190. else
  1191. {
  1192. resp = &results;
  1193. }
  1194. S32 type = (*resp)[HttpCoroutineAdapter::HTTP_RESULTS_TYPE].asInteger();
  1195. S32 code = (*resp)[HttpCoroutineAdapter::HTTP_RESULTS_STATUS].asInteger();
  1196. return LLCore::HttpStatus((LLCore::HttpStatus::type_enum_t)type,
  1197. (short)code);
  1198. }
  1199. //static
  1200. void HttpCoroutineAdapter::callbackHttpGet(const std::string& url,
  1201. LLCore::HttpRequest::policy_t policy_id,
  1202. completionCallback_t success,
  1203. completionCallback_t failure)
  1204. {
  1205. gCoros.launch("HttpCoroutineAdapter::genericGetCoro",
  1206. boost::bind(&HttpCoroutineAdapter::trivialGetCoro, url,
  1207. policy_id, success, failure));
  1208. }
  1209. //static
  1210. void HttpCoroutineAdapter::messageHttpGet(const std::string& url,
  1211. const std::string& success,
  1212. const std::string& failure)
  1213. {
  1214. completionCallback_t cb_succ = NULL;
  1215. if (!success.empty())
  1216. {
  1217. cb_succ = (completionCallback_t)boost::bind(&logMessageSuccess,
  1218. "HttpCoroutineAdapter",
  1219. url, success);
  1220. }
  1221. completionCallback_t cb_fail = NULL;
  1222. if (!failure.empty())
  1223. {
  1224. cb_fail = (completionCallback_t)boost::bind(&logMessageFail,
  1225. "HttpCoroutineAdapter",
  1226. url, failure);
  1227. }
  1228. callbackHttpGet(url, cb_succ, cb_fail);
  1229. }
  1230. //static
  1231. void HttpCoroutineAdapter::trivialGetCoro(std::string url,
  1232. LLCore::HttpRequest::policy_t policy_id,
  1233. completionCallback_t success,
  1234. completionCallback_t failure)
  1235. {
  1236. LL_DEBUGS("CoreHttp") << "Generic GET for: " << url << LL_ENDL;
  1237. LLCore::HttpOptions::ptr_t options(DEFAULT_HTTP_OPTIONS);
  1238. options->setWantHeaders(true);
  1239. LLCoreHttpUtil::HttpCoroutineAdapter adapter("genericGetCoro", policy_id);
  1240. LLSD result = adapter.getAndSuspend(url, options);
  1241. LLCore::HttpStatus status =
  1242. LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(result);
  1243. if (status)
  1244. {
  1245. if (success)
  1246. {
  1247. success(result);
  1248. }
  1249. }
  1250. else if (failure)
  1251. {
  1252. const LLSD& http_results =
  1253. result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
  1254. failure(http_results);
  1255. }
  1256. }
  1257. //static
  1258. void HttpCoroutineAdapter::callbackHttpPost(const std::string& url,
  1259. LLCore::HttpRequest::policy_t policy_id,
  1260. const LLSD& postdata,
  1261. completionCallback_t success,
  1262. completionCallback_t failure)
  1263. {
  1264. gCoros.launch("HttpCoroutineAdapter::genericPostCoro",
  1265. boost::bind(&HttpCoroutineAdapter::trivialPostCoro, url,
  1266. policy_id, postdata, success, failure));
  1267. }
  1268. //static
  1269. void HttpCoroutineAdapter::messageHttpPost(const std::string& url,
  1270. const LLSD& postdata,
  1271. const std::string& success,
  1272. const std::string& failure)
  1273. {
  1274. completionCallback_t cb_succ = NULL;
  1275. if (!success.empty())
  1276. {
  1277. cb_succ = (completionCallback_t)boost::bind(&logMessageSuccess,
  1278. "HttpCoroutineAdapter",
  1279. url, success);
  1280. }
  1281. completionCallback_t cb_fail = NULL;
  1282. if (!failure.empty())
  1283. {
  1284. cb_fail = (completionCallback_t)boost::bind(&logMessageFail,
  1285. "HttpCoroutineAdapter",
  1286. url, failure);
  1287. }
  1288. callbackHttpPost(url, postdata, cb_succ, cb_fail);
  1289. }
  1290. //static
  1291. void HttpCoroutineAdapter::trivialPostCoro(std::string url,
  1292. LLCore::HttpRequest::policy_t policy_id,
  1293. LLSD postdata,
  1294. completionCallback_t success,
  1295. completionCallback_t failure)
  1296. {
  1297. LL_DEBUGS("CoreHttp") << "Generic POST for: " << url << LL_ENDL;
  1298. LLCore::HttpOptions::ptr_t options(DEFAULT_HTTP_OPTIONS);
  1299. options->setWantHeaders(true);
  1300. LLCoreHttpUtil::HttpCoroutineAdapter adapter("genericPostCoro", policy_id);
  1301. LLSD result = adapter.postAndSuspend(url, postdata, options);
  1302. LLCore::HttpStatus status =
  1303. LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(result);
  1304. if (status)
  1305. {
  1306. // If a success routine is provided call it.
  1307. if (success)
  1308. {
  1309. success(result);
  1310. }
  1311. }
  1312. else if (failure)
  1313. {
  1314. // If a failure routine is provided call it.
  1315. const LLSD& http_results =
  1316. result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
  1317. failure(http_results);
  1318. }
  1319. }
  1320. } // End namespace LLCoreHttpUtil