-
Notifications
You must be signed in to change notification settings - Fork 373
/
Copy pathWebSession.C
3204 lines (2739 loc) · 91.3 KB
/
WebSession.C
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 Emweb bv, Herent, Belgium.
*
* See the LICENSE file for terms of use.
*/
#include "Wt/Utils.h"
#include "Wt/WApplication.h"
#include "Wt/WCombinedLocalizedStrings.h"
#include "Wt/WContainerWidget.h"
#include "Wt/WException.h"
#include "Wt/WFormWidget.h"
#ifndef WT_TARGET_JAVA
#include "Wt/WIOService.h"
#endif
#include "Wt/WResource.h"
#include "Wt/WServer.h"
#include "Wt/WTimerWidget.h"
#ifndef WT_TARGET_JAVA
#include "Wt/WWebSocketResource.h"
#endif // WT_TARGET_JAVA
#include "Wt/Http/Request.h"
#include "CgiParser.h"
#include "Configuration.h"
#include "DomElement.h"
#include "WebController.h"
#include "WebRequest.h"
#include "WebSession.h"
#include "WebSocketMessage.h"
#include "WebUtils.h"
#include <boost/algorithm/string.hpp>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#ifdef WT_WIN32
#include <process.h>
#endif
#ifdef WT_TARGET_JAVA
#define RETHROW(e) throw e
#else
#define RETHROW(e) throw
#endif
namespace {
#ifdef WT_TARGET_JAVA
static Wt::Http::UploadedFile* uf;
#endif
bool isAbsoluteUrl(const std::string& url) {
return url.find(":") != std::string::npos;
}
std::string host(const std::string& url) {
std::size_t pos = 0;
for (unsigned i = 0; i < 3; ++i) {
pos = url.find('/', pos);
if (pos == std::string::npos)
return url;
else
++pos;
}
return url.substr(0, pos - 1);
}
inline std::string str(const char *v) {
return v ? std::string(v) : std::string();
}
inline bool isEqual(const char *s1, const char *s2) {
#ifdef WT_TARGET_JAVA
if (s1 == 0) {
return s2 == 0;
} else {
return std::string(s1) == s2;
}
#else
return strcmp(s1, s2) == 0;
#endif
}
}
namespace Wt {
LOGGER("Wt");
#ifdef WT_TARGET_JAVA
boost::thread_specific_ptr<WebSession::Handler> WebSession::threadHandler_;
#else // WT_TARGET_JAVA
#ifdef WT_THREADED
static thread_local WebSession::Handler * threadHandler_ = nullptr;
#else // !WT_THREADED
static WebSession::Handler * threadHandler_ = nullptr;
#endif // WT_THREADED
#endif // WT_TARGET_JAVA
WebSession::WebSession(WebController *controller,
const std::string& sessionId,
EntryPointType type,
const std::string& favicon,
const WebRequest *request,
WEnvironment *env)
: type_(type),
favicon_(favicon),
state_(State::JustCreated),
sessionId_(sessionId),
sessionIdChanged_(false),
sessionIdCookieChanged_(false),
sessionIdInUrl_(false),
controller_(controller),
renderer_(*this),
asyncResponse_(nullptr),
webSocket_(nullptr),
bootStyleResponse_(nullptr),
canWriteWebSocket_(false),
webSocketConnected_(false),
pollRequestsIgnored_(0),
progressiveBoot_(false),
deferredRequest_(nullptr),
deferredResponse_(nullptr),
deferCount_(0),
#ifdef WT_TARGET_JAVA
recursiveEvent_(mutex_.newCondition()),
recursiveEventDone_(mutex_.newCondition()),
newRecursiveEvent_(nullptr),
updatesPendingEvent_(mutex_.newCondition()),
#else
newRecursiveEvent_(nullptr),
#endif
updatesPending_(false),
triggerUpdate_(false),
embeddedEnv_(this),
app_(nullptr),
debug_(controller_->configuration().debug()),
recursiveEventHandler_(nullptr)
{
env_ = env ? env : &embeddedEnv_;
// Update the URL scheme so we can set the session cookie correctly (with secure for https)
if (request)
env_->updateUrlScheme(*request);
/*
* Obtain the applicationName_ as soon as possible for log().
*/
if (request)
applicationUrl_ = request->fullEntryPointPath();
else
applicationUrl_ = "/";
deploymentPath_ = applicationUrl_;
std::string::size_type slashpos = deploymentPath_.rfind('/');
if (slashpos != std::string::npos) {
basePath_ = deploymentPath_.substr(0, slashpos + 1);
applicationName_ = deploymentPath_.substr(slashpos + 1);
} else { // ?
basePath_ = "";
applicationName_ = applicationUrl_;
}
#ifndef WT_TARGET_JAVA
LOG_INFO("session created (#sessions = " <<
(controller_->sessionCount() + 1) << ")");
expire_ = Time() + 60*1000;
#endif // WT_TARGET_JAVA
if (controller_->configuration().sessionIdCookie()) {
sessionIdCookie_ = WRandom::generateId();
sessionIdCookieChanged_ = true;
Http::Cookie cookie("Wt" + sessionIdCookie_, "1");
cookie.setSecure(env_->urlScheme() == "https");
#ifndef WT_TARGET_JAVA
cookie.setSameSite(Http::Cookie::SameSite::Strict);
#else
cookie.setHttpOnly(true);
#endif
renderer().setCookie(cookie);
}
}
void WebSession::setApplication(WApplication *app)
{
app_ = app;
}
void WebSession::deferRendering()
{
if (!deferredRequest_) {
Handler *handler = WebSession::Handler::instance();
deferredRequest_ = handler->request();
deferredResponse_ = handler->response();
handler->setRequest(nullptr, nullptr);
}
++deferCount_;
}
void WebSession::resumeRendering()
{
if (--deferCount_ == 0) {
Handler *handler = WebSession::Handler::instance();
handler->setRequest(deferredRequest_, deferredResponse_);
deferredRequest_ = nullptr;
deferredResponse_ = nullptr;
}
}
void WebSession::setTriggerUpdate(bool update)
{
triggerUpdate_ = update;
}
#ifndef WT_TARGET_JAVA
WLogger& WebSession::logInstance() const
{
return controller_->server()->logger();
}
WLogEntry WebSession::log(const std::string& type) const
{
if (controller_->server()->customLogger()) {
return WLogEntry(*controller_->server()->customLogger(), type);
}
WLogEntry e = controller_->server()->logger().entry(type);
#ifndef WT_TARGET_JAVA
e << WLogger::timestamp << WLogger::sep << getpid() << WLogger::sep
<< '[' << deploymentPath_ << ' ' << sessionId()
<< ']' << WLogger::sep << '[' << type << ']' << WLogger::sep;
#endif // WT_TARGET_JAVA
return e;
}
#endif // WT_TARGET_JAVA
WebSession::~WebSession()
{
/*
* From here on, we cannot create a shared_ptr to this session. Therefore,
* app_ uses a weak_ptr to this session for which lock() returns an empty
* shared pointer.
*/
state_ = State::Dead;
#ifndef WT_TARGET_JAVA
Handler handler(this);
if (app_)
app_->notify
(WEvent(WEvent::Impl
(&handler, std::bind(&WApplication::finalize, app_))));
delete app_;
app_ = nullptr;
#endif // WT_TARGET_JAVA
if (asyncResponse_) {
asyncResponse_->flush();
asyncResponse_ = nullptr;
}
if (webSocket_) {
webSocket_->flush();
webSocket_ = nullptr;
}
if (deferredResponse_) {
deferredResponse_->flush();
deferredResponse_ = nullptr;
}
#ifdef WT_BOOST_THREADS
updatesPendingEvent_.notify_one();
#endif // WT_BOOST_THREADS
flushBootStyleResponse();
controller_->configuration().registerSessionId(sessionId_, std::string());
controller_->sessionDeleted();
#ifndef WT_TARGET_JAVA
LOG_INFO("session destroyed (#sessions = " << controller_->sessionCount()
<< ")");
#endif // WT_TARGET_JAVA
}
#ifdef WT_TARGET_JAVA
void WebSession::destruct()
{
if (asyncResponse_) {
asyncResponse_->flush();
asyncResponse_ = nullptr;
}
if (deferredResponse_) {
deferredResponse_->flush();
deferredResponse_ = nullptr;
}
mutex_.lock();
updatesPendingEvent_.notify_one();
mutex_.unlock();
flushBootStyleResponse();
}
#endif // WT_TARGET_JAVA
std::string WebSession::docType() const
{
const bool xhtml = env_->contentType() == HtmlContentType::XHTML1;
if (xhtml)
/*
* This would be what we want, but it is too strict (does not
* validate iframe's and target attribute for links):
"\"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN\" "
"\"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd\">"
* so instead we use transitional xhtml -- it will fail to
* validate properly when we have svg !
*/
return "<!DOCTYPE html PUBLIC "
"\"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
else
return
#ifdef HTML4_DOCTYPE
"<!DOCTYPE html PUBLIC "
"\"-//W3C//DTD HTML 4.01 Transitional//EN\" "
"\"http://www.w3.org/TR/html4/loose.dtd\">";
#else
"<!DOCTYPE html>"; // HTML5 hoeray
#endif
}
void WebSession::setLoaded()
{
bool wasSuspended = state_ == State::Suspended;
setState(State::Loaded, controller_->configuration().sessionTimeout());
if (wasSuspended) {
if (env_->ajax() && controller_->configuration().reloadIsNewSession()) {
app_->doJavaScript(WT_CLASS ".history.removeSessionId()");
sessionIdInUrl_ = false;
}
app_->unsuspended().emit();
}
}
void WebSession::setExpectLoad()
{
if (controller_->configuration().ajaxPuzzle())
setState(State::ExpectLoad, controller_->configuration().bootstrapTimeout());
else
setLoaded();
}
void WebSession::setState(State state, int timeout)
{
#ifdef WT_THREADED
// this assertion is not true for when we are working from an attached
// thread: that thread does not have an associated handler, but its contract
// dictates that it should work on behalf of a thread that has the lock.
//assert(WebSession::Handler::instance()->haveLock());
#endif // WT_THREADED
if (state_ != State::Dead) {
state_ = state;
LOG_DEBUG("Setting to expire in " << timeout << "s");
#ifndef WT_TARGET_JAVA
if (controller_->configuration().sessionTimeout() != -1)
expire_ = Time() + timeout*1000;
#endif // WT_TARGET_JAVA
}
}
std::string WebSession::sessionQuery() const
{
std::string result ="?wtd=" + DomElement::urlEncodeS(sessionId_);
if (type() == EntryPointType::WidgetSet)
result += "&wtt=widgetset";
return result;
}
void WebSession::init(const WebRequest& request)
{
env_->init(request);
const std::string *hashE = request.getParameter("_");
absoluteBaseUrl_ = env_->urlScheme() + "://" + env_->hostName() + basePath_;
bool useAbsoluteUrls;
#ifndef WT_TARGET_JAVA
useAbsoluteUrls
= env_->server()->readConfigurationProperty("baseURL", absoluteBaseUrl_);
#else
std::string* absoluteBaseUrl
= app_->readConfigurationProperty("baseURL", absoluteBaseUrl_);
if (absoluteBaseUrl != &absoluteBaseUrl_) {
absoluteBaseUrl_ = *absoluteBaseUrl;
useAbsoluteUrls = true;
} else {
useAbsoluteUrls = false;
}
#endif
if (useAbsoluteUrls) {
std::string::size_type slashpos = absoluteBaseUrl_.rfind('/');
if (slashpos != std::string::npos
&& slashpos != absoluteBaseUrl_.length() - 1)
absoluteBaseUrl_ = absoluteBaseUrl_.substr(0, slashpos + 1);
slashpos = absoluteBaseUrl_.find("://");
if (slashpos != std::string::npos) {
slashpos = absoluteBaseUrl_.find("/", slashpos + 3);
if (slashpos != std::string::npos) {
deploymentPath_ = absoluteBaseUrl_.substr(slashpos) + applicationName_;
}
}
}
bookmarkUrl_ = applicationName_;
if (type() == EntryPointType::WidgetSet || useAbsoluteUrls) {
applicationUrl_ = absoluteBaseUrl_ + applicationName_;
bookmarkUrl_ = applicationUrl_;
}
auto extraPathInfo = request.extraPathInfo().to_string();
std::string path = extraPathInfo;
if (path.empty() && hashE)
path = *hashE;
env_->setInternalPath(path);
pagePathInfo_ = std::move(extraPathInfo);
// Cache document root
docRoot_ = getCgiValue("DOCUMENT_ROOT");
}
bool WebSession::useUglyInternalPaths() const
{
#ifndef WT_TARGET_JAVA
/*
* We need ugly ?_= internal paths if the server does not route
* /app/foo to an application deployed as /app/
*/
if (applicationName_.empty() && controller_->server()) {
Configuration& conf = controller_->configuration();
return conf.useSlashExceptionForInternalPaths();
} else
return false;
#else
return false;
#endif
}
std::string WebSession::bootstrapUrl(WT_MAYBE_UNUSED const WebResponse& response,
BootstrapOption option) const
{
switch (option) {
case BootstrapOption::KeepInternalPath: {
std::string url;
std::string internalPath
= app_ ? app_->internalPath() : env_->internalPath();
if (useUglyInternalPaths()) {
if (internalPath.length() > 1)
url = "?_=" + DomElement::urlEncodeS(internalPath, "#/");
if (isAbsoluteUrl(applicationUrl_))
url = applicationUrl_ + url;
} else {
if (!isAbsoluteUrl(applicationUrl_)) {
/*
* Java application servers use ";jsessionid=..." which generates
* URLs relative to the current directory, not current filename
* (unlike '?=...')
*
* Therefore we start with the current 'filename', this does no harm
* for C++ well behaving servers either.
*/
if (internalPath.length() > 1) {
std::string lastPart
= internalPath.substr(internalPath.rfind('/') + 1);
url = ""; /* lastPart; */
} else
url = applicationName_;
} else {
if (applicationName_.empty() && internalPath.length() > 1)
internalPath = internalPath.substr(1);
url = applicationUrl_ + internalPath;
}
}
return appendSessionQuery(url);
}
case BootstrapOption::ClearInternalPath: {
std::string url;
if (applicationName_.empty()) {
url = fixRelativeUrl(".");
url = url.substr(0, url.length() - 1);
} else
url = fixRelativeUrl(applicationName_);
return appendSessionQuery(url);
}
default:
assert(false);
}
return std::string();
}
std::string WebSession::fixRelativeUrl(const std::string& url) const
{
if (isAbsoluteUrl(url))
return url;
if (url.length() > 0 && url[0] == '#') {
if (!isAbsoluteUrl(applicationUrl_))
return url;
else
// we have <href base=...> which requires us to put the application
// name before a named anchor
return applicationName_ + url;
}
if (!isAbsoluteUrl(applicationUrl_)) {
if (!url.empty() && url[0] == '/')
return url;
else if (!env_->publicDeploymentPath_.empty()) {
std::string dp = env_->publicDeploymentPath_;
if (url.empty())
return dp;
else if (url[0] == '?')
return dp + url;
else {
std::size_t s = dp.rfind('/');
std::string parentDir = dp.substr(0, s + 1);
if (url[0] == '.' && (url.size() == 1 || url[1] == '?' || url[1] == '#' || url[1] == ';'))
return parentDir + url.substr(1);
else if (url.size() >= 2 && url[0] == '.' && url[1] == '/') {
// Note: deployment path is guaranteed to start with /
// WEnvironment checks this!
return parentDir + url.substr(2);
} else
return parentDir + url;
}
} else {
/*
* The public deployment path may lack if:
* - we are a widget set script, but then we should have absolute
* applicationUrl and internal paths are not really going to work
* - we are a plain HTML session. but then we are not hashing internal
* paths, so first condition should never be met
*/
if (env_->internalPathUsingFragments())
return url;
else {
std::string rel = "";
std::string pi = pagePathInfo_;
for (unsigned i = 0; i < pi.length(); ++i) {
if (pi[i] == '/')
rel += "../";
}
if (url.empty())
return rel + applicationName_;
else
return rel + url;
}
}
} else
return makeAbsoluteUrl(url);
}
std::string WebSession::makeAbsoluteUrl(const std::string& url) const
{
if (isAbsoluteUrl(url))
return url;
else {
if (!url.empty() && url[0] == '.' &&
(url.length() == 1 || url[1] != '.'))
return absoluteBaseUrl_ + (url.c_str() + 1);
else if (url.empty() || url[0] != '/')
return absoluteBaseUrl_ + url;
else
return host(absoluteBaseUrl_) + url;
}
}
std::string WebSession::mostRelativeUrl(const std::string& internalPath) const
{
return appendSessionQuery(bookmarkUrl(internalPath));
}
std::string WebSession::appendSessionQuery(const std::string& url) const
{
std::string result = url;
if (env_->agentIsSpiderBot())
return result;
std::size_t questionPos = result.find('?');
if (questionPos == std::string::npos)
result += sessionQuery();
else if (questionPos == result.length() - 1)
result += sessionQuery().substr(1);
else
result += '&' + sessionQuery().substr(1);
#ifndef WT_TARGET_JAVA
return result;
#else
if (boost::starts_with(result, "?"))
result = applicationUrl_ + result;
if (WebSession::Handler::instance()->response())
return WebSession::Handler::instance()->response()->encodeURL(result);
else {
/*
* This may happen if we are inside a WServer::posted() function.
* Unfortunately, then we cannot use Servlet API to URL encode.
*/
questionPos = result.find('?');
return result.substr(0, questionPos) + ";jsessionid=" + sessionId()
+ result.substr(questionPos);
}
#endif // WT_TARGET_JAVA
}
std::string WebSession::bookmarkUrl() const
{
if (app_)
return bookmarkUrl(app_->internalPath());
else
return bookmarkUrl(env_->internalPath());
}
std::string WebSession::bookmarkUrl(const std::string& internalPath) const
{
std::string result = bookmarkUrl_;
return appendInternalPath(result, internalPath);
}
std::string WebSession::appendInternalPath(const std::string& baseUrl,
const std::string& internalPath)
const
{
if (internalPath.empty() || internalPath == "/")
if (baseUrl.empty())
if (applicationName_.empty())
return ".";
else
return applicationName_;
else
return baseUrl;
else {
if (useUglyInternalPaths())
return baseUrl + "?_=" + DomElement::urlEncodeS(internalPath, "#/");
else {
if (applicationName_.empty())
return baseUrl + DomElement::urlEncodeS(internalPath.substr(1), "#/");
else
return baseUrl + DomElement::urlEncodeS(internalPath, "#/");
}
}
}
bool WebSession::start(WebResponse *response)
{
try {
app_ = controller_->doCreateApplication(this).release();
if (app_) {
if (!app_->internalPathValid_) {
if (response->responseType() == WebResponse::ResponseType::Page) {
response->setStatus(404);
}
}
} else {
throw WException("WebSession::start: ApplicationCreator returned a nullptr");
}
} catch (std::exception& e) {
app_ = nullptr;
kill();
RETHROW(e);
} catch (...) {
app_ = nullptr;
kill();
throw;
}
return app_;
}
std::string WebSession::getCgiValue(const std::string& varName) const
{
WebRequest *request = WebSession::Handler::instance()->request();
if (request)
return str(request->envValue(varName.c_str()));
else if(varName == "DOCUMENT_ROOT")
return docRoot_;
else
return std::string();
}
std::string WebSession::getCgiHeader(const std::string& headerName) const
{
WebRequest *request = WebSession::Handler::instance()->request();
if (request)
return str(request->headerValue(headerName.c_str()));
else
return std::string();
}
void WebSession::kill()
{
state_ = State::Dead;
/*
* Unlock the recursive eventloop that may be pending.
*/
unlockRecursiveEventLoop();
}
void WebSession::checkTimers()
{
WContainerWidget *timers = app_->timerRoot();
const std::vector<WWidget *>& timerWidgets = timers->children();
std::vector<WTimerWidget *> expired;
for (unsigned i = 0; i < timerWidgets.size(); ++i) {
WTimerWidget *wti = dynamic_cast<WTimerWidget *>(timerWidgets[i]);
if (wti->timerExpired())
expired.push_back(wti);
}
WMouseEvent dummy;
for (unsigned i = 0; i < expired.size(); ++i)
expired[i]->clicked().emit(dummy);
}
void WebSession::redirect(const std::string& url)
{
redirect_ = url;
if (redirect_.empty())
redirect_ = "?";
}
std::string WebSession::getRedirect()
{
std::string result = redirect_;
redirect_.clear();
return result;
}
WebSession::Handler::Handler()
: nextSignal(-1),
prevHandler_(nullptr),
session_(nullptr),
request_(nullptr),
response_(nullptr),
killed_(false)
{
init();
}
WebSession::Handler::Handler(const std::shared_ptr<WebSession>& session,
LockOption lockOption)
: nextSignal(-1),
#ifndef WT_TARGET_JAVA
sessionPtr_(session),
#endif // WT_TARGET_JAVA
#ifdef WT_THREADED
lock_(session->mutex_, std::defer_lock),
#endif // WT_THREADED
prevHandler_(nullptr),
session_(session.get()),
request_(nullptr),
response_(nullptr),
killed_(false)
{
switch (lockOption) {
case LockOption::NoLock:
break;
case LockOption::TakeLock:
#ifdef WT_THREADED
lockOwner_ = std::this_thread::get_id();
lock_.lock();
#endif
#ifdef WT_TARGET_JAVA
session->mutex().lock();
#endif
break;
case LockOption::TryLock:
#ifdef WT_THREADED
if (lock_.try_lock())
lockOwner_ = std::this_thread::get_id();
#endif
#ifdef WT_TARGET_JAVA
session->mutex().try_lock();
#endif
break;
}
init();
}
WebSession::Handler::Handler(WebSession *session)
: nextSignal(-1),
#ifdef WT_THREADED
lock_(session->mutex_),
#endif // WT_THREADED
prevHandler_(nullptr),
session_(session),
request_(nullptr),
response_(nullptr),
killed_(false)
{
#ifdef WT_THREADED
lockOwner_ = std::this_thread::get_id();
#endif
#ifdef WT_TARGET_JAVA
session->mutex().lock();
#endif // WT_TARGET_JAVA
init();
}
WebSession::Handler::Handler(const std::shared_ptr<WebSession>& session,
WebRequest& request, WebResponse& response)
: nextSignal(-1),
#ifndef WT_TARGET_JAVA
sessionPtr_(session),
#endif // WT_TARGET_JAVA
#ifdef WT_THREADED
lock_(session->mutex_),
#endif // WT_THREADED
prevHandler_(nullptr),
session_(session.get()),
request_(&request),
response_(&response),
killed_(false)
{
#ifdef WT_THREADED
lockOwner_ = std::this_thread::get_id();
#endif
#ifdef WT_TARGET_JAVA
session->mutex().lock();
#endif
init();
}
WebSession::Handler *WebSession::Handler::instance()
{
#ifdef WT_TARGET_JAVA
return threadHandler_.get();
#else
return threadHandler_;
#endif
}
bool WebSession::Handler::haveLock() const
{
#ifdef WT_THREADED
return lock_.owns_lock();
#else
#ifdef WT_TARGET_JAVA
return session_->mutex().owns_lock();
#else
return true;
#endif
#endif
}
void WebSession::Handler::unlock()
{
if (haveLock()) {
#ifndef WT_TARGET_JAVA
Utils::erase(session_->handlers_, this);
#ifdef WT_THREADED
lock_.unlock();
#endif // WT_THREADED
#endif // WT_TARGET_JAVA
#ifdef WT_TARGET_JAVA
session_->mutex().unlock();
#endif
}
}
void WebSession::Handler::init()
{
prevHandler_ = attachThreadToHandler(this);
#ifndef WT_TARGET_JAVA
if (haveLock())
session_->handlers_.push_back(this);
#endif
}
WebSession::Handler *
WebSession::Handler::attachThreadToHandler(Handler *handler)
{
WebSession::Handler *result;
#ifdef WT_TARGET_JAVA
result = threadHandler_.release();
threadHandler_.reset(handler);
#else
result = threadHandler_;
threadHandler_ = handler;
#endif
return result;
}
bool WebSession::attachThreadToLockedHandler()
{
#if !defined(WT_TARGET_JAVA)
/*
* We assume that another handler has already locked this session for us.
* We just need to find it.
*/
for (unsigned i = 0; i < handlers_.size(); ++i)
if (handlers_[i]->haveLock()) {
WebSession::Handler::attachThreadToHandler(handlers_[i]);
return true;
}
return false;
#else
Handler::attachThreadToHandler(new Handler(this, Handler::LockOption::NoLock));
return true;
#endif
}
void WebSession
::Handler::attachThreadToSession(const std::shared_ptr<WebSession>& session)
{
attachThreadToHandler(nullptr);
#ifdef WT_BOOST_THREADS
if (!session.get())
return;
/*
* It may be that we still need to attach to a session while it is being
* destroyed ? I'm not sure why this is useful, but cannot see anything
* wrong about it either ?
*/
if (session->state_ == State::Dead)
LOG_WARN_S(session, "attaching to dead session?");
if (!session.get()->attachThreadToLockedHandler()) {
/*
* We actually have two scenarios:
* - attachThread() once to have WApplication::instance() work. This will
* give the warning, and will not work reliably !
* - attachThread() in the wtwithqt case should execute what we have above
*/
LOG_WARN_S(session,
"attachThread(): no thread is holding this application's "
"lock ?");
WebSession::Handler::attachThreadToHandler
(new Handler(session, Handler::LockOption::NoLock));
}
#else
LOG_ERROR_S(session, "attachThread(): needs Wt built with threading enabled");
#endif
}
std::shared_ptr<ApplicationEvent> WebSession::popQueuedEvent()
{