forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsCookieService.cpp
4354 lines (3689 loc) · 152 KB
/
nsCookieService.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
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=8 et tw=80 : */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Likely.h"
#include "mozilla/net/CookieServiceChild.h"
#include "mozilla/net/NeckoCommon.h"
#include "nsCookieService.h"
#include "nsIServiceManager.h"
#include "nsIIOService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefService.h"
#include "nsICookiePermission.h"
#include "nsIURI.h"
#include "nsIURL.h"
#include "nsIChannel.h"
#include "nsIFile.h"
#include "nsIObserverService.h"
#include "nsILineInputStream.h"
#include "nsIEffectiveTLDService.h"
#include "nsIIDNService.h"
#include "mozIThirdPartyUtil.h"
#include "nsTArray.h"
#include "nsCOMArray.h"
#include "nsIMutableArray.h"
#include "nsArrayEnumerator.h"
#include "nsEnumeratorUtils.h"
#include "nsAutoPtr.h"
#include "nsReadableUtils.h"
#include "nsCRT.h"
#include "prprf.h"
#include "nsNetUtil.h"
#include "nsNetCID.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsNetCID.h"
#include "mozilla/storage.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/FileUtils.h"
#include "mozilla/Telemetry.h"
#include "nsIAppsService.h"
#include "mozIApplication.h"
#include "nsIConsoleService.h"
using namespace mozilla;
using namespace mozilla::net;
// Create key from baseDomain that will access the default cookie namespace.
// TODO: When we figure out what the API will look like for nsICookieManager{2}
// on content processes (see bug 777620), change to use the appropriate app
// namespace. For now those IDLs aren't supported on child processes.
#define DEFAULT_APP_KEY(baseDomain) \
nsCookieKey(baseDomain, NECKO_NO_APP_ID, false)
/******************************************************************************
* nsCookieService impl:
* useful types & constants
******************************************************************************/
static nsCookieService *gCookieService;
// XXX_hack. See bug 178993.
// This is a hack to hide HttpOnly cookies from older browsers
static const char kHttpOnlyPrefix[] = "#HttpOnly_";
#define COOKIES_FILE "cookies.sqlite"
#define COOKIES_SCHEMA_VERSION 5
// parameter indexes; see EnsureReadDomain, EnsureReadComplete and
// ReadCookieDBListener::HandleResult
#define IDX_NAME 0
#define IDX_VALUE 1
#define IDX_HOST 2
#define IDX_PATH 3
#define IDX_EXPIRY 4
#define IDX_LAST_ACCESSED 5
#define IDX_CREATION_TIME 6
#define IDX_SECURE 7
#define IDX_HTTPONLY 8
#define IDX_BASE_DOMAIN 9
#define IDX_APP_ID 10
#define IDX_BROWSER_ELEM 11
static const int64_t kCookieStaleThreshold = 60 * PR_USEC_PER_SEC; // 1 minute in microseconds
static const int64_t kCookiePurgeAge =
int64_t(30 * 24 * 60 * 60) * PR_USEC_PER_SEC; // 30 days in microseconds
static const char kOldCookieFileName[] = "cookies.txt";
#undef LIMIT
#define LIMIT(x, low, high, default) ((x) >= (low) && (x) <= (high) ? (x) : (default))
#undef ADD_TEN_PERCENT
#define ADD_TEN_PERCENT(i) static_cast<uint32_t>((i) + (i)/10)
// default limits for the cookie list. these can be tuned by the
// network.cookie.maxNumber and network.cookie.maxPerHost prefs respectively.
static const uint32_t kMaxNumberOfCookies = 3000;
static const uint32_t kMaxCookiesPerHost = 150;
static const uint32_t kMaxBytesPerCookie = 4096;
static const uint32_t kMaxBytesPerPath = 1024;
// behavior pref constants
static const uint32_t BEHAVIOR_ACCEPT = 0; // allow all cookies
static const uint32_t BEHAVIOR_REJECTFOREIGN = 1; // reject all third-party cookies
static const uint32_t BEHAVIOR_REJECT = 2; // reject all cookies
static const uint32_t BEHAVIOR_LIMITFOREIGN = 3; // reject third-party cookies unless the
// eTLD already has at least one cookie
// pref string constants
static const char kPrefCookieBehavior[] = "network.cookie.cookieBehavior";
static const char kPrefMaxNumberOfCookies[] = "network.cookie.maxNumber";
static const char kPrefMaxCookiesPerHost[] = "network.cookie.maxPerHost";
static const char kPrefCookiePurgeAge[] = "network.cookie.purgeAge";
static const char kPrefThirdPartySession[] = "network.cookie.thirdparty.sessionOnly";
static void
bindCookieParameters(mozIStorageBindingParamsArray *aParamsArray,
const nsCookieKey &aKey,
const nsCookie *aCookie);
// struct for temporarily storing cookie attributes during header parsing
struct nsCookieAttributes
{
nsAutoCString name;
nsAutoCString value;
nsAutoCString host;
nsAutoCString path;
nsAutoCString expires;
nsAutoCString maxage;
int64_t expiryTime;
bool isSession;
bool isSecure;
bool isHttpOnly;
};
// stores the nsCookieEntry entryclass and an index into the cookie array
// within that entryclass, for purposes of storing an iteration state that
// points to a certain cookie.
struct nsListIter
{
// default (non-initializing) constructor.
nsListIter()
{
}
// explicit constructor to a given iterator state with entryclass 'aEntry'
// and index 'aIndex'.
explicit
nsListIter(nsCookieEntry *aEntry, nsCookieEntry::IndexType aIndex)
: entry(aEntry)
, index(aIndex)
{
}
// get the nsCookie * the iterator currently points to.
nsCookie * Cookie() const
{
return entry->GetCookies()[index];
}
nsCookieEntry *entry;
nsCookieEntry::IndexType index;
};
/******************************************************************************
* Cookie logging handlers
* used for logging in nsCookieService
******************************************************************************/
// logging handlers
#ifdef MOZ_LOGGING
// in order to do logging, the following environment variables need to be set:
//
// set NSPR_LOG_MODULES=cookie:3 -- shows rejected cookies
// set NSPR_LOG_MODULES=cookie:4 -- shows accepted and rejected cookies
// set NSPR_LOG_FILE=cookie.log
//
#include "prlog.h"
#endif
// define logging macros for convenience
#define SET_COOKIE true
#define GET_COOKIE false
#ifdef PR_LOGGING
static PRLogModuleInfo *
GetCookieLog()
{
static PRLogModuleInfo *sCookieLog;
if (!sCookieLog)
sCookieLog = PR_NewLogModule("cookie");
return sCookieLog;
}
#define COOKIE_LOGFAILURE(a, b, c, d) LogFailure(a, b, c, d)
#define COOKIE_LOGSUCCESS(a, b, c, d, e) LogSuccess(a, b, c, d, e)
#define COOKIE_LOGEVICTED(a, details) \
PR_BEGIN_MACRO \
if (PR_LOG_TEST(GetCookieLog(), PR_LOG_DEBUG)) \
LogEvicted(a, details); \
PR_END_MACRO
#define COOKIE_LOGSTRING(lvl, fmt) \
PR_BEGIN_MACRO \
PR_LOG(GetCookieLog(), lvl, fmt); \
PR_LOG(GetCookieLog(), lvl, ("\n")); \
PR_END_MACRO
static void
LogFailure(bool aSetCookie, nsIURI *aHostURI, const char *aCookieString, const char *aReason)
{
// if logging isn't enabled, return now to save cycles
if (!PR_LOG_TEST(GetCookieLog(), PR_LOG_WARNING))
return;
nsAutoCString spec;
if (aHostURI)
aHostURI->GetAsciiSpec(spec);
PR_LOG(GetCookieLog(), PR_LOG_WARNING,
("===== %s =====\n", aSetCookie ? "COOKIE NOT ACCEPTED" : "COOKIE NOT SENT"));
PR_LOG(GetCookieLog(), PR_LOG_WARNING,("request URL: %s\n", spec.get()));
if (aSetCookie)
PR_LOG(GetCookieLog(), PR_LOG_WARNING,("cookie string: %s\n", aCookieString));
PRExplodedTime explodedTime;
PR_ExplodeTime(PR_Now(), PR_GMTParameters, &explodedTime);
char timeString[40];
PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
PR_LOG(GetCookieLog(), PR_LOG_WARNING,("current time: %s", timeString));
PR_LOG(GetCookieLog(), PR_LOG_WARNING,("rejected because %s\n", aReason));
PR_LOG(GetCookieLog(), PR_LOG_WARNING,("\n"));
}
static void
LogCookie(nsCookie *aCookie)
{
PRExplodedTime explodedTime;
PR_ExplodeTime(PR_Now(), PR_GMTParameters, &explodedTime);
char timeString[40];
PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("current time: %s", timeString));
if (aCookie) {
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("----------------\n"));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("name: %s\n", aCookie->Name().get()));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("value: %s\n", aCookie->Value().get()));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("%s: %s\n", aCookie->IsDomain() ? "domain" : "host", aCookie->Host().get()));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("path: %s\n", aCookie->Path().get()));
PR_ExplodeTime(aCookie->Expiry() * int64_t(PR_USEC_PER_SEC),
PR_GMTParameters, &explodedTime);
PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,
("expires: %s%s", timeString, aCookie->IsSession() ? " (at end of session)" : ""));
PR_ExplodeTime(aCookie->CreationTime(), PR_GMTParameters, &explodedTime);
PR_FormatTimeUSEnglish(timeString, 40, "%c GMT", &explodedTime);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("created: %s", timeString));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("is secure: %s\n", aCookie->IsSecure() ? "true" : "false"));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("is httpOnly: %s\n", aCookie->IsHttpOnly() ? "true" : "false"));
}
}
static void
LogSuccess(bool aSetCookie, nsIURI *aHostURI, const char *aCookieString, nsCookie *aCookie, bool aReplacing)
{
// if logging isn't enabled, return now to save cycles
if (!PR_LOG_TEST(GetCookieLog(), PR_LOG_DEBUG)) {
return;
}
nsAutoCString spec;
if (aHostURI)
aHostURI->GetAsciiSpec(spec);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,
("===== %s =====\n", aSetCookie ? "COOKIE ACCEPTED" : "COOKIE SENT"));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("request URL: %s\n", spec.get()));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("cookie string: %s\n", aCookieString));
if (aSetCookie)
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("replaces existing cookie: %s\n", aReplacing ? "true" : "false"));
LogCookie(aCookie);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("\n"));
}
static void
LogEvicted(nsCookie *aCookie, const char* details)
{
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("===== COOKIE EVICTED =====\n"));
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("%s\n", details));
LogCookie(aCookie);
PR_LOG(GetCookieLog(), PR_LOG_DEBUG,("\n"));
}
// inline wrappers to make passing in nsAFlatCStrings easier
static inline void
LogFailure(bool aSetCookie, nsIURI *aHostURI, const nsAFlatCString &aCookieString, const char *aReason)
{
LogFailure(aSetCookie, aHostURI, aCookieString.get(), aReason);
}
static inline void
LogSuccess(bool aSetCookie, nsIURI *aHostURI, const nsAFlatCString &aCookieString, nsCookie *aCookie, bool aReplacing)
{
LogSuccess(aSetCookie, aHostURI, aCookieString.get(), aCookie, aReplacing);
}
#else
#define COOKIE_LOGFAILURE(a, b, c, d) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGSUCCESS(a, b, c, d, e) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGEVICTED(a, b) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#define COOKIE_LOGSTRING(a, b) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#endif
#ifdef DEBUG
#define NS_ASSERT_SUCCESS(res) \
PR_BEGIN_MACRO \
nsresult __rv = res; /* Do not evaluate |res| more than once! */ \
if (NS_FAILED(__rv)) { \
char *msg = PR_smprintf("NS_ASSERT_SUCCESS(%s) failed with result 0x%X", \
#res, __rv); \
NS_ASSERTION(NS_SUCCEEDED(__rv), msg); \
PR_smprintf_free(msg); \
} \
PR_END_MACRO
#else
#define NS_ASSERT_SUCCESS(res) PR_BEGIN_MACRO /* nothing */ PR_END_MACRO
#endif
/******************************************************************************
* DBListenerErrorHandler impl:
* Parent class for our async storage listeners that handles the logging of
* errors.
******************************************************************************/
class DBListenerErrorHandler : public mozIStorageStatementCallback
{
protected:
explicit DBListenerErrorHandler(DBState* dbState) : mDBState(dbState) { }
nsRefPtr<DBState> mDBState;
virtual const char *GetOpType() = 0;
public:
NS_IMETHOD HandleError(mozIStorageError* aError) override
{
int32_t result = -1;
aError->GetResult(&result);
#ifdef PR_LOGGING
nsAutoCString message;
aError->GetMessage(message);
COOKIE_LOGSTRING(PR_LOG_WARNING,
("DBListenerErrorHandler::HandleError(): Error %d occurred while "
"performing operation '%s' with message '%s'; rebuilding database.",
result, GetOpType(), message.get()));
#endif
// Rebuild the database.
gCookieService->HandleCorruptDB(mDBState);
return NS_OK;
}
};
/******************************************************************************
* InsertCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous insertion operations.
******************************************************************************/
class InsertCookieDBListener final : public DBListenerErrorHandler
{
private:
virtual const char *GetOpType() override { return "INSERT"; }
~InsertCookieDBListener() {}
public:
NS_DECL_ISUPPORTS
explicit InsertCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
NS_IMETHOD HandleResult(mozIStorageResultSet*) override
{
NS_NOTREACHED("Unexpected call to InsertCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t aReason) override
{
// If we were rebuilding the db and we succeeded, make our corruptFlag say
// so.
if (mDBState->corruptFlag == DBState::REBUILDING &&
aReason == mozIStorageStatementCallback::REASON_FINISHED) {
COOKIE_LOGSTRING(PR_LOG_DEBUG,
("InsertCookieDBListener::HandleCompletion(): rebuild complete"));
mDBState->corruptFlag = DBState::OK;
}
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(InsertCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* UpdateCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous update operations.
******************************************************************************/
class UpdateCookieDBListener final : public DBListenerErrorHandler
{
private:
virtual const char *GetOpType() override { return "UPDATE"; }
~UpdateCookieDBListener() {}
public:
NS_DECL_ISUPPORTS
explicit UpdateCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
NS_IMETHOD HandleResult(mozIStorageResultSet*) override
{
NS_NOTREACHED("Unexpected call to UpdateCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t aReason) override
{
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(UpdateCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* RemoveCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous removal operations.
******************************************************************************/
class RemoveCookieDBListener final : public DBListenerErrorHandler
{
private:
virtual const char *GetOpType() override { return "REMOVE"; }
~RemoveCookieDBListener() {}
public:
NS_DECL_ISUPPORTS
explicit RemoveCookieDBListener(DBState* dbState) : DBListenerErrorHandler(dbState) { }
NS_IMETHOD HandleResult(mozIStorageResultSet*) override
{
NS_NOTREACHED("Unexpected call to RemoveCookieDBListener::HandleResult");
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t aReason) override
{
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(RemoveCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* ReadCookieDBListener impl:
* mozIStorageStatementCallback used to track asynchronous removal operations.
******************************************************************************/
class ReadCookieDBListener final : public DBListenerErrorHandler
{
private:
virtual const char *GetOpType() override { return "READ"; }
bool mCanceled;
~ReadCookieDBListener() {}
public:
NS_DECL_ISUPPORTS
explicit ReadCookieDBListener(DBState* dbState)
: DBListenerErrorHandler(dbState)
, mCanceled(false)
{
}
void Cancel() { mCanceled = true; }
NS_IMETHOD HandleResult(mozIStorageResultSet *aResult) override
{
nsCOMPtr<mozIStorageRow> row;
while (1) {
DebugOnly<nsresult> rv = aResult->GetNextRow(getter_AddRefs(row));
NS_ASSERT_SUCCESS(rv);
if (!row)
break;
CookieDomainTuple *tuple = mDBState->hostArray.AppendElement();
row->GetUTF8String(IDX_BASE_DOMAIN, tuple->key.mBaseDomain);
tuple->key.mAppId = static_cast<uint32_t>(row->AsInt32(IDX_APP_ID));
tuple->key.mInBrowserElement = static_cast<bool>(row->AsInt32(IDX_BROWSER_ELEM));
tuple->cookie = gCookieService->GetCookieFromRow(row);
}
return NS_OK;
}
NS_IMETHOD HandleCompletion(uint16_t aReason) override
{
// Process the completion of the read operation. If we have been canceled,
// we cannot assume that the cookieservice still has an open connection
// or that it even refers to the same database, so we must return early.
// Conversely, the cookieservice guarantees that if we have not been
// canceled, the database connection is still alive and we can safely
// operate on it.
if (mCanceled) {
// We may receive a REASON_FINISHED after being canceled;
// tweak the reason accordingly.
aReason = mozIStorageStatementCallback::REASON_CANCELED;
}
switch (aReason) {
case mozIStorageStatementCallback::REASON_FINISHED:
gCookieService->AsyncReadComplete();
break;
case mozIStorageStatementCallback::REASON_CANCELED:
// Nothing more to do here. The partially read data has already been
// thrown away.
COOKIE_LOGSTRING(PR_LOG_DEBUG, ("Read canceled"));
break;
case mozIStorageStatementCallback::REASON_ERROR:
// Nothing more to do here. DBListenerErrorHandler::HandleError()
// can handle it.
COOKIE_LOGSTRING(PR_LOG_DEBUG, ("Read error"));
break;
default:
NS_NOTREACHED("invalid reason");
}
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(ReadCookieDBListener, mozIStorageStatementCallback)
/******************************************************************************
* CloseCookieDBListener imp:
* Static mozIStorageCompletionCallback used to notify when the database is
* successfully closed.
******************************************************************************/
class CloseCookieDBListener final : public mozIStorageCompletionCallback
{
~CloseCookieDBListener() {}
public:
explicit CloseCookieDBListener(DBState* dbState) : mDBState(dbState) { }
nsRefPtr<DBState> mDBState;
NS_DECL_ISUPPORTS
NS_IMETHOD Complete(nsresult, nsISupports*) override
{
gCookieService->HandleDBClosed(mDBState);
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(CloseCookieDBListener, mozIStorageCompletionCallback)
namespace {
class AppClearDataObserver final : public nsIObserver {
~AppClearDataObserver() {}
public:
NS_DECL_ISUPPORTS
// nsIObserver implementation.
NS_IMETHODIMP
Observe(nsISupports *aSubject, const char *aTopic, const char16_t *data) override
{
MOZ_ASSERT(!nsCRT::strcmp(aTopic, TOPIC_WEB_APP_CLEAR_DATA));
uint32_t appId = NECKO_UNKNOWN_APP_ID;
bool browserOnly = false;
nsresult rv = NS_GetAppInfoFromClearDataNotification(aSubject, &appId,
&browserOnly);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsICookieManager2> cookieManager
= do_GetService(NS_COOKIEMANAGER_CONTRACTID);
MOZ_ASSERT(cookieManager);
return cookieManager->RemoveCookiesForApp(appId, browserOnly);
}
};
NS_IMPL_ISUPPORTS(AppClearDataObserver, nsIObserver)
} // anonymous namespace
size_t
nsCookieKey::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
return mBaseDomain.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
size_t
nsCookieEntry::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
size_t amount = nsCookieKey::SizeOfExcludingThis(aMallocSizeOf);
amount += mCookies.SizeOfExcludingThis(aMallocSizeOf);
for (uint32_t i = 0; i < mCookies.Length(); ++i) {
amount += mCookies[i]->SizeOfIncludingThis(aMallocSizeOf);
}
return amount;
}
size_t
CookieDomainTuple::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
size_t amount = 0;
amount += key.SizeOfExcludingThis(aMallocSizeOf);
amount += cookie->SizeOfIncludingThis(aMallocSizeOf);
return amount;
}
size_t
DBState::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const
{
size_t amount = 0;
amount += aMallocSizeOf(this);
amount += hostTable.SizeOfExcludingThis(aMallocSizeOf);
amount += hostArray.SizeOfExcludingThis(aMallocSizeOf);
for (uint32_t i = 0; i < hostArray.Length(); ++i) {
amount += hostArray[i].SizeOfExcludingThis(aMallocSizeOf);
}
amount += readSet.SizeOfExcludingThis(aMallocSizeOf);
return amount;
}
/******************************************************************************
* nsCookieService impl:
* singleton instance ctor/dtor methods
******************************************************************************/
nsICookieService*
nsCookieService::GetXPCOMSingleton()
{
if (IsNeckoChild())
return CookieServiceChild::GetSingleton();
return GetSingleton();
}
nsCookieService*
nsCookieService::GetSingleton()
{
NS_ASSERTION(!IsNeckoChild(), "not a parent process");
if (gCookieService) {
NS_ADDREF(gCookieService);
return gCookieService;
}
// Create a new singleton nsCookieService.
// We AddRef only once since XPCOM has rules about the ordering of module
// teardowns - by the time our module destructor is called, it's too late to
// Release our members (e.g. nsIObserverService and nsIPrefBranch), since GC
// cycles have already been completed and would result in serious leaks.
// See bug 209571.
gCookieService = new nsCookieService();
if (gCookieService) {
NS_ADDREF(gCookieService);
if (NS_FAILED(gCookieService->Init())) {
NS_RELEASE(gCookieService);
}
}
return gCookieService;
}
/* static */ void
nsCookieService::AppClearDataObserverInit()
{
nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
nsCOMPtr<nsIObserver> obs = new AppClearDataObserver();
observerService->AddObserver(obs, TOPIC_WEB_APP_CLEAR_DATA,
/* holdsWeak= */ false);
}
/******************************************************************************
* nsCookieService impl:
* public methods
******************************************************************************/
NS_IMPL_ISUPPORTS(nsCookieService,
nsICookieService,
nsICookieManager,
nsICookieManager2,
nsIObserver,
nsISupportsWeakReference,
nsIMemoryReporter)
nsCookieService::nsCookieService()
: mDBState(nullptr)
, mCookieBehavior(BEHAVIOR_ACCEPT)
, mThirdPartySession(false)
, mMaxNumberOfCookies(kMaxNumberOfCookies)
, mMaxCookiesPerHost(kMaxCookiesPerHost)
, mCookiePurgeAge(kCookiePurgeAge)
{
}
nsresult
nsCookieService::Init()
{
nsresult rv;
mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
mIDNService = do_GetService(NS_IDNSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID);
NS_ENSURE_SUCCESS(rv, rv);
// init our pref and observer
nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (prefBranch) {
prefBranch->AddObserver(kPrefCookieBehavior, this, true);
prefBranch->AddObserver(kPrefMaxNumberOfCookies, this, true);
prefBranch->AddObserver(kPrefMaxCookiesPerHost, this, true);
prefBranch->AddObserver(kPrefCookiePurgeAge, this, true);
prefBranch->AddObserver(kPrefThirdPartySession, this, true);
PrefChanged(prefBranch);
}
mStorageService = do_GetService("@mozilla.org/storage/service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Init our default, and possibly private DBStates.
InitDBStates();
RegisterWeakMemoryReporter(this);
mObserverService = mozilla::services::GetObserverService();
NS_ENSURE_STATE(mObserverService);
mObserverService->AddObserver(this, "profile-before-change", true);
mObserverService->AddObserver(this, "profile-do-change", true);
mObserverService->AddObserver(this, "last-pb-context-exited", true);
mPermissionService = do_GetService(NS_COOKIEPERMISSION_CONTRACTID);
if (!mPermissionService) {
NS_WARNING("nsICookiePermission implementation not available - some features won't work!");
COOKIE_LOGSTRING(PR_LOG_WARNING, ("Init(): nsICookiePermission implementation not available"));
}
return NS_OK;
}
void
nsCookieService::InitDBStates()
{
NS_ASSERTION(!mDBState, "already have a DBState");
NS_ASSERTION(!mDefaultDBState, "already have a default DBState");
NS_ASSERTION(!mPrivateDBState, "already have a private DBState");
// Create a new default DBState and set our current one.
mDefaultDBState = new DBState();
mDBState = mDefaultDBState;
mPrivateDBState = new DBState();
// Get our cookie file.
nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(mDefaultDBState->cookieFile));
if (NS_FAILED(rv)) {
// We've already set up our DBStates appropriately; nothing more to do.
COOKIE_LOGSTRING(PR_LOG_WARNING,
("InitDBStates(): couldn't get cookie file"));
return;
}
mDefaultDBState->cookieFile->AppendNative(NS_LITERAL_CSTRING(COOKIES_FILE));
// Attempt to open and read the database. If TryInitDB() returns RESULT_RETRY,
// do so.
OpenDBResult result = TryInitDB(false);
if (result == RESULT_RETRY) {
// Database may be corrupt. Synchronously close the connection, clean up the
// default DBState, and try again.
COOKIE_LOGSTRING(PR_LOG_WARNING, ("InitDBStates(): retrying TryInitDB()"));
CleanupCachedStatements();
CleanupDefaultDBConnection();
result = TryInitDB(true);
if (result == RESULT_RETRY) {
// We're done. Change the code to failure so we clean up below.
result = RESULT_FAILURE;
}
}
if (result == RESULT_FAILURE) {
COOKIE_LOGSTRING(PR_LOG_WARNING,
("InitDBStates(): TryInitDB() failed, closing connection"));
// Connection failure is unrecoverable. Clean up our connection. We can run
// fine without persistent storage -- e.g. if there's no profile.
CleanupCachedStatements();
CleanupDefaultDBConnection();
}
}
/* Attempt to open and read the database. If 'aRecreateDB' is true, try to
* move the existing database file out of the way and create a new one.
*
* @returns RESULT_OK if opening or creating the database succeeded;
* RESULT_RETRY if the database cannot be opened, is corrupt, or some
* other failure occurred that might be resolved by recreating the
* database; or RESULT_FAILED if there was an unrecoverable error and
* we must run without a database.
*
* If RESULT_RETRY or RESULT_FAILED is returned, the caller should perform
* cleanup of the default DBState.
*/
OpenDBResult
nsCookieService::TryInitDB(bool aRecreateDB)
{
NS_ASSERTION(!mDefaultDBState->dbConn, "nonnull dbConn");
NS_ASSERTION(!mDefaultDBState->stmtInsert, "nonnull stmtInsert");
NS_ASSERTION(!mDefaultDBState->insertListener, "nonnull insertListener");
NS_ASSERTION(!mDefaultDBState->syncConn, "nonnull syncConn");
// Ditch an existing db, if we've been told to (i.e. it's corrupt). We don't
// want to delete it outright, since it may be useful for debugging purposes,
// so we move it out of the way.
nsresult rv;
if (aRecreateDB) {
nsCOMPtr<nsIFile> backupFile;
mDefaultDBState->cookieFile->Clone(getter_AddRefs(backupFile));
rv = backupFile->MoveToNative(nullptr,
NS_LITERAL_CSTRING(COOKIES_FILE ".bak"));
NS_ENSURE_SUCCESS(rv, RESULT_FAILURE);
}
// This block provides scope for the Telemetry AutoTimer
{
Telemetry::AutoTimer<Telemetry::MOZ_SQLITE_COOKIES_OPEN_READAHEAD_MS>
telemetry;
ReadAheadFile(mDefaultDBState->cookieFile);
// open a connection to the cookie database, and only cache our connection
// and statements upon success. The connection is opened unshared to eliminate
// cache contention between the main and background threads.
rv = mStorageService->OpenUnsharedDatabase(mDefaultDBState->cookieFile,
getter_AddRefs(mDefaultDBState->dbConn));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Set up our listeners.
mDefaultDBState->insertListener = new InsertCookieDBListener(mDefaultDBState);
mDefaultDBState->updateListener = new UpdateCookieDBListener(mDefaultDBState);
mDefaultDBState->removeListener = new RemoveCookieDBListener(mDefaultDBState);
mDefaultDBState->closeListener = new CloseCookieDBListener(mDefaultDBState);
// Grow cookie db in 512KB increments
mDefaultDBState->dbConn->SetGrowthIncrement(512 * 1024, EmptyCString());
bool tableExists = false;
mDefaultDBState->dbConn->TableExists(NS_LITERAL_CSTRING("moz_cookies"),
&tableExists);
if (!tableExists) {
rv = CreateTable();
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
} else {
// table already exists; check the schema version before reading
int32_t dbSchemaVersion;
rv = mDefaultDBState->dbConn->GetSchemaVersion(&dbSchemaVersion);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Start a transaction for the whole migration block.
mozStorageTransaction transaction(mDefaultDBState->dbConn, true);
switch (dbSchemaVersion) {
// Upgrading.
// Every time you increment the database schema, you need to implement
// the upgrading code from the previous version to the new one. If migration
// fails for any reason, it's a bug -- so we return RESULT_RETRY such that
// the original database will be saved, in the hopes that we might one day
// see it and fix it.
case 1:
{
// Add the lastAccessed column to the table.
rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
"ALTER TABLE moz_cookies ADD lastAccessed INTEGER"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Fall through to the next upgrade.
case 2:
{
// Add the baseDomain column and index to the table.
rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
"ALTER TABLE moz_cookies ADD baseDomain TEXT"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
// Compute the baseDomains for the table. This must be done eagerly
// otherwise we won't be able to synchronously read in individual
// domains on demand.
const int64_t SCHEMA2_IDX_ID = 0;
const int64_t SCHEMA2_IDX_HOST = 1;
nsCOMPtr<mozIStorageStatement> select;
rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
"SELECT id, host FROM moz_cookies"), getter_AddRefs(select));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCOMPtr<mozIStorageStatement> update;
rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
"UPDATE moz_cookies SET baseDomain = :baseDomain WHERE id = :id"),
getter_AddRefs(update));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCString baseDomain, host;
bool hasResult;
while (1) {
rv = select->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
if (!hasResult)
break;
int64_t id = select->AsInt64(SCHEMA2_IDX_ID);
select->GetUTF8String(SCHEMA2_IDX_HOST, host);
rv = GetBaseDomainFromHost(host, baseDomain);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
mozStorageStatementScoper scoper(update);
rv = update->BindUTF8StringByName(NS_LITERAL_CSTRING("baseDomain"),
baseDomain);
NS_ASSERT_SUCCESS(rv);
rv = update->BindInt64ByName(NS_LITERAL_CSTRING("id"),
id);
NS_ASSERT_SUCCESS(rv);
rv = update->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Create an index on baseDomain.
rv = mDefaultDBState->dbConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
"CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)"));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
}
// Fall through to the next upgrade.
case 3:
{
// Add the creationTime column to the table, and create a unique index
// on (name, host, path). Before we do this, we have to purge the table
// of expired cookies such that we know that the (name, host, path)
// index is truly unique -- otherwise we can't create the index. Note
// that we can't just execute a statement to delete all rows where the
// expiry column is in the past -- doing so would rely on the clock
// (both now and when previous cookies were set) being monotonic.
// Select the whole table, and order by the fields we're interested in.
// This means we can simply do a linear traversal of the results and
// check for duplicates as we go.
const int64_t SCHEMA3_IDX_ID = 0;
const int64_t SCHEMA3_IDX_NAME = 1;
const int64_t SCHEMA3_IDX_HOST = 2;
const int64_t SCHEMA3_IDX_PATH = 3;
nsCOMPtr<mozIStorageStatement> select;
rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
"SELECT id, name, host, path FROM moz_cookies "
"ORDER BY name ASC, host ASC, path ASC, expiry ASC"),
getter_AddRefs(select));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);
nsCOMPtr<mozIStorageStatement> deleteExpired;
rv = mDefaultDBState->dbConn->CreateStatement(NS_LITERAL_CSTRING(
"DELETE FROM moz_cookies WHERE id = :id"),
getter_AddRefs(deleteExpired));
NS_ENSURE_SUCCESS(rv, RESULT_RETRY);