- add sources.
[platform/framework/web/crosswalk.git] / src / rlz / mac / lib / rlz_value_store_mac.mm
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.
4
5 #include "rlz/mac/lib/rlz_value_store_mac.h"
6
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"
15
16 #import <Foundation/Foundation.h>
17 #include <pthread.h>
18
19 using base::mac::ObjCCast;
20
21 namespace rlz_lib {
22
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";
28
29 namespace {
30
31 NSString* GetNSProductName(Product product) {
32   return base::SysUTF8ToNSString(GetProductName(product));
33 }
34
35 NSString* GetNSAccessPointName(AccessPoint p) {
36   return base::SysUTF8ToNSString(GetAccessPointName(p));
37 }
38
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]);
45   if (!d) {
46     d = [NSMutableDictionary dictionaryWithCapacity:0];
47     [p setObject:d forKey:k];
48   }
49   return d;
50 }
51
52 }  // namespace
53
54 RlzValueStoreMac::RlzValueStoreMac(NSMutableDictionary* dict,
55                                    NSString* plist_path)
56   : dict_([dict retain]), plist_path_([plist_path retain]) {
57 }
58
59 RlzValueStoreMac::~RlzValueStoreMac() {
60 }
61
62 bool RlzValueStoreMac::HasAccess(AccessType type) {
63   NSFileManager* manager = [NSFileManager defaultManager];
64   switch (type) {
65     case kReadAccess:  return [manager isReadableFileAtPath:plist_path_];
66     case kWriteAccess: return [manager isWritableFileAtPath:plist_path_];
67   }
68 }
69
70 bool RlzValueStoreMac::WritePingTime(Product product, int64 time) {
71   NSNumber* n = [NSNumber numberWithLongLong:time];
72   [ProductDict(product) setObject:n forKey:kPingTimeKey];
73   return true;
74 }
75
76 bool RlzValueStoreMac::ReadPingTime(Product product, int64* time) {
77   if (NSNumber* n =
78       ObjCCast<NSNumber>([ProductDict(product) objectForKey:kPingTimeKey])) {
79     *time = [n longLongValue];
80     return true;
81   }
82   return false;
83 }
84
85 bool RlzValueStoreMac::ClearPingTime(Product product) {
86   [ProductDict(product) removeObjectForKey:kPingTimeKey];
87   return true;
88 }
89
90
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)];
96   return true;
97 }
98
99 bool RlzValueStoreMac::ReadAccessPointRlz(AccessPoint access_point,
100                                           char* rlz,
101                                           size_t rlz_size) {
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)]);
107     if (!val) {
108       if (rlz_size > 0)
109         rlz[0] = '\0';
110       return true;
111     }
112
113     std::string s = base::SysNSStringToUTF8(val);
114     if (s.size() >= rlz_size) {
115       rlz[0] = 0;
116       ASSERT_STRING("GetAccessPointRlz: Insufficient buffer size");
117       return false;
118     }
119     strncpy(rlz, s.c_str(), rlz_size);
120     return true;
121   }
122   if (rlz_size > 0)
123     rlz[0] = '\0';
124   return true;
125 }
126
127 bool RlzValueStoreMac::ClearAccessPointRlz(AccessPoint access_point) {
128   if (NSMutableDictionary* d = ObjCCast<NSMutableDictionary>(
129       [WorkingDict() objectForKey:kAccessPointKey])) {
130     [d removeObjectForKey:GetNSAccessPointName(access_point)];
131   }
132   return true;
133 }
134
135
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)];
141   return true;
142 }
143
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));
150     return true;
151   }
152   return true;
153 }
154
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)];
160     return true;
161   }
162   return false;
163 }
164
165 bool RlzValueStoreMac::ClearAllProductEvents(Product product) {
166   [ProductDict(product) removeObjectForKey:kProductEventKey];
167   return true;
168 }
169
170
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)];
176   return true;
177 }
178
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;
184   }
185   return false;
186 }
187
188 bool RlzValueStoreMac::ClearAllStatefulEvents(Product product) {
189   [ProductDict(product) removeObjectForKey:kStatefulEventKey];
190   return true;
191 }
192
193
194 void RlzValueStoreMac::CollectGarbage() {
195   NOTIMPLEMENTED();
196 }
197
198 NSDictionary* RlzValueStoreMac::dictionary() {
199   return dict_.get();
200 }
201
202 NSMutableDictionary* RlzValueStoreMac::WorkingDict() {
203   std::string brand(SupplementaryBranding::GetBrand());
204   if (brand.empty())
205     return dict_;
206
207   NSString* brand_ns =
208       [@"brand_" stringByAppendingString:base::SysUTF8ToNSString(brand)];
209
210   return GetOrCreateDict(dict_.get(), brand_ns);
211 }
212
213 NSMutableDictionary* RlzValueStoreMac::ProductDict(Product p) {
214   return GetOrCreateDict(WorkingDict(), GetNSProductName(p));
215 }
216
217
218 namespace {
219
220 RecursiveCrossProcessLock g_recursive_lock =
221     RECURSIVE_CROSS_PROCESS_LOCK_INITIALIZER;
222
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;
226
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
230 // object.
231
232 // This counts the nesting depth.
233 int g_lock_depth = 0;
234
235 // This is the store object that might be shared. Only set if g_lock_depth > 0.
236 RlzValueStoreMac* g_store_object = NULL;
237
238
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]);
246   if (!folder)
247     folder = [@"~/Library/Application Support" stringByStandardizingPath];
248   folder = [folder stringByAppendingPathComponent:@"Google/RLZ"];
249
250   if (g_test_folder)
251     folder = [g_test_folder stringByAppendingPathComponent:folder];
252
253   [manager createDirectoryAtPath:folder
254      withIntermediateDirectories:YES
255                       attributes:nil
256                            error:nil];
257   return folder;
258 }
259
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];
265 }
266
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];
272 }
273
274 }  // namespace
275
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|.
281
282   ++g_lock_depth;
283
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
287     // destructor.
288     CHECK(!g_store_object);
289     return;
290   }
291
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);
296     return;
297   }
298
299   CHECK(!g_store_object);
300
301   NSString* plist = RlzPlistFilename();
302
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];
307
308   NSMutableDictionary* dict =
309       [NSMutableDictionary dictionaryWithContentsOfFile:plist];
310   VERIFY(dict);
311
312   if (dict) {
313     store_.reset(new RlzValueStoreMac(dict, plist));
314     g_store_object = (RlzValueStoreMac*)store_.get();
315   }
316 }
317
318 ScopedRlzValueStoreLock::~ScopedRlzValueStoreLock() {
319   --g_lock_depth;
320   CHECK(g_lock_depth >= 0);
321
322   if (g_lock_depth > 0) {
323     // Other locks are still using store_, don't free it yet.
324     ignore_result(store_.release());
325     return;
326   }
327
328   if (store_.get()) {
329     g_store_object = NULL;
330
331     NSDictionary* dict =
332         static_cast<RlzValueStoreMac*>(store_.get())->dictionary();
333     VERIFY([dict writeToFile:RlzPlistFilename() atomically:YES]);
334   }
335
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.
338   if (store_.get())
339     CHECK(g_recursive_lock.file_lock_ != -1);
340   if (g_recursive_lock.file_lock_ == -1)
341     CHECK(!store_.get());
342
343   g_recursive_lock.ReleaseLock();
344 }
345
346 RlzValueStore* ScopedRlzValueStoreLock::GetStore() {
347   return store_.get();
348 }
349
350 namespace testing {
351
352 void SetRlzStoreDirectory(const base::FilePath& directory) {
353   base::mac::ScopedNSAutoreleasePool pool;
354
355   [g_test_folder release];
356   if (directory.empty()) {
357     g_test_folder = nil;
358   } else {
359     // Not Unsafe on OS X.
360     g_test_folder =
361       [[NSString alloc] initWithUTF8String:directory.AsUTF8Unsafe().c_str()];
362   }
363 }
364
365 std::string RlzStoreFilenameStr() {
366   @autoreleasepool {
367     return std::string([RlzPlistFilename() fileSystemRepresentation]);
368   }
369 }
370
371 }  // namespace testing
372
373 }  // namespace rlz_lib