1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "rlz/mac/lib/rlz_value_store_mac.h"
7 #include "base/files/file_path.h"
8 #include "base/logging.h"
9 #include "base/mac/foundation_util.h"
10 #include "base/strings/sys_string_conversions.h"
11 #include "rlz/lib/assert.h"
12 #include "rlz/lib/lib_values.h"
13 #include "rlz/lib/recursive_cross_process_lock_posix.h"
14 #include "rlz/lib/rlz_lib.h"
16 #import <Foundation/Foundation.h>
19 using base::mac::ObjCCast;
23 // These are written to disk and should not be changed.
24 NSString* const kPingTimeKey = @"pingTime";
25 NSString* const kAccessPointKey = @"accessPoints";
26 NSString* const kProductEventKey = @"productEvents";
27 NSString* const kStatefulEventKey = @"statefulEvents";
31 NSString* GetNSProductName(Product product) {
32 return base::SysUTF8ToNSString(GetProductName(product));
35 NSString* GetNSAccessPointName(AccessPoint p) {
36 return base::SysUTF8ToNSString(GetAccessPointName(p));
39 // Retrieves a subdictionary in |p| for key |k|, creating it if necessary.
40 // If the dictionary contains an object for |k| that is not a mutable
41 // dictionary, that object is replaced with an empty mutable dictinary.
42 NSMutableDictionary* GetOrCreateDict(
43 NSMutableDictionary* p, NSString* k) {
44 NSMutableDictionary* d = ObjCCast<NSMutableDictionary>([p objectForKey:k]);
46 d = [NSMutableDictionary dictionaryWithCapacity:0];
47 [p setObject:d forKey:k];
54 RlzValueStoreMac::RlzValueStoreMac(NSMutableDictionary* dict,
56 : dict_([dict retain]), plist_path_([plist_path retain]) {
59 RlzValueStoreMac::~RlzValueStoreMac() {
62 bool RlzValueStoreMac::HasAccess(AccessType type) {
63 NSFileManager* manager = [NSFileManager defaultManager];
65 case kReadAccess: return [manager isReadableFileAtPath:plist_path_];
66 case kWriteAccess: return [manager isWritableFileAtPath:plist_path_];
70 bool RlzValueStoreMac::WritePingTime(Product product, int64 time) {
71 NSNumber* n = [NSNumber numberWithLongLong:time];
72 [ProductDict(product) setObject:n forKey:kPingTimeKey];
76 bool RlzValueStoreMac::ReadPingTime(Product product, int64* time) {
78 ObjCCast<NSNumber>([ProductDict(product) objectForKey:kPingTimeKey])) {
79 *time = [n longLongValue];
85 bool RlzValueStoreMac::ClearPingTime(Product product) {
86 [ProductDict(product) removeObjectForKey:kPingTimeKey];
91 bool RlzValueStoreMac::WriteAccessPointRlz(AccessPoint access_point,
92 const char* new_rlz) {
93 NSMutableDictionary* d = GetOrCreateDict(WorkingDict(), kAccessPointKey);
94 [d setObject:base::SysUTF8ToNSString(new_rlz)
95 forKey:GetNSAccessPointName(access_point)];
99 bool RlzValueStoreMac::ReadAccessPointRlz(AccessPoint access_point,
102 // Reading a non-existent access point counts as success.
103 if (NSDictionary* d = ObjCCast<NSDictionary>(
104 [WorkingDict() objectForKey:kAccessPointKey])) {
105 NSString* val = ObjCCast<NSString>(
106 [d objectForKey:GetNSAccessPointName(access_point)]);
113 std::string s = base::SysNSStringToUTF8(val);
114 if (s.size() >= rlz_size) {
116 ASSERT_STRING("GetAccessPointRlz: Insufficient buffer size");
119 strncpy(rlz, s.c_str(), rlz_size);
127 bool RlzValueStoreMac::ClearAccessPointRlz(AccessPoint access_point) {
128 if (NSMutableDictionary* d = ObjCCast<NSMutableDictionary>(
129 [WorkingDict() objectForKey:kAccessPointKey])) {
130 [d removeObjectForKey:GetNSAccessPointName(access_point)];
136 bool RlzValueStoreMac::AddProductEvent(Product product,
137 const char* event_rlz) {
138 [GetOrCreateDict(ProductDict(product), kProductEventKey)
139 setObject:[NSNumber numberWithBool:YES]
140 forKey:base::SysUTF8ToNSString(event_rlz)];
144 bool RlzValueStoreMac::ReadProductEvents(Product product,
145 std::vector<std::string>* events) {
146 if (NSDictionary* d = ObjCCast<NSDictionary>(
147 [ProductDict(product) objectForKey:kProductEventKey])) {
148 for (NSString* s in d)
149 events->push_back(base::SysNSStringToUTF8(s));
155 bool RlzValueStoreMac::ClearProductEvent(Product product,
156 const char* event_rlz) {
157 if (NSMutableDictionary* d = ObjCCast<NSMutableDictionary>(
158 [ProductDict(product) objectForKey:kProductEventKey])) {
159 [d removeObjectForKey:base::SysUTF8ToNSString(event_rlz)];
165 bool RlzValueStoreMac::ClearAllProductEvents(Product product) {
166 [ProductDict(product) removeObjectForKey:kProductEventKey];
171 bool RlzValueStoreMac::AddStatefulEvent(Product product,
172 const char* event_rlz) {
173 [GetOrCreateDict(ProductDict(product), kStatefulEventKey)
174 setObject:[NSNumber numberWithBool:YES]
175 forKey:base::SysUTF8ToNSString(event_rlz)];
179 bool RlzValueStoreMac::IsStatefulEvent(Product product,
180 const char* event_rlz) {
181 if (NSDictionary* d = ObjCCast<NSDictionary>(
182 [ProductDict(product) objectForKey:kStatefulEventKey])) {
183 return [d objectForKey:base::SysUTF8ToNSString(event_rlz)] != nil;
188 bool RlzValueStoreMac::ClearAllStatefulEvents(Product product) {
189 [ProductDict(product) removeObjectForKey:kStatefulEventKey];
194 void RlzValueStoreMac::CollectGarbage() {
198 NSDictionary* RlzValueStoreMac::dictionary() {
202 NSMutableDictionary* RlzValueStoreMac::WorkingDict() {
203 std::string brand(SupplementaryBranding::GetBrand());
208 [@"brand_" stringByAppendingString:base::SysUTF8ToNSString(brand)];
210 return GetOrCreateDict(dict_.get(), brand_ns);
213 NSMutableDictionary* RlzValueStoreMac::ProductDict(Product p) {
214 return GetOrCreateDict(WorkingDict(), GetNSProductName(p));
220 RecursiveCrossProcessLock g_recursive_lock =
221 RECURSIVE_CROSS_PROCESS_LOCK_INITIALIZER;
223 // This is set during test execution, to write RLZ files into a temporary
224 // directory instead of the user's Application Support folder.
225 NSString* g_test_folder;
227 // RlzValueStoreMac keeps its data in memory and only writes it to disk when
228 // ScopedRlzValueStoreLock goes out of scope. Hence, if several
229 // ScopedRlzValueStoreLocks are nested, they all need to use the same store
232 // This counts the nesting depth.
233 int g_lock_depth = 0;
235 // This is the store object that might be shared. Only set if g_lock_depth > 0.
236 RlzValueStoreMac* g_store_object = NULL;
239 NSString* CreateRlzDirectory() {
240 NSFileManager* manager = [NSFileManager defaultManager];
241 NSArray* paths = NSSearchPathForDirectoriesInDomains(
242 NSApplicationSupportDirectory, NSUserDomainMask, /*expandTilde=*/YES);
243 NSString* folder = nil;
244 if ([paths count] > 0)
245 folder = ObjCCast<NSString>([paths objectAtIndex:0]);
247 folder = [@"~/Library/Application Support" stringByStandardizingPath];
248 folder = [folder stringByAppendingPathComponent:@"Google/RLZ"];
251 folder = [g_test_folder stringByAppendingPathComponent:folder];
253 [manager createDirectoryAtPath:folder
254 withIntermediateDirectories:YES
260 // Returns the path of the rlz plist store, also creates the parent directory
261 // path if it doesn't exist.
262 NSString* RlzPlistFilename() {
263 NSString* const kRlzFile = @"RlzStore.plist";
264 return [CreateRlzDirectory() stringByAppendingPathComponent:kRlzFile];
267 // Returns the path of the rlz lock file, also creates the parent directory
268 // path if it doesn't exist.
269 NSString* RlzLockFilename() {
270 NSString* const kRlzLockfile = @"flockfile";
271 return [CreateRlzDirectory() stringByAppendingPathComponent:kRlzLockfile];
276 ScopedRlzValueStoreLock::ScopedRlzValueStoreLock() {
277 bool got_distributed_lock = g_recursive_lock.TryGetCrossProcessLock(
278 base::FilePath([RlzLockFilename() fileSystemRepresentation]));
279 // At this point, we hold the in-process lock, no matter the value of
280 // |got_distributed_lock|.
284 if (!got_distributed_lock) {
285 // Give up. |store_| isn't set, which signals to callers that acquiring
286 // the lock failed. |g_recursive_lock| will be released by the
288 CHECK(!g_store_object);
292 if (g_lock_depth > 1) {
293 // Reuse the already existing store object. Note that it can be NULL when
294 // lock acquisition succeeded but the rlz data file couldn't be read.
295 store_.reset(g_store_object);
299 CHECK(!g_store_object);
301 NSString* plist = RlzPlistFilename();
303 // Create an empty file if none exists yet.
304 NSFileManager* manager = [NSFileManager defaultManager];
305 if (![manager fileExistsAtPath:plist isDirectory:NULL])
306 [[NSDictionary dictionary] writeToFile:plist atomically:YES];
308 NSMutableDictionary* dict =
309 [NSMutableDictionary dictionaryWithContentsOfFile:plist];
313 store_.reset(new RlzValueStoreMac(dict, plist));
314 g_store_object = (RlzValueStoreMac*)store_.get();
318 ScopedRlzValueStoreLock::~ScopedRlzValueStoreLock() {
320 CHECK(g_lock_depth >= 0);
322 if (g_lock_depth > 0) {
323 // Other locks are still using store_, don't free it yet.
324 ignore_result(store_.release());
329 g_store_object = NULL;
332 static_cast<RlzValueStoreMac*>(store_.get())->dictionary();
333 VERIFY([dict writeToFile:RlzPlistFilename() atomically:YES]);
336 // Check that "store_ set" => "file_lock acquired". The converse isn't true,
337 // for example if the rlz data file can't be read.
339 CHECK(g_recursive_lock.file_lock_ != -1);
340 if (g_recursive_lock.file_lock_ == -1)
341 CHECK(!store_.get());
343 g_recursive_lock.ReleaseLock();
346 RlzValueStore* ScopedRlzValueStoreLock::GetStore() {
352 void SetRlzStoreDirectory(const base::FilePath& directory) {
353 base::mac::ScopedNSAutoreleasePool pool;
355 [g_test_folder release];
356 if (directory.empty()) {
359 // Not Unsafe on OS X.
361 [[NSString alloc] initWithUTF8String:directory.AsUTF8Unsafe().c_str()];
365 std::string RlzStoreFilenameStr() {
367 return std::string([RlzPlistFilename() fileSystemRepresentation]);
371 } // namespace testing
373 } // namespace rlz_lib