FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
rstudio/src/cpp/session/SessionHttpMethods.cpp at master · pearsonca/rstudio · GitHub
pearsonca
/
rstudio
Public
forked from
rstudio/rstudio
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
rstudio
/
src
/
cpp
/
session
/
SessionHttpMethods.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
848 lines (729 loc) · 29.6 KB
Breadcrumbs
rstudio
/
src
/
cpp
/
session
/
SessionHttpMethods.cpp
Copy path
File metadata and controls
848 lines (729 loc) · 29.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* SessionHttpMethods.hpp
*
* Copyright (C) 2009-19 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* 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
"
SessionHttpMethods.hpp
"
#
include
"
SessionConsoleInput.hpp
"
#
include
"
SessionMainProcess.hpp
"
#
include
"
SessionSuspend.hpp
"
#
include
"
SessionClientInit.hpp
"
#
include
"
SessionInit.hpp
"
#
include
"
SessionUriHandlers.hpp
"
#
include
"
SessionDirs.hpp
"
#
include
"
SessionRpc.hpp
"
#
include
"
http/SessionTcpIpHttpConnectionListener.hpp
"
#
include
"
session-config.h
"
#
include
<
boost/algorithm/string.hpp
>
#
include
<
core/gwt/GwtLogHandler.hpp
>
#
include
<
core/gwt/GwtFileHandler.hpp
>
#
include
<
shared_core/json/Json.hpp
>
#
include
<
core/json/JsonRpc.hpp
>
#
include
<
core/system/Crypto.hpp
>
#
include
<
core/text/TemplateFilter.hpp
>
#
include
<
core/http/CSRFToken.hpp
>
#
include
<
r/RExec.hpp
>
#
include
<
r/session/RSession.hpp
>
#
include
<
r/session/REventLoop.hpp
>
#
include
<
session/RVersionSettings.hpp
>
#
include
<
session/SessionHttpConnection.hpp
>
#
include
<
session/SessionHttpConnectionListener.hpp
>
#
include
<
session/SessionModuleContext.hpp
>
#
include
<
session/SessionOptions.hpp
>
#
include
<
session/SessionPersistentState.hpp
>
#
include
<
session/SessionScopes.hpp
>
#
include
<
session/projects/SessionProjects.hpp
>
#
ifdef
RSTUDIO_SERVER
#
include
<
server_core/sessions/SessionSignature.hpp
>
#
endif
using
namespace
rstudio
::core
;
namespace
rstudio
{
namespace
session
{
namespace
{
core::http::UriHandlerFunction s_defaultUriHandler;
//
version of the executable -- this is the legacy version designator. we
//
set it to double max so that it always invalidates legacy clients
double
s_version = std::numeric_limits<
double
>::max();
//
names of waitForMethod handlers (used to screen out of bkgnd processing)
std::vector<std::string> s_waitForMethodNames;
//
url for next session
std::string s_nextSessionUrl;
boost::posix_time::ptime
timeoutTimeFromNow
()
{
int
timeoutMinutes =
options
().
timeoutMinutes
();
if
(timeoutMinutes >
0
)
{
return
boost::posix_time::second_clock::universal_time
() +
boost::posix_time::minutes
(
options
().
timeoutMinutes
());
}
else
{
return
boost::posix_time::ptime
(boost::posix_time::not_a_date_time);
}
}
void
processEvents
()
{
//
execute safely since this can call arbitrary R code (and
//
(can also cause jump_to_top if an interrupt is pending)
Error error =
rstudio::r::exec::executeSafely
(
rstudio::r::session::event_loop::processEvents);
if
(error)
LOG_ERROR
(error);
}
bool
parseAndValidateJsonRpcConnection
(
boost::shared_ptr<HttpConnection> ptrConnection,
json::JsonRpcRequest* pJsonRpcRequest)
{
//
attempt to parse the request into a json-rpc request
Error error =
json::parseJsonRpcRequest
(ptrConnection->
request
().
body
(),
pJsonRpcRequest);
if
(error)
{
ptrConnection->
sendJsonRpcError
(error);
return
false
;
}
//
check for valid CSRF headers in server mode
if
(
options
().
programMode
() ==
kSessionProgramModeServer
&&
!
core::http::validateCSRFHeaders
(ptrConnection->
request
()))
{
ptrConnection->
sendJsonRpcError
(
Error
(json::errc::Unauthorized,
ERROR_LOCATION
));
return
false
;
}
//
check for invalid client id
if
(pJsonRpcRequest->
clientId
!=
persistentState
().
activeClientId
())
{
Error
error
(json::errc::InvalidClientId,
ERROR_LOCATION
);
ptrConnection->
sendJsonRpcError
(error);
return
false
;
}
//
check for legacy client version (need to invalidate any client using
//
the old version field)
if
( (pJsonRpcRequest->
version
>
0
) &&
(s_version > pJsonRpcRequest->
version
) )
{
Error
error
(json::errc::InvalidClientVersion,
ERROR_LOCATION
);
ptrConnection->
sendJsonRpcError
(error);
return
false
;
}
//
check for client version
if
(!pJsonRpcRequest->
clientVersion
.
empty
() &&
http_methods::clientVersion
() != pJsonRpcRequest->
clientVersion
)
{
Error
error
(json::errc::InvalidClientVersion,
ERROR_LOCATION
);
ptrConnection->
sendJsonRpcError
(error);
return
false
;
}
//
got through all of the validation, return true
return
true
;
}
void
endHandleConnection
(boost::shared_ptr<HttpConnection> ptrConnection,
http_methods::ConnectionType connectionType,
core::http::Response* pResponse)
{
ptrConnection->
sendResponse
(*pResponse);
if
(!
console_input::executing
())
module_context::events
().
onDetectChanges
(module_context::ChangeSourceURI);
}
bool
isMethod
(
const
std::string& uri,
const
std::string& method)
{
return
boost::algorithm::ends_with
(uri, method);
}
bool
isMethod
(boost::shared_ptr<HttpConnection> ptrConnection,
const
std::string& method)
{
return
isMethod
(ptrConnection->
request
().
uri
(), method);
}
Error
startHttpConnectionListener
()
{
initializeHttpConnectionListener
();
Error error =
httpConnectionListener
().
start
();
if
(error)
return
error;
if
(
options
().
standalone
())
{
//
log the endpoint to which we have bound to so other services can discover us
TcpIpHttpConnectionListener& listener =
static_cast
<TcpIpHttpConnectionListener&>(
httpConnectionListener
());
boost::asio::ip::tcp::endpoint endpoint = listener.
getLocalEndpoint
();
std::cout <<
"
Listener bound to address
"
<< endpoint.
address
().
to_string
()
<<
"
port
"
<< endpoint.
port
() << std::endl;
//
set the standalone port so rpostback and others know how to
//
connect back into the session process
core::system::setenv
(
kRSessionStandalonePortNumber
,
safe_convert::numberToString
(endpoint.
port
()));
}
return
Success
();
}
bool
isTimedOut
(
const
boost::posix_time::ptime& timeoutTime)
{
using
namespace
boost
::posix_time
;
//
never time out in desktop mode
if
(
options
().
programMode
() ==
kSessionProgramModeDesktop
)
return
false
;
//
check for an client disconnection based timeout
int
disconnectedTimeoutMinutes =
options
().
disconnectedTimeoutMinutes
();
if
(disconnectedTimeoutMinutes >
0
)
{
ptime lastEventConnection =
httpConnectionListener
().
eventsConnectionQueue
().
lastConnectionTime
();
if
(!lastEventConnection.
is_not_a_date_time
())
{
if
( (lastEventConnection +
minutes
(disconnectedTimeoutMinutes)
<
second_clock::universal_time
()) )
{
return
true
;
}
}
}
//
check for a foreground inactivity based timeout
if
(timeoutTime.
is_not_a_date_time
())
return
false
;
else
return
second_clock::universal_time
() > timeoutTime;
}
bool
isWaitForMethodUri
(
const
std::string& uri)
{
for
(
const
std::string& methodName : s_waitForMethodNames)
{
if
(
isMethod
(uri, methodName))
return
true
;
}
return
false
;
}
bool
isJsonRpcRequest
(boost::shared_ptr<HttpConnection> ptrConnection)
{
return
boost::algorithm::starts_with
(ptrConnection->
request
().
uri
(),
"
/rpc/
"
);
}
void
polledEventHandler
()
{
//
if R is getting called after a fork this is likely multicore or
//
some other parallel computing package that uses fork. in this
//
case be defensive by shutting down as many things as we can
//
which might cause mischief in the child process
if
(
main_process::wasForked
())
{
//
no more polled events
rstudio::r::session::event_loop::permanentlyDisablePolledEventHandler
();
//
done
return
;
}
//
static lastPerformed value used for throttling
using
namespace
boost
::posix_time
;
static
ptime s_lastPerformed;
if
(s_lastPerformed.
is_not_a_date_time
())
s_lastPerformed =
microsec_clock::universal_time
();
//
throttle to no more than once every 50ms
static
time_duration s_intervalMs =
milliseconds
(
50
);
if
(
microsec_clock::universal_time
() <= (s_lastPerformed + s_intervalMs))
return
;
//
notify modules
module_context::onBackgroundProcessing
(
false
);
//
set last performed (should be set after calling onBackgroundProcessing so
//
that long running background processing handlers can't overflow the 50ms
//
interval between background processing invocations)
s_lastPerformed =
microsec_clock::universal_time
();
//
check for a pending connections only while R is processing
//
(otherwise we'll handle them directly in waitForMethod)
if
(
console_input::executing
())
{
//
check the uri of the next connection
std::string nextConnectionUri =
httpConnectionListener
().
mainConnectionQueue
().
peekNextConnectionUri
();
//
if the uri is empty or if it one of our special waitForMethod calls
//
then bails so that the waitForMethod logic can handle it
if
(nextConnectionUri.
empty
() ||
isWaitForMethodUri
(nextConnectionUri))
return
;
//
attempt to deque a connection and handle it. for now we just handle
//
a single connection at a time (we'll be called back again if processing
//
continues)
boost::shared_ptr<HttpConnection> ptrConnection =
httpConnectionListener
().
mainConnectionQueue
().
dequeConnection
();
if
(ptrConnection)
{
if
(
isMethod
(ptrConnection,
kClientInit
) )
{
//
client_init means the user is attempting to reload the browser
//
in the middle of a computation. process client_init and post
//
a busy event as our initFunction
using
namespace
session
::module_context
;
ClientEvent
busyEvent
(client_events::
kBusy
,
true
);
client_init::handleClientInit
(
boost::bind
(enqueClientEvent, busyEvent), ptrConnection);
}
else
{
handleConnection
(ptrConnection, http_methods::BackgroundConnection);
}
}
}
}
bool
registeredWaitForMethod
(
const
std::string& method,
const
ClientEvent& event,
core::json::JsonRpcRequest* pRequest)
{
//
enque the event which notifies the client we want input
module_context::enqueClientEvent
(event);
//
wait for method
return
http_methods::waitForMethod
(method,
boost::bind
(http_methods::waitForMethodInitFunction,
event),
suspend::disallowSuspend,
pRequest);
}
bool
verifyRequestSignature
(
const
core::http::Request& request)
{
#
ifndef
RSTUDIO_SERVER
//
signatures only supported in server mode - requires a dependency
//
on server_core, which is only available to server platforms
return
true
;
#
else
//
only verify signatures if we are in standalone mode and
//
we are explicitly configured to verify signatures
if
(!
options
().
verifySignatures
() || !
options
().
standalone
())
return
true
;
//
determine which signing key pair to use
//
we use an automatically generated key for postback requests
//
(since we do not have access to the private key of rserver)
std::string signingKey =
options
().
signingKey
();
if
(request.
headerValue
(
"
X-Session-Postback
"
) ==
"
1
"
)
signingKey =
options
().
sessionRsaPublicKey
();
//
ensure specified signature is valid
//
note: we do not validate the signing username if we are running in a root container
Error error = !
core::system::effectiveUserIsRoot
() ?
server_core::sessions::verifyRequestSignature
(signingKey,
core::system::username
(), request) :
server_core::sessions::verifyRequestSignature
(signingKey, request);
if
(error)
{
LOG_ERROR
(error);
return
false
;
}
return
true
;
#
endif
}
}
//
anonymous namespace
namespace
module_context
{
module_context::WaitForMethodFunction
registerWaitForMethod
(
const
std::string& methodName)
{
s_waitForMethodNames.
push_back
(methodName);
return
boost::bind
(registeredWaitForMethod, methodName, _2, _1);
}
}
//
namespace module_context
namespace
http_methods
{
//
client version -- this is determined by the git revision hash. the client
//
and the server can diverge if a new version of the server was installed
//
underneath a previously rendered client. if versions diverge then a reload
//
of the client is forced
std::string
clientVersion
()
{
//
never return a version in desktop mode
if
(
options
().
programMode
() ==
kSessionProgramModeDesktop
)
return
std::string
();
//
never return a version in standalone mode
if
(
options
().
standalone
())
return
std::string
();
//
clientVersion is the git revision hash
return
RSTUDIO_GIT_REVISION_HASH
;
}
void
waitForMethodInitFunction
(
const
ClientEvent& initEvent)
{
module_context::enqueClientEvent
(initEvent);
if
(
console_input::executing
())
{
ClientEvent
busyEvent
(client_events::
kBusy
,
true
);
module_context::enqueClientEvent
(busyEvent);
}
else
{
console_input::reissueLastConsolePrompt
();
}
}
//
wait for the specified method. will either:
//
- return true and the method request in pRequest
//
- return false indicating failure (e.g. called after fork in child)
//
- suspend or quit the process
//
exit the process as a result of suspend or quit)
bool
waitForMethod
(
const
std::string& method,
const
boost::function<
void
()>& initFunction,
const
boost::function<bool()>& allowSuspend,
core::json::JsonRpcRequest* pRequest)
{
if
(
main_process::wasForked
())
{
LOG_ERROR_MESSAGE
(
"
Waiting for method
"
+ method +
"
after fork
"
);
return
false
;
}
//
establish timeouts
boost::posix_time::ptime timeoutTime =
timeoutTimeFromNow
();
boost::posix_time::time_duration connectionQueueTimeout =
boost::posix_time::milliseconds
(
50
);
//
wait until we get the method we are looking for
while
(
true
)
{
//
suspend if necessary (does not return if a suspend occurs)
suspend::suspendIfRequested
(allowSuspend);
//
check for timeout
if
(
isTimedOut
(timeoutTime) )
{
if
(
allowSuspend
())
{
//
note that we timed out
suspend::setSuspendedFromTimeout
(
true
);
if
(!
options
().
timeoutSuspend
())
{
//
configuration dictates that we should quit the
//
session instead of suspending when timeout occurs
//
//
the conditions for the quit must be the same as those
//
for a regular suspend
rstudio::r::session::quit
(
false
,
EXIT_SUCCESS
);
//
does not return
return
false
;
}
//
attempt to suspend (does not return if it succeeds)
if
(!
suspend::suspendSession
(
false
))
{
//
reset timeout flag
suspend::setSuspendedFromTimeout
(
false
);
//
if it fails then reset the timeout timer so we don't keep
//
hammering away on the failure case
timeoutTime =
timeoutTimeFromNow
();
}
}
}
//
if we have at least one async process running then this counts
//
as "activity" and resets the timeout timer
if
(
main_process::haveActiveChildren
())
timeoutTime =
timeoutTimeFromNow
();
//
look for a connection (waiting for the specified interval)
boost::shared_ptr<HttpConnection> ptrConnection =
httpConnectionListener
().
mainConnectionQueue
().
dequeConnection
(
connectionQueueTimeout);
//
perform background processing (true for isIdle)
module_context::onBackgroundProcessing
(
true
);
//
process pending events
processEvents
();
if
(ptrConnection)
{
//
ensure request signature is valid
if
(!
verifyRequestSignature
(ptrConnection->
request
()))
{
LOG_ERROR_MESSAGE
(
"
Invalid signature for request URI
"
+ ptrConnection->
request
().
uri
());
core::http::Response response;
response.
setError
(http::status::Unauthorized,
"
Invalid message signature
"
);
ptrConnection->
sendResponse
(response);
continue
;
}
//
check for client_init
if
(
isMethod
(ptrConnection,
kClientInit
) )
{
client_init::handleClientInit
(initFunction, ptrConnection);
}
//
check for the method we are waiting on
else
if
(
isMethod
(ptrConnection, method) )
{
//
parse and validate request then proceed
if
(
parseAndValidateJsonRpcConnection
(ptrConnection, pRequest))
{
//
respond to the method
ptrConnection->
sendJsonRpcResponse
();
//
ensure initialized
init::ensureSessionInitialized
();
break
;
//
got the method, we are out of here!
}
}
//
another connection type, dispatch it
else
{
handleConnection
(ptrConnection, ForegroundConnection);
}
//
since we got a connection we can reset the timeout time
timeoutTime =
timeoutTimeFromNow
();
//
after we've processed at least one waitForMethod it is now safe to
//
initialize the polledEventHandler (which is used to maintain rsession
//
responsiveness even when R is executing code received at the console).
//
we defer this to make sure that the FIRST request is always handled
//
by the logic above. if we didn't do this then client_init or
//
console_input (often the first request) could go directly to
//
handleConnection which wouldn't know what to do with them
if
(!
rstudio::r::session::event_loop::polledEventHandlerInitialized
())
rstudio::r::session::event_loop::initializePolledEventHandler
(
polledEventHandler);
}
}
//
satisfied the request
return
true
;
}
//
wait for the specified method (will either return the method or
//
exit the process as a result of suspend or quit)
bool
waitForMethod
(
const
std::string& method,
const
ClientEvent& initEvent,
const
boost::function<
bool
()>& allowSuspend,
core::json::JsonRpcRequest* pRequest)
{
return
waitForMethod
(method,
boost::bind
(module_context::enqueClientEvent,
initEvent),
allowSuspend,
pRequest);
}
void
handleConnection
(boost::shared_ptr<HttpConnection> ptrConnection,
ConnectionType connectionType)
{
//
check for a uri handler registered by a module
const
core::http::Request& request = ptrConnection->
request
();
std::string uri = request.
uri
();
boost::optional<core::http::UriAsyncHandlerFunctionVariant> uriHandler =
uri_handlers::handlers
().
handlerFor
(uri);
if
(uriHandler)
//
uri handler
{
core::http::visitHandler
(uriHandler.
get
(),
request,
boost::bind
(endHandleConnection,
ptrConnection,
connectionType,
_1));
//
r code may execute - ensure session is initialized
init::ensureSessionInitialized
();
}
else
if
(
isJsonRpcRequest
(ptrConnection))
//
check for json-rpc
{
//
r code may execute - ensure session is initialized
init::ensureSessionInitialized
();
//
attempt to parse & validate
json::JsonRpcRequest jsonRpcRequest;
if
(
parseAndValidateJsonRpcConnection
(ptrConnection, &jsonRpcRequest))
{
//
quit_session: exit process
if
(jsonRpcRequest.
method
==
kQuitSession
)
{
#
ifdef
_WIN32
//
if we are on windows then we can't quit while the browser
//
context is active
if
(
rstudio::r::session::browserContextActive
())
{
module_context::consoleWriteError
(
"
Error: unable to quit when browser is active
\n
"
);
json::JsonRpcResponse response;
response.
setResult
(
false
);
ptrConnection->
sendJsonRpcResponse
(response);
return
;
}
#
endif
//
see whether we should save the workspace
bool
saveWorkspace =
true
;
std::string switchToProject, hostPageUrl;
json::Value switchToVersionJson;
Error error =
json::readParams
(jsonRpcRequest.
params
,
&saveWorkspace,
&switchToProject,
&switchToVersionJson,
&hostPageUrl) ;
if
(error)
LOG_ERROR
(error);
//
note switch to project
if
(!switchToProject.
empty
())
{
//
if we don't have a project file then create it (can
//
occur when e.g. opening a project from a directory for
//
which we don't yet have a .Rproj file)
if
(switchToProject !=
kProjectNone
)
{
FilePath projFile =
module_context::resolveAliasedPath
(switchToProject);
if
(projFile.
getParent
().
exists
() && !projFile.
exists
())
{
Error error =
r_util::writeProjectFile
(
projFile,
projects::ProjectContext::buildDefaults
(),
projects::ProjectContext::defaultConfig
());
if
(error)
LOG_ERROR
(error);
}
}
//
update project and working dir
using
namespace
module_context
;
if
(switchToProject ==
kProjectNone
)
{
//
update the project and working dir
activeSession
().
setProject
(
kProjectNone
);
activeSession
().
setWorkingDir
(
createAliasedPath
(
dirs::getDefaultWorkingDirectory
()));
}
else
{
FilePath projFile =
module_context::resolveAliasedPath
(switchToProject);
std::string projDir =
createAliasedPath
(projFile.
getParent
());
activeSession
().
setProject
(projDir);
activeSession
().
setWorkingDir
(projDir);
}
if
(
options
().
switchProjectsWithUrl
())
{
r_util::SessionScope scope;
if
(switchToProject ==
kProjectNone
)
{
scope =
r_util::SessionScope::projectNone
(
options
().
sessionScope
().
id
());
}
else
{
//
extract the directory (aliased)
using
namespace
module_context
;
FilePath projFile =
module_context::resolveAliasedPath
(switchToProject);
std::string projDir =
createAliasedPath
(projFile.
getParent
());
scope =
r_util::SessionScope::fromProject
(
projDir,
options
().
sessionScope
().
id
(),
filePathToProjectId
(
options
().
userScratchPath
(),
FilePath
(
options
().
getOverlayOption
(
kSessionSharedStoragePath
))));
}
//
set next session url
s_nextSessionUrl =
r_util::createSessionUrl
(hostPageUrl,
scope);
}
else
{
projects::ProjectsSettings
(
options
().
userScratchPath
()).
setSwitchToProjectPath
(switchToProject);
}
//
note switch to R version if requested
if
(json::isType<json::Object>(switchToVersionJson))
{
using
namespace
module_context
;
std::string version, rHome, label;
Error error =
json::readObject
(
switchToVersionJson.
getObject
(),
"
version
"
, &version,
"
r_home
"
, &rHome,
"
label
"
, &label);
if
(!error)
{
//
set version for active session
activeSession
().
setRVersion
(version, rHome, label);
//
if we had a project directory as well then
//
set it's version (this is necessary because
//
project versions override session versions)
if
(switchToProject !=
kProjectNone
)
{
FilePath projFile =
resolveAliasedPath
(switchToProject);
std::string projDir =
createAliasedPath
(projFile.
getParent
());
RVersionSettings
verSettings
(
options
().
userScratchPath
(),
FilePath
(
options
().
getOverlayOption
(
kSessionSharedStoragePath
)));
verSettings.
setProjectLastRVersion
(projDir,
module_context::sharedProjectScratchPath
(),
version,
rHome,
label);
}
}
else
LOG_ERROR
(error);
}
}
//
exit status
int
status = switchToProject.
empty
() ?
EXIT_SUCCESS
:
EX_CONTINUE
;
//
acknowledge request & quit session
json::JsonRpcResponse response;
response.
setResult
(
true
);
ptrConnection->
sendJsonRpcResponse
(response);
rstudio::r::session::quit
(saveWorkspace, status);
//
does not return
}
else
if
(jsonRpcRequest.
method
==
kSuspendSession
)
{
//
check for force
bool
force =
true
;
Error error =
json::readParams
(jsonRpcRequest.
params
, &force);
if
(error)
LOG_ERROR
(error);
//
acknowledge request and set flags to suspend session
ptrConnection->
sendJsonRpcResponse
();
if
(force)
suspend::handleUSR2
(
0
);
else
suspend::handleUSR1
(
0
);
}
//
interrupt
else
if
( jsonRpcRequest.
method
==
kInterrupt
)
{
//
Discard any buffered input
console_input::clearConsoleInputBuffer
();
//
aknowledge request
ptrConnection->
sendJsonRpcResponse
();
//
only accept interrupts while R is processing input
if
(
console_input::executing
())
rstudio::r::exec::setInterruptsPending
(
true
);
}
//
other rpc method, handle it
else
{
jsonRpcRequest.
isBackgroundConnection
=
(connectionType == BackgroundConnection);
rpc::handleRpcRequest
(jsonRpcRequest, ptrConnection, connectionType);
}
}
}
else
if
(s_defaultUriHandler)
{
core::http::Response response;
s_defaultUriHandler
(request, &response);
ptrConnection->
sendResponse
(response);
}
else
{
core::http::Response response;
response.
setNotFoundError
(request);
ptrConnection->
sendResponse
(response);
}
}
WaitResult
startHttpConnectionListenerWithTimeout
()
{
Error error =
startHttpConnectionListener
();
//
When the rsession restarts, it may take a few ms for the port to become
//
available; therefore, retry connection, but only for address_in_use error
if
(!error)
return
WaitResult
(WaitSuccess,
Success
());
else
if
(error !=
boost::system::error_code
(boost::system::errc::address_in_use,
boost::system::generic_category
()))
return
WaitResult
(WaitError, error);
else
return
WaitResult
(WaitContinue, error);
}
void
registerGwtHandlers
()
{
//
alias options
session::Options& options =
session::options
();
//
establish logging handler
module_context::registerUriHandler
(
"
/log
"
,
boost::bind
(gwt::handleLogRequest, options.
userIdentity
(), _1, _2));
//
establish progress handler
FilePath
wwwPath
(options.
wwwLocalPath
());
FilePath progressPagePath = wwwPath.
completePath
(
"
progress.htm
"
);
module_context::registerUriHandler
(
"
/progress
"
,
boost::bind
(text::handleTemplateRequest, progressPagePath, _1, _2));
//
initialize gwt symbol maps
gwt::initializeSymbolMaps
(options.
wwwSymbolMapsPath
());
//
declare program mode in JS init block (for GWT boot time access)
std::string initJs =
"
window.program_mode =
\"
"
+ options.
programMode
() +
"
\"
;
\n
"
;
//
set default handler
s_defaultUriHandler =
gwt::fileHandlerFunction
(options.
wwwLocalPath
(), options.
useSecureCookies
(),
"
/
"
,
http::UriFilterFunction
(), initJs);
}
std::string
nextSessionUrl
()
{
return
s_nextSessionUrl;
}
}
//
namespace http_methods
}
//
namespace session
}
//
namespace rstudio
Back
|
FazBrowse Home
|
New Git URL