OpenUDID.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //
  2. // OpenUDID.m
  3. // openudid
  4. //
  5. // initiated by Yann Lechelle (cofounder @Appsfire) on 8/28/11.
  6. // Copyright 2011 OpenUDID.org
  7. //
  8. // Initiators/root branches
  9. // iOS code: https://github.com/ylechelle/OpenUDID
  10. // Android code: https://github.com/vieux/OpenUDID
  11. //
  12. // Contributors:
  13. // https://github.com/ylechelle/OpenUDID/contributors
  14. //
  15. /*
  16. http://en.wikipedia.org/wiki/Zlib_License
  17. This software is provided 'as-is', without any express or implied
  18. warranty. In no event will the authors be held liable for any damages
  19. arising from the use of this software.
  20. Permission is granted to anyone to use this software for any purpose,
  21. including commercial applications, and to alter it and redistribute it
  22. freely, subject to the following restrictions:
  23. 1. The origin of this software must not be misrepresented; you must not
  24. claim that you wrote the original software. If you use this software
  25. in a product, an acknowledgment in the product documentation would be
  26. appreciated but is not required.
  27. 2. Altered source versions must be plainly marked as such, and must not be
  28. misrepresented as being the original software.
  29. 3. This notice may not be removed or altered from any source
  30. distribution.
  31. */
  32. #if __has_feature(objc_arc)
  33. #error This file uses the classic non-ARC retain/release model; hints below...
  34. // to selectively compile this file as non-ARC, do as follows:
  35. // https://img.skitch.com/20120411-bcku69k1uw528cwh9frh5px8ya.png
  36. #endif
  37. #import "OpenUDID.h"
  38. #import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access
  39. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  40. #import <UIKit/UIPasteboard.h>
  41. #import <UIKit/UIKit.h>
  42. #else
  43. #import <AppKit/NSPasteboard.h>
  44. #endif
  45. #define OpenUDIDLog(fmt, ...)
  46. //#define OpenUDIDLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
  47. //#define OpenUDIDLog(fmt, ...) NSLog((@"[Line %d] " fmt), __LINE__, ##__VA_ARGS__);
  48. static NSString * kOpenUDIDSessionCache = nil;
  49. static NSString * const kOpenUDIDKey = @"OpenUDID";
  50. static NSString * const kOpenUDIDSlotKey = @"OpenUDID_slot";
  51. static NSString * const kOpenUDIDAppUIDKey = @"OpenUDID_appUID";
  52. static NSString * const kOpenUDIDTSKey = @"OpenUDID_createdTS";
  53. static NSString * const kOpenUDIDOOTSKey = @"OpenUDID_optOutTS";
  54. static NSString * const kOpenUDIDDomain = @"org.OpenUDID";
  55. static NSString * const kOpenUDIDSlotPBPrefix = @"org.OpenUDID.slot.";
  56. static int const kOpenUDIDRedundancySlots = 100;
  57. @interface OpenUDID (Private)
  58. + (void) _setDict:(id)dict forPasteboard:(id)pboard;
  59. + (NSMutableDictionary*) _getDictFromPasteboard:(id)pboard;
  60. + (NSString*) _generateFreshOpenUDID;
  61. @end
  62. @implementation OpenUDID
  63. // Archive a NSDictionary inside a pasteboard of a given type
  64. // Convenience method to support iOS & Mac OS X
  65. //
  66. + (void) _setDict:(id)dict forPasteboard:(id)pboard {
  67. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  68. [pboard setData:[NSKeyedArchiver archivedDataWithRootObject:dict] forPasteboardType:kOpenUDIDDomain];
  69. #else
  70. [pboard setData:[NSKeyedArchiver archivedDataWithRootObject:dict] forType:kOpenUDIDDomain];
  71. #endif
  72. }
  73. // Retrieve an NSDictionary from a pasteboard of a given type
  74. // Convenience method to support iOS & Mac OS X
  75. //
  76. + (NSMutableDictionary*) _getDictFromPasteboard:(id)pboard {
  77. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  78. id item = [pboard dataForPasteboardType:kOpenUDIDDomain];
  79. #else
  80. id item = [pboard dataForType:kOpenUDIDDomain];
  81. #endif
  82. if (item) {
  83. @try{
  84. item = [NSKeyedUnarchiver unarchiveObjectWithData:item];
  85. } @catch(NSException* e) {
  86. OpenUDIDLog(@"Unable to unarchive item %@ on pasteboard!", [pboard name]);
  87. item = nil;
  88. }
  89. }
  90. // return an instance of a MutableDictionary
  91. return [NSMutableDictionary dictionaryWithDictionary:(item == nil || [item isKindOfClass:[NSDictionary class]]) ? item : nil];
  92. }
  93. // Private method to create and return a new OpenUDID
  94. // Theoretically, this function is called once ever per application when calling [OpenUDID value] for the first time.
  95. // After that, the caching/pasteboard/redundancy mechanism inside [OpenUDID value] returns a persistent and cross application OpenUDID
  96. //
  97. + (NSString*) _generateFreshOpenUDID {
  98. NSString* _openUDID = nil;
  99. // August 2011: One day, this may no longer be allowed in iOS. When that is, just comment this line out.
  100. // March 25th 2012: this day has come, let's remove this "outlawed" call...
  101. #if TARGET_OS_IPHONE
  102. // if([UIDevice instancesRespondToSelector:@selector(uniqueIdentifier)]){
  103. // _openUDID = [[UIDevice currentDevice] uniqueIdentifier];
  104. // }
  105. #endif
  106. // Next we generate a UUID.
  107. // UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally Unique Identifiers) or IIDs
  108. // (Interface Identifiers), are 128-bit values guaranteed to be unique. A UUID is made unique over
  109. // both space and time by combining a value unique to the computer on which it was generated—usually the
  110. // Ethernet hardware address—and a value representing the number of 100-nanosecond intervals since
  111. // October 15, 1582 at 00:00:00.
  112. // We then hash this UUID with md5 to get 32 bytes, and then add 4 extra random bytes
  113. // Collision is possible of course, but unlikely and suitable for most industry needs (e.g. aggregate tracking)
  114. //
  115. if (_openUDID==nil) {
  116. CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  117. CFStringRef cfstring = CFUUIDCreateString(kCFAllocatorDefault, uuid);
  118. const char *cStr = CFStringGetCStringPtr(cfstring,CFStringGetFastestEncoding(cfstring));
  119. unsigned char result[16];
  120. CC_MD5( cStr, (int)strlen(cStr), result );
  121. CFRelease(uuid);
  122. CFRelease(cfstring);
  123. _openUDID = [NSString stringWithFormat:
  124. @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%08lx",
  125. result[0], result[1], result[2], result[3],
  126. result[4], result[5], result[6], result[7],
  127. result[8], result[9], result[10], result[11],
  128. result[12], result[13], result[14], result[15],
  129. arc4random() % 4294967295];
  130. }
  131. // Call to other developers in the Open Source community:
  132. //
  133. // feel free to suggest better or alternative "UDID" generation code above.
  134. // NOTE that the goal is NOT to find a better hash method, but rather, find a decentralized (i.e. not web-based)
  135. // 160 bits / 20 bytes random string generator with the fewest possible collisions.
  136. //
  137. return _openUDID;
  138. }
  139. // Main public method that returns the OpenUDID
  140. // This method will generate and store the OpenUDID if it doesn't exist, typically the first time it is called
  141. // It will return the null udid (forty zeros) if the user has somehow opted this app out (this is subject to 3rd party implementation)
  142. // Otherwise, it will register the current app and return the OpenUDID
  143. //
  144. + (NSString*) value {
  145. return [OpenUDID valueWithError:nil];
  146. }
  147. + (NSString*) valueWithError:(NSError **)error {
  148. if (kOpenUDIDSessionCache!=nil) {
  149. if (error!=nil)
  150. *error = [NSError errorWithDomain:kOpenUDIDDomain
  151. code:kOpenUDIDErrorNone
  152. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"OpenUDID in cache from first call",@"description", nil]];
  153. return kOpenUDIDSessionCache;
  154. }
  155. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  156. // The AppUID will uniquely identify this app within the pastebins
  157. //
  158. NSString * appUID = (NSString *) [defaults objectForKey:kOpenUDIDAppUIDKey];
  159. if(appUID == nil)
  160. {
  161. // generate a new uuid and store it in user defaults
  162. CFUUIDRef uuid = CFUUIDCreate(NULL);
  163. appUID = (NSString *) CFUUIDCreateString(NULL, uuid);
  164. CFRelease(uuid);
  165. }
  166. NSString* openUDID = nil;
  167. NSString* myRedundancySlotPBid = nil;
  168. NSDate* optedOutDate = nil;
  169. BOOL optedOut = NO;
  170. BOOL saveLocalDictToDefaults = NO;
  171. BOOL isCompromised = NO;
  172. // Do we have a local copy of the OpenUDID dictionary?
  173. // This local copy contains a copy of the openUDID, myRedundancySlotPBid (and unused in this block, the local bundleid, and the timestamp)
  174. //
  175. id localDict = [defaults objectForKey:kOpenUDIDKey];
  176. if ([localDict isKindOfClass:[NSDictionary class]]) {
  177. localDict = [NSMutableDictionary dictionaryWithDictionary:localDict]; // we might need to set/overwrite the redundancy slot
  178. openUDID = [localDict objectForKey:kOpenUDIDKey];
  179. myRedundancySlotPBid = [localDict objectForKey:kOpenUDIDSlotKey];
  180. optedOutDate = [localDict objectForKey:kOpenUDIDOOTSKey];
  181. optedOut = optedOutDate!=nil;
  182. OpenUDIDLog(@"localDict = %@",localDict);
  183. }
  184. // Here we go through a sequence of slots, each of which being a UIPasteboard created by each participating app
  185. // The idea behind this is to both multiple and redundant representations of OpenUDIDs, as well as serve as placeholder for potential opt-out
  186. //
  187. NSString* availableSlotPBid = nil;
  188. NSMutableDictionary* frequencyDict = [NSMutableDictionary dictionaryWithCapacity:kOpenUDIDRedundancySlots];
  189. for (int n=0; n<kOpenUDIDRedundancySlots; n++) {
  190. NSString* slotPBid = [NSString stringWithFormat:@"%@%d",kOpenUDIDSlotPBPrefix,n];
  191. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  192. UIPasteboard* slotPB = [UIPasteboard pasteboardWithName:slotPBid create:NO];
  193. #else
  194. NSPasteboard* slotPB = [NSPasteboard pasteboardWithName:slotPBid];
  195. #endif
  196. OpenUDIDLog(@"SlotPB name = %@",slotPBid);
  197. if (slotPB==nil) {
  198. // assign availableSlotPBid to be the first one available
  199. if (availableSlotPBid==nil) availableSlotPBid = slotPBid;
  200. } else {
  201. NSDictionary* dict = [OpenUDID _getDictFromPasteboard:slotPB];
  202. NSString* oudid = [dict objectForKey:kOpenUDIDKey];
  203. OpenUDIDLog(@"SlotPB dict = %@",dict);
  204. if (oudid==nil) {
  205. // availableSlotPBid could inside a non null slot where no oudid can be found
  206. if (availableSlotPBid==nil) availableSlotPBid = slotPBid;
  207. } else {
  208. // increment the frequency of this oudid key
  209. int count = [[frequencyDict valueForKey:oudid] intValue];
  210. [frequencyDict setObject:[NSNumber numberWithInt:++count] forKey:oudid];
  211. }
  212. // if we have a match with the app unique id,
  213. // then let's look if the external UIPasteboard representation marks this app as OptedOut
  214. NSString* gid = [dict objectForKey:kOpenUDIDAppUIDKey];
  215. if (gid!=nil && [gid isEqualToString:appUID]) {
  216. myRedundancySlotPBid = slotPBid;
  217. // the local dictionary is prime on the opt-out subject, so ignore if already opted-out locally
  218. if (optedOut) {
  219. optedOutDate = [dict objectForKey:kOpenUDIDOOTSKey];
  220. optedOut = optedOutDate!=nil;
  221. }
  222. }
  223. }
  224. }
  225. // sort the Frequency dict with highest occurence count of the same OpenUDID (redundancy, failsafe)
  226. // highest is last in the list
  227. //
  228. NSArray* arrayOfUDIDs = [frequencyDict keysSortedByValueUsingSelector:@selector(compare:)];
  229. NSString* mostReliableOpenUDID = (arrayOfUDIDs!=nil && [arrayOfUDIDs count]>0)? [arrayOfUDIDs lastObject] : nil;
  230. OpenUDIDLog(@"Freq Dict = %@\nMost reliable %@",frequencyDict,mostReliableOpenUDID);
  231. // if openUDID was not retrieved from the local preferences, then let's try to get it from the frequency dictionary above
  232. //
  233. if (openUDID==nil) {
  234. if (mostReliableOpenUDID==nil) {
  235. // this is the case where this app instance is likely to be the first one to use OpenUDID on this device
  236. // we create the OpenUDID, legacy or semi-random (i.e. most certainly unique)
  237. //
  238. openUDID = [OpenUDID _generateFreshOpenUDID];
  239. } else {
  240. // or we leverage the OpenUDID shared by other apps that have already gone through the process
  241. //
  242. openUDID = mostReliableOpenUDID;
  243. }
  244. // then we create a local representation
  245. //
  246. if (localDict==nil) {
  247. localDict = [NSMutableDictionary dictionaryWithCapacity:4];
  248. [localDict setObject:openUDID forKey:kOpenUDIDKey];
  249. [localDict setObject:appUID forKey:kOpenUDIDAppUIDKey];
  250. [localDict setObject:[NSDate date] forKey:kOpenUDIDTSKey];
  251. if (optedOut) [localDict setObject:optedOutDate forKey:kOpenUDIDTSKey];
  252. saveLocalDictToDefaults = YES;
  253. }
  254. }
  255. else {
  256. // Sanity/tampering check
  257. //
  258. if (mostReliableOpenUDID!=nil && ![mostReliableOpenUDID isEqualToString:openUDID])
  259. isCompromised = YES;
  260. }
  261. // Here we store in the available PB slot, if applicable
  262. //
  263. OpenUDIDLog(@"Available Slot %@ Existing Slot %@",availableSlotPBid,myRedundancySlotPBid);
  264. if (availableSlotPBid!=nil && (myRedundancySlotPBid==nil || [availableSlotPBid isEqualToString:myRedundancySlotPBid])) {
  265. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  266. UIPasteboard* slotPB = [UIPasteboard pasteboardWithName:availableSlotPBid create:YES];
  267. [slotPB setPersistent:YES];
  268. #else
  269. NSPasteboard* slotPB = [NSPasteboard pasteboardWithName:availableSlotPBid];
  270. #endif
  271. // save slotPBid to the defaults, and remember to save later
  272. //
  273. if (localDict) {
  274. [localDict setObject:availableSlotPBid forKey:kOpenUDIDSlotKey];
  275. saveLocalDictToDefaults = YES;
  276. }
  277. // Save the local dictionary to the corresponding UIPasteboard slot
  278. //
  279. if (openUDID && localDict)
  280. [OpenUDID _setDict:localDict forPasteboard:slotPB];
  281. }
  282. // Save the dictionary locally if applicable
  283. //
  284. if (localDict && saveLocalDictToDefaults)
  285. [defaults setObject:localDict forKey:kOpenUDIDKey];
  286. // If the UIPasteboard external representation marks this app as opted-out, then to respect privacy, we return the ZERO OpenUDID, a sequence of 40 zeros...
  287. // This is a *new* case that developers have to deal with. Unlikely, statistically low, but still.
  288. // To circumvent this and maintain good tracking (conversion ratios, etc.), developers are invited to calculate how many of their users have opted-out from the full set of users.
  289. // This ratio will let them extrapolate convertion ratios more accurately.
  290. //
  291. if (optedOut) {
  292. if (error!=nil) *error = [NSError errorWithDomain:kOpenUDIDDomain
  293. code:kOpenUDIDErrorOptedOut
  294. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Application with unique id %@ is opted-out from OpenUDID as of %@",appUID,optedOutDate],@"description", nil]];
  295. kOpenUDIDSessionCache = [[NSString stringWithFormat:@"%040x",0] retain];
  296. return kOpenUDIDSessionCache;
  297. }
  298. // return the well earned openUDID!
  299. //
  300. if (error!=nil) {
  301. if (isCompromised)
  302. *error = [NSError errorWithDomain:kOpenUDIDDomain
  303. code:kOpenUDIDErrorCompromised
  304. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Found a discrepancy between stored OpenUDID (reliable) and redundant copies; one of the apps on the device is most likely corrupting the OpenUDID protocol",@"description", nil]];
  305. else
  306. *error = [NSError errorWithDomain:kOpenUDIDDomain
  307. code:kOpenUDIDErrorNone
  308. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"OpenUDID succesfully retrieved",@"description", nil]];
  309. }
  310. kOpenUDIDSessionCache = [openUDID retain];
  311. return kOpenUDIDSessionCache;
  312. }
  313. + (void) setOptOut:(BOOL)optOutValue {
  314. // init call
  315. [OpenUDID value];
  316. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  317. // load the dictionary from local cache or create one
  318. id dict = [defaults objectForKey:kOpenUDIDKey];
  319. if ([dict isKindOfClass:[NSDictionary class]]) {
  320. dict = [NSMutableDictionary dictionaryWithDictionary:dict];
  321. } else {
  322. dict = [NSMutableDictionary dictionaryWithCapacity:2];
  323. }
  324. // set the opt-out date or remove key, according to parameter
  325. if (optOutValue)
  326. [dict setObject:[NSDate date] forKey:kOpenUDIDOOTSKey];
  327. else
  328. [dict removeObjectForKey:kOpenUDIDOOTSKey];
  329. // store the dictionary locally
  330. [defaults setObject:dict forKey:kOpenUDIDKey];
  331. OpenUDIDLog(@"Local dict after opt-out = %@",dict);
  332. // reset memory cache
  333. kOpenUDIDSessionCache = nil;
  334. }
  335. @end