-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
SessionHelp.cpp
880 lines (760 loc) · 25.4 KB
/
SessionHelp.cpp
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
/*
* SessionHelp.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionHelp.hpp"
#include <algorithm>
#include <boost/ref.hpp>
#include <boost/regex.hpp>
#include <boost/function.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/iostreams/filter/aggregate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/Log.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/URL.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <core/r_util/RPackageInfo.hpp>
#define R_INTERNAL_FUNCTIONS
#include <r/RInternal.hpp>
#include <r/RSexp.hpp>
#include <r/RExec.hpp>
#include <r/RFunctionHook.hpp>
#include <r/ROptions.hpp>
#include <r/RUtil.hpp>
#include <r/session/RSessionUtils.hpp>
#include <session/SessionModuleContext.hpp>
// protect R against windows TRUE/FALSE defines
#undef TRUE
#undef FALSE
using namespace core;
namespace session {
namespace modules {
namespace help {
namespace {
// save computed help url prefix for comparison in rHelpUrlHandler
std::string s_localIP;
std::string s_localPort;
const char * const kHelpLocation = "/help";
const char * const kCustomLocation = "/custom";
const char * const kSessionLocation = "/session";
const char * const kCustomHelprLocation = "/custom/helpr";
// flag indicating whether we should send headers to custom handlers
// (only do this for 2.13 or higher)
bool s_provideHeaders = false;
std::string localURL(const std::string& address)
{
return "http://" + address + ":" + s_localPort + "/";
}
bool isLocalURL(const std::string& url,
const std::string& scope,
std::string* pLocalURLPath)
{
// first look for local ip prefix
std::string urlPrefix = localURL(s_localIP);
size_t pos = url.find(urlPrefix + scope);
if (pos != std::string::npos)
{
*pLocalURLPath = url.substr(urlPrefix.length());
return true;
}
// next look for localhost
urlPrefix = localURL("localhost");
pos = url.find(urlPrefix + scope);
if (pos != std::string::npos)
{
*pLocalURLPath = url.substr(urlPrefix.length());
return true;
}
// none found
return false;
}
// replace the internal startHTTPD function (called from startDynamicHelp
// to run the http server). we simply record the ip/port info for future
// reference (comparision in rBrowseHelpUrlHandler)
SEXP startHTTPDHook(SEXP call, SEXP op, SEXP args, SEXP rho)
{
// startHTTPD(ip, port)
r::function_hook::checkArity(op, args, call);
try
{
// save ip and port
s_localIP = r::sexp::asString(CAR(args));
s_localPort = r::sexp::asString(CADR(args));
}
CATCH_UNEXPECTED_EXCEPTION
// return status 0L to indicate success
r::sexp::Protect rProtect;
return r::sexp::create(0, &rProtect);
}
// replace the internal stopHTTPD function
SEXP stopHTTPDHook(SEXP call, SEXP op, SEXP args, SEXP rho)
{
// stopHTTPD()
r::function_hook::checkArity(op, args, call);
return R_NilValue;
}
// hook the browseURL function to look for calls to the R internal http
// server. for custom URLs remap the address to remote and then fire
// the browse_url event. for help URLs fire the appropraite show_help event
bool handleLocalHttpUrl(const std::string& url)
{
// return false if the help url prefix hasn't been set yet
if (s_localPort.empty())
return false;
// check for helpr
std::string helprPath;
if (isLocalURL(url, "custom/helpr", &helprPath))
{
ClientEvent helpEvent(client_events::kShowHelp, helprPath);
module_context::enqueClientEvent(helpEvent);
return true;
}
// check for custom
std::string customPath;
if (isLocalURL(url, "custom", &customPath))
{
ClientEvent event = browseUrlEvent(customPath);
module_context::enqueClientEvent(event);
return true;
}
// check for session
std::string sessionPath;
if (isLocalURL(url, "session", &sessionPath))
{
ClientEvent event = browseUrlEvent(sessionPath);
module_context::enqueClientEvent(event);
return true;
}
// otherwise look for help (which would be all other localhost urls)
std::string helpPath;
if (isLocalURL(url, "", &helpPath))
{
helpPath = "help/" + helpPath;
ClientEvent helpEvent(client_events::kShowHelp, helpPath);
module_context::enqueClientEvent(helpEvent);
return true;
}
// wasn't a url of interest
return false;
}
// As of R 2.10 RShowDoc still uses the legacy file::// mechanism for
// displaying the manual. Redirect these to the appropriate help event
bool handleRShowDocFile(const core::FilePath& filePath)
{
boost::regex manualRegx(".*/lib/R/(doc/manual/[A-Za-z0-9_\\-]*\\.html)");
boost::smatch match;
if (regex_match(filePath.absolutePath(), match, manualRegx))
{
ClientEvent helpEvent(client_events::kShowHelp, match[1]);
module_context::enqueClientEvent(helpEvent);
return true;
}
else
{
return false;
}
}
// javascript callbacks to inject into page
const char * const kJsCallbacks =
"<script type=\"text/javascript\">\n"
"if (window.parent.helpNavigated)\n"
" window.parent.helpNavigated(document, window);\n"
"if (window.parent.helpKeydown)\n"
" window.onkeydown = function(e) {window.parent.helpKeydown(e);}\n"
"</script>\n";
class HelpContentsFilter : public boost::iostreams::aggregate_filter<char>
{
public:
typedef std::vector<char> Characters ;
HelpContentsFilter(const http::Request& request)
{
requestUri_ = request.uri();
}
void do_filter(const Characters& src, Characters& dest)
{
std::string baseUrl = http::URL::uncomplete(
requestUri_,
kHelpLocation);
// fixup hard-coded hrefs
Characters tempDest;
boost::algorithm::replace_all_copy(
std::back_inserter(tempDest),
boost::make_iterator_range(src.begin(), src.end()),
"href=\"/",
"href=\"" + baseUrl + "/");
// fixup hard-coded src=
boost::algorithm::replace_all_copy(
std::back_inserter(dest),
boost::make_iterator_range(tempDest.begin(), tempDest.end()),
"src=\"/",
"src=\"" + baseUrl + "/");
// append javascript callbacks
std::string js(kJsCallbacks);
std::copy(js.begin(), js.end(), std::back_inserter(dest));
}
private:
std::string requestUri_;
};
class CustomHelprContentsFilter
: public boost::iostreams::aggregate_filter<char>
{
void do_filter(const std::vector<char>& src, std::vector<char>& dest)
{
std::string js(kJsCallbacks);
std::copy(src.begin(), src.end(), std::back_inserter(dest));
std::copy(js.begin(), js.end(), std::back_inserter(dest));
}
};
template <typename Filter>
void setDynamicContentResponse(const std::string& content,
const http::Request& request,
const Filter& filter,
http::Response* pResponse)
{
// always attempt gzip
if (request.acceptsEncoding(http::kGzipEncoding))
pResponse->setContentEncoding(http::kGzipEncoding);
// force cache revalidation since this is dynamic content
pResponse->setCacheWithRevalidationHeaders();
// set as cacheable content (uses eTag/If-None-Match)
Error error = pResponse->setCacheableBody(content, request, filter);
if (error)
{
pResponse->setError(http::status::InternalServerError,
error.code().message());
}
}
void setDynamicContentResponse(const std::string& content,
const http::Request& request,
http::Response* pResponse)
{
http::NullOutputFilter nullFilter;
setDynamicContentResponse(content, request, nullFilter, pResponse);
}
template <typename Filter>
void handleHttpdResult(SEXP httpdSEXP,
const http::Request& request,
const Filter& htmlFilter,
http::Response* pResponse)
{
// NOTE: this function is a port of process_request in Rhttpd.c
// (that function is coupled to sending its results via the R http daemon,
// since we need to send the results via our daemon we need our own
// implemetnation of the function). The port was completed 10/28/2009 so
// diffs in this function subsequent to that should be accounted for
// defaults
int code = 200;
const char * const kTextHtml = "text/html";
std::string contentType(kTextHtml);
std::vector<std::string> headers;
// if present, second element is content type
if (LENGTH(httpdSEXP) > 1)
{
SEXP ctSEXP = VECTOR_ELT(httpdSEXP, 1);
if (TYPEOF(ctSEXP) == STRSXP && LENGTH(ctSEXP) > 0)
contentType = CHAR(STRING_ELT(ctSEXP, 0));
}
// if present, third element is headers vector
if (LENGTH(httpdSEXP) > 2)
{
SEXP headersSEXP = VECTOR_ELT(httpdSEXP, 2);
if (TYPEOF(headersSEXP) == STRSXP)
r::sexp::extract(headersSEXP, &headers);
}
// if present, fourth element is HTTP code
if (LENGTH(httpdSEXP) > 3)
{
code = r::sexp::asInteger(VECTOR_ELT(httpdSEXP, 3));
}
// setup response
pResponse->setStatusCode(code);
pResponse->setContentType(contentType);
// set headers
std::for_each(headers.begin(),
headers.end(),
boost::bind(&http::Response::setHeaderLine, pResponse, _1));
// check payload
SEXP payloadSEXP = VECTOR_ELT(httpdSEXP, 0);
// payload = string
if ((TYPEOF(payloadSEXP) == STRSXP || TYPEOF(payloadSEXP) == VECSXP) &&
LENGTH(payloadSEXP) > 0)
{
// get the names and the content string
SEXP namesSEXP = r::sexp::getNames(httpdSEXP);
std::string content;
if (TYPEOF(payloadSEXP) == STRSXP)
content = r::sexp::asString(STRING_ELT(payloadSEXP, 0));
else if (TYPEOF(payloadSEXP) == VECSXP)
content = r::sexp::asString(VECTOR_ELT(payloadSEXP, 0));
// check for special file returns
std::string fileName ;
if (TYPEOF(namesSEXP) == STRSXP && LENGTH(namesSEXP) > 0 &&
!std::strcmp(CHAR(STRING_ELT(namesSEXP, 0)), "file"))
{
fileName = content;
}
else if (LENGTH(payloadSEXP) > 1 && content == "*FILE*")
{
fileName = CHAR(STRING_ELT(payloadSEXP, 1));
}
// set the body
if (!fileName.empty()) // from file
{
// get file path
FilePath filePath(fileName);
// cache with revalidation
pResponse->setCacheWithRevalidationHeaders();
// read file contents
std::string contents;
Error error = readStringFromFile(filePath, &contents);
if (error)
{
pResponse->setError(error);
return;
}
// set body (apply filter to html)
if (pResponse->contentType() == kTextHtml)
{
pResponse->setCacheableBody(contents, request, htmlFilter);
}
else
{
pResponse->setCacheableBody(contents, request);
}
}
else // from dynamic content
{
if (code == http::status::Ok)
{
// set body (apply filter to html)
if (pResponse->contentType() == kTextHtml)
{
setDynamicContentResponse(content,
request,
htmlFilter,
pResponse);
}
else
{
setDynamicContentResponse(content, request, pResponse);
}
}
else // could be a redirect or something else, don't interfere
{
pResponse->setBodyUnencoded(content);
}
}
}
// payload = raw buffer
else if (TYPEOF(payloadSEXP) == RAWSXP)
{
std::string bytes((char*)(RAW(payloadSEXP)), LENGTH(payloadSEXP));
setDynamicContentResponse(bytes, request, pResponse);
}
// payload = unexpected type
else
{
pResponse->setError(http::status::InternalServerError,
"Invalid response from R");
}
}
// mirrors parse_query in Rhttpd.c
SEXP parseQuery(const http::Fields& fields, r::sexp::Protect* pProtect)
{
if (fields.empty())
return R_NilValue;
else
return r::sexp::create(fields, pProtect);
}
// mirrors parse_request_body in Rhttpd.c
SEXP parseRequestBody(const http::Request& request, r::sexp::Protect* pProtect)
{
if (request.body().empty())
{
return R_NilValue;
}
else if (request.contentType() == "application/x-www-form-urlencoded")
{
return parseQuery(request.formFields(), pProtect);
}
else
{
// body bytes
int contentLength = request.body().length();
SEXP bodySEXP;
pProtect->add(bodySEXP = Rf_allocVector(RAWSXP, contentLength));
if (contentLength > 0)
::memcpy(RAW(bodySEXP), request.body().c_str(), contentLength);
// content type
if (!request.contentType().empty())
{
Rf_setAttrib(bodySEXP,
Rf_install("content-type"),
Rf_mkString(request.contentType().c_str()));
}
return bodySEXP;
}
}
// mirrors collect_buffers in Rhttpd.c
SEXP headersBuffer(const http::Request& request, r::sexp::Protect* pProtect)
{
// get headers
std::string headers;
for(http::Headers::const_iterator it = request.headers().begin();
it != request.headers().end();
++it)
{
headers.append(it->name);
headers.append(": ");
headers.append(it->value);
headers.append("\n");
}
// allocate RAWSXP and copy headers to it
SEXP headersSEXP = Rf_allocVector(RAWSXP, headers.length());
pProtect->add(headersSEXP);
char* headersBuffer = (char*) RAW(headersSEXP);
headers.copy(headersBuffer, headers.length());
// return
return headersSEXP;
}
typedef boost::function<SEXP(const std::string&)> HandlerSource;
// NOTE: this emulates the calling portion of process_request in Rhttpd.c,
// to do this it uses low-level R functions and therefore must be wrapped
// in executeSafely
SEXP callHandler(const std::string& path,
const http::Request& request,
const HandlerSource& handlerSource,
r::sexp::Protect* pProtect)
{
// uri decode the path
std::string decodedPath = http::util::urlDecode(path, false);
// construct "try(httpd(url, query, body, headers), silent=TRUE)"
SEXP trueSEXP;
pProtect->add(trueSEXP = Rf_ScalarLogical(TRUE));
SEXP queryStringSEXP = parseQuery(request.queryParams(), pProtect);
SEXP requestBodySEXP = parseRequestBody(request, pProtect);
SEXP headersSEXP = headersBuffer(request, pProtect);
// only provide headers if appropriate
SEXP argsSEXP;
if (s_provideHeaders)
{
argsSEXP = Rf_list4(Rf_mkString(path.c_str()),
queryStringSEXP,
requestBodySEXP,
headersSEXP);
}
else
{
argsSEXP = Rf_list3(Rf_mkString(path.c_str()),
queryStringSEXP,
requestBodySEXP);
}
pProtect->add(argsSEXP);
// form the call expression
SEXP callSEXP;
pProtect->add(callSEXP = Rf_lang3(
Rf_install("try"),
Rf_lcons( (handlerSource(path)), argsSEXP),
trueSEXP));
SET_TAG(CDR(CDR(callSEXP)), Rf_install("silent"));
// execute and return
SEXP resultSEXP;
pProtect->add(resultSEXP = Rf_eval(callSEXP,
R_FindNamespace(Rf_mkString("tools"))));
return resultSEXP;
}
r_util::RPackageInfo packageInfoForRd(const FilePath& rdFilePath)
{
FilePath packageDir = rdFilePath.parent().parent();
FilePath descFilePath = packageDir.childPath("DESCRIPTION");
if (!descFilePath.exists())
return r_util::RPackageInfo();
r_util::RPackageInfo pkgInfo;
Error error = pkgInfo.read(packageDir);
if (error)
{
LOG_ERROR(error);
return r_util::RPackageInfo();
}
else
{
return pkgInfo;
}
}
template <typename Filter>
void handleRdPreviewRequest(const http::Request& request,
const Filter& filter,
http::Response* pResponse)
{
// read parmaeters
std::string file = request.queryParamValue("file");
if (file.empty())
{
pResponse->setError(http::status::BadRequest, "No file parameter");
return;
}
// ensure file exists
FilePath filePath = module_context::resolveAliasedPath(file);
if (!filePath.exists())
{
pResponse->setError(http::status::NotFound, request.uri());
return;
}
// build command used to convert to HTML
FilePath rHomeBinDir;
Error error = module_context::rBinDir(&rHomeBinDir);
if (error)
{
pResponse->setError(error);
return;
}
shell_utils::ShellCommand rCmd = module_context::rCmd(rHomeBinDir);
rCmd << "Rdconv";
rCmd << "--type=html";
r_util::RPackageInfo pkgInfo = packageInfoForRd(filePath);
if (!pkgInfo.empty())
rCmd << "--package=" + pkgInfo.name();
rCmd << filePath;
// run the converstion and return it
core::system::ProcessOptions options;
core::system::ProcessResult result;
error = core::system::runCommand(rCmd, options, &result);
if (error)
{
pResponse->setError(error);
}
else if (result.exitStatus != EXIT_SUCCESS)
{
pResponse->setError(http::status::InternalServerError, result.stdErr);
}
else
{
pResponse->setContentType("text/html");
pResponse->setNoCacheHeaders();
std::istringstream istr(result.stdOut);
pResponse->setBody(istr, filter);
}
}
template <typename Filter>
void handleHttpdRequest(const std::string& location,
const HandlerSource& handlerSource,
const http::Request& request,
const Filter& filter,
http::Response* pResponse)
{
// get the requested path
std::string path = http::util::pathAfterPrefix(request, location);
// server custom css file if necessary
if (boost::algorithm::ends_with(path, "/R.css"))
{
core::FilePath cssFile = options().rResourcesPath().childPath("R.css");
if (cssFile.exists())
{
pResponse->setFile(cssFile, request, filter);
return;
}
}
// handle Rd file preview
if (boost::algorithm::starts_with(path, "/preview"))
{
handleRdPreviewRequest(request, filter, pResponse);
return;
}
// markdown help is also a special case
if (path == "/doc/markdown_help.html")
{
core::FilePath helpFile = options().rResourcesPath().childPath(
"markdown_help.html");
if (helpFile.exists())
{
pResponse->setFile(helpFile, request, filter);
return;
}
}
// redirect from stock home to helpr home if it is active
if (path == "/doc/html/index.html")
{
bool helprActive = false;
Error error = r::exec::RFunction(".rs.helprIsActive").call(&helprActive);
if (error)
LOG_ERROR(error);
if (helprActive)
{
pResponse->setMovedTemporarily(request, "/custom/helpr/index.html");
return;
}
}
// evalute the handler
r::sexp::Protect rp;
SEXP httpdSEXP;
Error error = r::exec::executeSafely<SEXP>(
boost::bind(callHandler,
path,
boost::cref(request),
handlerSource,
&rp),
&httpdSEXP);
// error calling the function
if (error)
{
pResponse->setError(http::status::InternalServerError,
error.code().message());
}
// error returned explicitly by httpd
else if (TYPEOF(httpdSEXP) == STRSXP && LENGTH(httpdSEXP) > 0)
{
pResponse->setError(http::status::InternalServerError,
r::sexp::asString(httpdSEXP));
}
// content returned from httpd
else if (TYPEOF(httpdSEXP) == VECSXP && LENGTH(httpdSEXP) > 0)
{
handleHttpdResult(httpdSEXP, request, filter, pResponse);
}
// unexpected SEXP type returned from httpd
else
{
pResponse->setError(http::status::InternalServerError,
"Invalid response from R");
}
}
// this mirrors handler_for_path in Rhttpd.c. They cache the custom handlers
// env (not sure why). do the same for consistency
SEXP s_customHandlersEnv = NULL;
SEXP lookupCustomHandler(const std::string& uri)
{
// pick name of handler out of uri
boost::regex customRegx(".*/custom/([A-Za-z0-9_\\-]*).*");
boost::smatch match;
if (regex_match(uri, match, customRegx))
{
std::string handler = match[1];
// load .httpd.handlers.env
if (!s_customHandlersEnv)
{
s_customHandlersEnv = Rf_eval(Rf_install(".httpd.handlers.env"),
R_FindNamespace(Rf_mkString("tools")));
}
// we only proceed if .httpd.handlers.env really exists
if (TYPEOF(s_customHandlersEnv) == ENVSXP)
{
SEXP cl = Rf_findVarInFrame3(s_customHandlersEnv,
Rf_install(handler.c_str()),
TRUE);
if (cl != R_UnboundValue && TYPEOF(cl) == CLOSXP) // need a closure
return cl;
}
}
// if we didn't find a handler then return handler lookup error
return r::sexp::findFunction(".rs.handlerLookupError");
}
void handleCustomHelprRequest(const http::Request& request,
http::Response* pResponse)
{
handleHttpdRequest("",
lookupCustomHandler,
request,
CustomHelprContentsFilter(),
pResponse);
}
// .httpd.handlers.env
void handleCustomRequest(const http::Request& request,
http::Response* pResponse)
{
handleHttpdRequest("",
lookupCustomHandler,
request,
http::NullOutputFilter(),
pResponse);
}
// handle requests for session temporary directory
void handleSessionRequest(const http::Request& request, http::Response* pResponse)
{
// get the raw uri & strip its location prefix
std::string sessionPrefix = std::string(kSessionLocation) + "/";
std::string uri = request.uri();
if (!uri.compare(0, sessionPrefix.length(), sessionPrefix))
uri = uri.substr(sessionPrefix.length());
// ensure that this path does not contain ..
if (uri.find("..") != std::string::npos)
{
pResponse->setError(http::status::NotFound, uri + " not found");
return;
}
// form a path to the temporary file
FilePath tempFilePath = r::session::utils::tempDir().childPath(uri);
// return the file
pResponse->setCacheableFile(tempFilePath, request);
}
// the ShowHelp event will result in the Help pane requesting the specified
// help url. we handle this request directly by calling the R httpd function
// to dynamically form the correct http response
void handleHelpRequest(const http::Request& request, http::Response* pResponse)
{
handleHttpdRequest(kHelpLocation,
boost::bind(r::sexp::findFunction, "httpd", "tools"),
request,
HelpContentsFilter(request),
pResponse);
}
Error setHelpPort()
{
Options& options = session::options();
if (options.programMode() == kSessionProgramModeDesktop)
{
int port = boost::lexical_cast<int>(session::options().wwwPort());
return r::options::setOption("help.ports", port);
}
else
{
return Success();
}
}
} // anonymous namespace
Error initialize()
{
// determine whether we should provide headers to custom handlers
s_provideHeaders = r::util::hasRequiredVersion("2.13");
using boost::bind;
using core::http::UriHandler;
using namespace module_context;
using namespace r::function_hook ;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerReplaceHook, "startHTTPD", startHTTPDHook, (CCODE*)NULL))
(bind(registerReplaceHook, "stopHTTPD", stopHTTPDHook, (CCODE*)NULL))
(bind(registerRBrowseUrlHandler, handleLocalHttpUrl))
(bind(registerRBrowseFileHandler, handleRShowDocFile))
(bind(registerUriHandler, kHelpLocation, handleHelpRequest))
(bind(registerUriHandler, kCustomHelprLocation, handleCustomHelprRequest))
(bind(registerUriHandler, kCustomLocation, handleCustomRequest))
(bind(registerUriHandler, kSessionLocation, handleSessionRequest))
(bind(setHelpPort))
(bind(sourceModuleRFile, "SessionHelp.R"));
Error error = initBlock.execute();
if (error)
return error;
// set the helpr load hook
error = r::exec::RFunction(".rs.setHelprLoadHook").call();
if (error)
LOG_ERROR(error);
return Success();
}
} // namepsace help
} // namespace modules
} // namesapce session