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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
|
/**
* @file llwebsharing.cpp
* @author Aimee
* @brief Web Snapshot Sharing
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llwebsharing.h"
#include "llagentui.h"
#include "llbufferstream.h"
#include "llhttpclient.h"
#include "llhttpconstants.h"
#include "llsdserialize.h"
#include "llsdutil.h"
#include "llurl.h"
#include "llviewercontrol.h"
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
///////////////////////////////////////////////////////////////////////////////
//
class LLWebSharingJSONResponder : public LLHTTPClient::Responder
{
LOG_CLASS(LLWebSharingJSONResponder);
public:
/// Overrides the default LLSD parsing behaviour, to allow parsing a JSON response.
virtual void completedRaw(const LLChannelDescriptors& channels,
const LLIOPipe::buffer_ptr_t& buffer)
{
LLBufferStream istr(channels, buffer.get());
// *TODO: LLSD notation is not actually JSON.
LLPointer<LLSDParser> parser = new LLSDNotationParser();
std::string debug_body("(empty)");
bool parsed=true;
if (EOF == istr.peek())
{
parsed=false;
}
// Try to parse body as llsd, no matter what 'content-type' says.
else if (parser->parse(istr, mContent, LLSDSerialize::SIZE_UNLIMITED) == LLSDParser::PARSE_FAILURE)
{
parsed=false;
char body[1025];
body[1024] = '\0';
istr.seekg(0, std::ios::beg);
istr.get(body,1024);
if (strlen(body) > 0)
{
mContent = body;
debug_body = body;
}
}
// Only emit a warning if we failed to parse when 'content-type' == 'application/json'
if (!parsed && (HTTP_CONTENT_JSON == getResponseHeader(HTTP_IN_HEADER_CONTENT_TYPE)))
{
llwarns << "Failed to deserialize LLSD from JSON response. " << getURL()
<< " [status:" << mStatus << "] "
<< "(" << mReason << ") body: " << debug_body << llendl;
}
if (!parsed)
{
// *TODO: This isn't necessarily the server's fault. Using a 5xx code
// isn't really appropriate here.
// Also, this hides the actual status returned by the server....
mStatus = HTTP_INTERNAL_ERROR;
mReason = "Failed to deserialize LLSD from JSON response.";
}
httpCompleted();
}
};
class LLWebSharingConfigResponder : public LLWebSharingJSONResponder
{
LOG_CLASS(LLWebSharingConfigResponder);
private:
virtual void httpFailure()
{
LL_WARNS("WebSharing") << dumpResponse() << LL_ENDL;
}
virtual void httpSuccess()
{
const LLSD& content = getContent();
if (!content.isMap())
{
failureResult(HTTP_INTERNAL_ERROR, "Malformed response contents", content);
return;
}
LLWebSharing::instance().receiveConfig(content);
}
};
///////////////////////////////////////////////////////////////////////////////
//
class LLWebSharingOpenIDAuthResponder : public LLHTTPClient::Responder
{
LOG_CLASS(LLWebSharingOpenIDAuthResponder);
public:
/* virtual */ void completedRaw(const LLChannelDescriptors& channels,
const LLIOPipe::buffer_ptr_t& buffer)
{
/// Left empty to override the default LLSD parsing behaviour.
httpCompleted();
}
private:
virtual void httpFailure()
{
if (HTTP_UNAUTHORIZED == getStatus())
{
LL_WARNS("WebSharing") << "AU account not authenticated." << LL_ENDL;
// *TODO: No account found on AU, so start the account creation process here.
}
else
{
LL_WARNS("WebSharing") << dumpResponse() << LL_ENDL;
LLWebSharing::instance().retryOpenIDAuth();
}
}
virtual void httpSuccess()
{
if (hasResponseHeader(HTTP_IN_HEADER_SET_COOKIE))
{
// OpenID request succeeded and returned a session cookie.
LLWebSharing::instance().receiveSessionCookie(getResponseHeader(HTTP_IN_HEADER_SET_COOKIE));
}
}
};
///////////////////////////////////////////////////////////////////////////////
//
class LLWebSharingSecurityTokenResponder : public LLWebSharingJSONResponder
{
LOG_CLASS(LLWebSharingSecurityTokenResponder);
private:
virtual void httpFailure()
{
LL_WARNS("WebSharing") << dumpResponse() << LL_ENDL;
LLWebSharing::instance().retryOpenIDAuth();
}
virtual void httpSuccess()
{
const LLSD& content = getContent();
if (content[0].has("st") && content[0].has("expires"))
{
const std::string& token = content[0]["st"].asString();
const std::string& expires = content[0]["expires"].asString();
if (LLWebSharing::instance().receiveSecurityToken(token, expires))
{
// Sucessfully received a valid security token.
return;
}
}
else
{
failureResult(HTTP_INTERNAL_ERROR, "No security token received.", content);
return;
}
LLWebSharing::instance().retryOpenIDAuth();
}
};
///////////////////////////////////////////////////////////////////////////////
//
class LLWebSharingUploadResponder : public LLWebSharingJSONResponder
{
LOG_CLASS(LLWebSharingUploadResponder);
private:
virtual void httpFailure()
{
LL_WARNS("WebSharing") << dumpResponse() << LL_ENDL;
}
virtual void httpSuccess()
{
const LLSD& content = getContent();
if (content[0].has("result") && content[0].has("id") &&
content[0]["id"].asString() == "newMediaItem")
{
// *TODO: Upload successful, continue from here to post metadata and create AU activity.
}
else
{
failureResult(HTTP_INTERNAL_ERROR, "Invalid response content", content);
return;
}
}
};
///////////////////////////////////////////////////////////////////////////////
//
LLWebSharing::LLWebSharing()
: mConfig(),
mSecurityToken(LLSD::emptyMap()),
mEnabled(false),
mRetries(0),
mImage(NULL),
mMetadata(LLSD::emptyMap())
{
}
void LLWebSharing::init()
{
if (!mEnabled)
{
sendConfigRequest();
}
}
bool LLWebSharing::shareSnapshot(LLImageJPEG* snapshot, LLSD& metadata)
{
LL_INFOS("WebSharing") << metadata << LL_ENDL;
if (mImage)
{
// *TODO: Handle this possibility properly, queue them up?
LL_WARNS("WebSharing") << "Snapshot upload already in progress." << LL_ENDL;
return false;
}
mImage = snapshot;
mMetadata = metadata;
// *TODO: Check whether we have a valid security token already and re-use it.
sendOpenIDAuthRequest();
return true;
}
bool LLWebSharing::setOpenIDCookie(const std::string& cookie)
{
LL_DEBUGS("WebSharing") << "Setting OpenID cookie " << cookie << LL_ENDL;
mOpenIDCookie = cookie;
return validateConfig();
}
bool LLWebSharing::receiveConfig(const LLSD& config)
{
LL_DEBUGS("WebSharing") << "Received config data: " << config << LL_ENDL;
mConfig = config;
return validateConfig();
}
bool LLWebSharing::receiveSessionCookie(const std::string& cookie)
{
LL_DEBUGS("WebSharing") << "Received AU session cookie: " << cookie << LL_ENDL;
mSessionCookie = cookie;
// Fetch a security token using the new session cookie.
LLWebSharing::instance().sendSecurityTokenRequest();
return (!mSessionCookie.empty());
}
bool LLWebSharing::receiveSecurityToken(const std::string& token, const std::string& expires)
{
mSecurityToken["st"] = token;
mSecurityToken["expires"] = LLDate(expires);
if (!securityTokenIsValid(mSecurityToken))
{
LL_WARNS("WebSharing") << "Invalid security token received: \"" << token << "\" Expires: " << expires << LL_ENDL;
return false;
}
LL_DEBUGS("WebSharing") << "Received security token: \"" << token << "\" Expires: " << expires << LL_ENDL;
mRetries = 0;
// Continue the upload process now that we have a security token.
sendUploadRequest();
return true;
}
void LLWebSharing::sendConfigRequest()
{
std::string config_url = gSavedSettings.getString("SnapshotConfigURL");
LL_DEBUGS("WebSharing") << "Requesting Snapshot Sharing config data from: " << config_url << LL_ENDL;
LLSD headers = LLSD::emptyMap();
headers[HTTP_OUT_HEADER_ACCEPT] = HTTP_CONTENT_JSON;
LLHTTPClient::get(config_url, new LLWebSharingConfigResponder(), headers);
}
void LLWebSharing::sendOpenIDAuthRequest()
{
std::string auth_url = mConfig["openIdAuthUrl"];
LL_DEBUGS("WebSharing") << "Starting OpenID Auth: " << auth_url << LL_ENDL;
LLSD headers = LLSD::emptyMap();
headers[HTTP_OUT_HEADER_COOKIE] = mOpenIDCookie;
headers[HTTP_OUT_HEADER_ACCEPT] = "*/*";
// Send request, successful login will trigger fetching a security token.
LLHTTPClient::get(auth_url, new LLWebSharingOpenIDAuthResponder(), headers);
}
bool LLWebSharing::retryOpenIDAuth()
{
if (mRetries++ >= MAX_AUTH_RETRIES)
{
LL_WARNS("WebSharing") << "Exceeded maximum number of authorization attempts, aborting." << LL_ENDL;
mRetries = 0;
return false;
}
LL_WARNS("WebSharing") << "Authorization failed, retrying (" << mRetries << "/" << MAX_AUTH_RETRIES << ")" << LL_ENDL;
sendOpenIDAuthRequest();
return true;
}
void LLWebSharing::sendSecurityTokenRequest()
{
std::string token_url = mConfig["securityTokenUrl"];
LL_DEBUGS("WebSharing") << "Fetching security token from: " << token_url << LL_ENDL;
LLSD headers = LLSD::emptyMap();
headers[HTTP_OUT_HEADER_COOKIE] = mSessionCookie;
headers[HTTP_OUT_HEADER_ACCEPT] = HTTP_CONTENT_JSON;
headers[HTTP_OUT_HEADER_CONTENT_TYPE] = HTTP_CONTENT_JSON;
std::ostringstream body;
body << "{ \"gadgets\": [{ \"url\":\""
<< mConfig["gadgetSpecUrl"].asString()
<< "\" }] }";
// postRaw() takes ownership of the buffer and releases it later.
size_t size = body.str().size();
U8 *data = new U8[size];
memcpy(data, body.str().data(), size);
// Send request, receiving a valid token will trigger snapshot upload.
LLHTTPClient::postRaw(token_url, data, size, new LLWebSharingSecurityTokenResponder(), headers);
}
void LLWebSharing::sendUploadRequest()
{
LLUriTemplate upload_template(mConfig["openSocialRpcUrlTemplate"].asString());
std::string upload_url(upload_template.buildURI(mSecurityToken));
LL_DEBUGS("WebSharing") << "Posting upload to: " << upload_url << LL_ENDL;
static const std::string BOUNDARY("------------abcdef012345xyZ");
LLSD headers = LLSD::emptyMap();
headers[HTTP_OUT_HEADER_COOKIE] = mSessionCookie;
headers[HTTP_OUT_HEADER_ACCEPT] = HTTP_CONTENT_JSON;
headers[HTTP_OUT_HEADER_CONTENT_TYPE] = "multipart/form-data; boundary=" + BOUNDARY;
std::ostringstream body;
body << "--" << BOUNDARY << "\r\n"
<< "Content-Disposition: form-data; name=\"request\"\r\n\r\n"
<< "[{"
<< "\"method\":\"mediaItems.create\","
<< "\"params\": {"
<< "\"userId\":[\"@me\"],"
<< "\"groupId\":\"@self\","
<< "\"mediaItem\": {"
<< "\"mimeType\":\"image/jpeg\","
<< "\"type\":\"image\","
<< "\"url\":\"@field:image1\""
<< "}"
<< "},"
<< "\"id\":\"newMediaItem\""
<< "}]"
<< "--" << BOUNDARY << "\r\n"
<< "Content-Disposition: form-data; name=\"image1\"\r\n\r\n";
// Insert the image data.
// *FIX: Treating this as a string will probably screw it up ...
U8* image_data = mImage->getData();
for (S32 i = 0; i < mImage->getDataSize(); ++i)
{
body << image_data[i];
}
body << "\r\n--" << BOUNDARY << "--\r\n";
// postRaw() takes ownership of the buffer and releases it later.
size_t size = body.str().size();
U8 *data = new U8[size];
memcpy(data, body.str().data(), size);
// Send request, successful upload will trigger posting metadata.
LLHTTPClient::postRaw(upload_url, data, size, new LLWebSharingUploadResponder(), headers);
}
bool LLWebSharing::validateConfig()
{
// Check the OpenID Cookie has been set.
if (mOpenIDCookie.empty())
{
mEnabled = false;
return mEnabled;
}
if (!mConfig.isMap())
{
mEnabled = false;
return mEnabled;
}
// Template to match the received config against.
LLSD required(LLSD::emptyMap());
required["gadgetSpecUrl"] = "";
required["loginTokenUrl"] = "";
required["openIdAuthUrl"] = "";
required["photoPageUrlTemplate"] = "";
required["openSocialRpcUrlTemplate"] = "";
required["securityTokenUrl"] = "";
required["tokenBasedLoginUrlTemplate"] = "";
required["viewerIdUrl"] = "";
std::string mismatch(llsd_matches(required, mConfig));
if (!mismatch.empty())
{
LL_WARNS("WebSharing") << "Malformed config data response: " << mismatch << LL_ENDL;
mEnabled = false;
return mEnabled;
}
mEnabled = true;
return mEnabled;
}
// static
bool LLWebSharing::securityTokenIsValid(LLSD& token)
{
return (token.has("st") &&
token.has("expires") &&
(token["st"].asString() != "") &&
(token["expires"].asDate() > LLDate::now()));
}
///////////////////////////////////////////////////////////////////////////////
//
LLUriTemplate::LLUriTemplate(const std::string& uri_template)
:
mTemplate(uri_template)
{
}
std::string LLUriTemplate::buildURI(const LLSD& vars)
{
// *TODO: Separate parsing the template from building the URI.
// Parsing only needs to happen on construction/assignnment.
static const std::string VAR_NAME_REGEX("[[:alpha:]][[:alnum:]\\._-]*");
// Capture var name with and without surrounding {}
static const std::string VAR_REGEX("\\{(" + VAR_NAME_REGEX + ")\\}");
// Capture delimiter and comma separated list of var names.
static const std::string JOIN_REGEX("\\{-join\\|(&)\\|(" + VAR_NAME_REGEX + "(?:," + VAR_NAME_REGEX + ")*)\\}");
std::string uri = mTemplate;
boost::smatch results;
// Validate and expand join operators : {-join|&|var1,var2,...}
boost::regex join_regex(JOIN_REGEX);
while (boost::regex_search(uri, results, join_regex))
{
// Extract the list of var names from the results.
std::string delim = results[1].str();
std::string var_list = results[2].str();
// Expand the list of vars into a query string with their values
std::string query = expandJoin(delim, var_list, vars);
// Substitute the query string into the template.
uri = boost::regex_replace(uri, join_regex, query, boost::format_first_only);
}
// Expand vars : {var1}
boost::regex var_regex(VAR_REGEX);
std::set<std::string> var_names;
std::string::const_iterator start = uri.begin();
std::string::const_iterator end = uri.end();
// Extract the var names used.
while (boost::regex_search(start, end, results, var_regex))
{
var_names.insert(results[1].str());
start = results[0].second;
}
// Replace each var with its value.
for (std::set<std::string>::const_iterator it = var_names.begin(); it != var_names.end(); ++it)
{
std::string var = *it;
if (vars.has(var))
{
boost::replace_all(uri, "{" + var + "}", vars[var].asString());
}
}
return uri;
}
std::string LLUriTemplate::expandJoin(const std::string& delim, const std::string& var_list, const LLSD& vars)
{
std::ostringstream query;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(",");
tokenizer var_names(var_list, sep);
tokenizer::const_iterator it = var_names.begin();
// First var does not need a delimiter
if (it != var_names.end())
{
const std::string& name = *it;
if (vars.has(name))
{
// URL encode the value before appending the name=value pair.
query << name << "=" << escapeURL(vars[name].asString());
}
}
for (++it; it != var_names.end(); ++it)
{
const std::string& name = *it;
if (vars.has(name))
{
// URL encode the value before appending the name=value pair.
query << delim << name << "=" << escapeURL(vars[name].asString());
}
}
return query.str();
}
// static
std::string LLUriTemplate::escapeURL(const std::string& unescaped)
{
char* escaped = curl_escape(unescaped.c_str(), unescaped.size());
std::string result = escaped;
curl_free(escaped);
return result;
}
|