WLUtils.m 16.6 KB
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
/*
 Copyright 2010-2016 Warply Inc. All rights reserved.
 
 Redistribution and use in source and binary forms, without modification, 
 are permitted provided that the following conditions are met:
 
 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 2. Redistributions in binaryform must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 
 THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "WLUtils.h"
#import "WLGlobals.h"

#import <Security/Security.h>

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@implementation UIDevice (Hardware)
/*
 Platforms
 
 iFPGA ->        ??
 
 iPhone1,1 ->    iPhone 1, M68
 iPhone1,2 ->    iPhone 3G, N82
 iPhone2,1 ->    iPhone 3GS, N88
 iPhone3,1 ->    iPhone 4/GSM, N89
 iPhone3,2 ->    iPhone 4/GSM Rev A, N90
 iPhone3,3 ->    iPhone 4/CDMA, N92
 iPhone4,1 ->    iPhone 4S/GSM+CDMA, N94
 iPhone5,1 ->    iPhone 5/GSM, N41
 iPhone5,2 ->    iPhone 5/GSM+CDMA, N42
 iPhone5,3 ->    iPhone 5C/GSM, N48
 iPhone5,4 ->    iPhone 5C/GSM+CDMA, N49
 iPhone6,1 ->    iPhone 5S/GSM, N51
 iPhone6,2 ->    iPhone 5S/GSM+CDMA, N53
 
 iPod1,1   ->    iPod touch 1, N45
 iPod2,1   ->    iPod touch 2, N72
 iPod2,2   ->    iPod touch 3, Prototype
 iPod3,1   ->    iPod touch 3, N18
 iPod4,1   ->    iPod touch 4, N81
 
 // Thanks NSForge
 ipad0,1   ->    iPad, Prototype
 iPad1,1   ->    iPad 1, WiFi and 3G, K48
 iPad2,1   ->    iPad 2, WiFi, K93
 iPad2,2   ->    iPad 2, GSM 3G, K94
 iPad2,3   ->    iPad 2, CDMA 3G, K95
 iPad2,4   ->    iPad 2, WiFi R2, K93A
 iPad3,1   ->    The new iPad, WiFi
 iPad3,2   ->    The new iPad, CDMA
 iPad3,3   ->    The new iPad
 iPad4,1   ->    (iPad 4G, WiFi)
 iPad4,2   ->    (iPad 4G, GSM)
 iPad4,3   ->    (iPad 4G, CDMA)
 
 iProd2,1   ->   AppleTV 2, Prototype
 AppleTV2,1 ->   AppleTV 2, K66
 AppleTV3,1 ->   AppleTV 3, ??
 
 i386, x86_64 -> iPhone Simulator
 */


#pragma mark sysctlbyname utils
////////////////////////////////////////////////////////////////////////////////
- (NSString *) getSysInfoByName:(char *)typeSpecifier
{
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
    
    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
    
    NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
    
    free(answer);
    return results;
}
////////////////////////////////////////////////////////////////////////////////
- (NSString *) platform
{
    return [self getSysInfoByName:"hw.machine"];
}

#pragma mark sysctl utils
////////////////////////////////////////////////////////////////////////////////
- (NSUInteger) getSysInfo: (uint) typeSpecifier
{
    size_t size = sizeof(int);
    int results;
    int mib[2] = {CTL_HW, typeSpecifier};
    sysctl(mib, 2, &results, &size, NULL, 0);
    return (NSUInteger) results;
}

#pragma mark platform type and name utils
////////////////////////////////////////////////////////////////////////////////
- (NSUInteger) platformType
{
    return [UIDevice platformTypeForString:[self platform]];
}

////////////////////////////////////////////////////////////////////////////////
- (NSString *) platformString
{
    return [UIDevice platformStringForType:[self platformType]];
}

////////////////////////////////////////////////////////////////////////////////
+ (NSUInteger) platformTypeForString:(NSString *)platform
{
    // The ever mysterious iFPGA
    if ([platform isEqualToString:@"iFPGA"])        return UIDeviceIFPGA;
    
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"])    return UIDeviceiPhone1;
    if ([platform isEqualToString:@"iPhone1,2"])    return UIDeviceiPhone3G;
    if ([platform hasPrefix:@"iPhone2"])            return UIDeviceiPhone3GS;
    if ([platform isEqualToString:@"iPhone3,1"])    return UIDeviceiPhone4GSM;
    if ([platform isEqualToString:@"iPhone3,2"])    return UIDeviceiPhone4GSMRevA;
    if ([platform isEqualToString:@"iPhone3,3"])    return UIDeviceiPhone4CDMA;
    if ([platform hasPrefix:@"iPhone4"])            return UIDeviceiPhone4S;
    if ([platform isEqualToString:@"iPhone5,1"])    return UIDeviceiPhone5GSM;
    if ([platform isEqualToString:@"iPhone5,2"])    return UIDeviceiPhone5CDMA;
    if ([platform isEqualToString:@"iPhone5,3"])    return UIDeviceiPhone5CGSM;
    if ([platform isEqualToString:@"iPhone5,4"])    return UIDeviceiPhone5CGSMCDMA;
    if ([platform isEqualToString:@"iPhone6,1"])    return UIDeviceiPhone5SGSM;
    if ([platform isEqualToString:@"iPhone6,2"])    return UIDeviceiPhone5SGSMCDMA;
    
    // iPod
    if ([platform hasPrefix:@"iPod1"])              return UIDeviceiPod1;
    if ([platform isEqualToString:@"iPod2,2"])      return UIDeviceiPod3;
    if ([platform hasPrefix:@"iPod2"])              return UIDeviceiPod2;
    if ([platform hasPrefix:@"iPod3"])              return UIDeviceiPod3;
    if ([platform hasPrefix:@"iPod4"])              return UIDeviceiPod4;
    if ([platform hasPrefix:@"iPod5"])              return UIDeviceiPod5;
    
    // iPad
    if ([platform hasPrefix:@"iPad1"])              return UIDeviceiPad1;
    if ([platform hasPrefix:@"iPad2"])
    {
        NSInteger submodel = [ UIDevice getSubmodel:platform ];
        if ( submodel <= 4 )
        {
            return UIDeviceiPad2;
        } else
        {
            return UIDeviceiPadMini;
        }
    }
    if ([platform hasPrefix:@"iPad3"])
    {
        NSInteger submodel = [ UIDevice getSubmodel:platform ];
        if ( submodel <= 3 )
        {
            return UIDeviceTheNewiPad;
        } else
        {
            return UIDeviceiPad4G;
        }
    }
    
    if ([platform isEqualToString:@"iPad4,1"])    return UIDeviceiPadAir;
    if ([platform isEqualToString:@"iPad4,2"])    return UIDeviceiPadAirLTE;
    
    // Apple TV
    if ([platform hasPrefix:@"AppleTV2"])           return UIDeviceAppleTV2;
    if ([platform hasPrefix:@"AppleTV3"])           return UIDeviceAppleTV3;
    
    if ([platform hasPrefix:@"iPhone"])             return UIDeviceUnknowniPhone;
    if ([platform hasPrefix:@"iPod"])               return UIDeviceUnknowniPod;
    if ([platform hasPrefix:@"iPad"])               return UIDeviceUnknowniPad;
    if ([platform hasPrefix:@"AppleTV"])            return UIDeviceUnknownAppleTV;
    
    // Simulator thanks Jordan Breeding
    if ([platform hasSuffix:@"86"] || [platform isEqual:@"x86_64"])
    {
        BOOL smallerScreen = [[UIScreen mainScreen] bounds].size.width < 768;
        return smallerScreen ? UIDeviceiPhoneSimulatoriPhone : UIDeviceiPhoneSimulatoriPad;
    }
    
    return UIDeviceUnknown;
}

////////////////////////////////////////////////////////////////////////////////
+( NSInteger )getSubmodel:( NSString* )platform
{
    NSInteger submodel = -1;
    
    NSArray* components = [ platform componentsSeparatedByString:@"," ];
    if ( [ components count ] >= 2 )
    {
        submodel = [ [ components objectAtIndex:1 ] intValue ];
    }
    return submodel;
}

////////////////////////////////////////////////////////////////////////////////
+ (NSString *) platformStringForType:(NSUInteger)platformType
{
    switch (platformType)
    {
        case UIDeviceiPhone1:               return IPHONE_1_NAMESTRING;
        case UIDeviceiPhone3G:              return IPHONE_3G_NAMESTRING;
        case UIDeviceiPhone3GS:             return IPHONE_3GS_NAMESTRING;
        case UIDeviceiPhone4GSM:            return IPHONE_4_NAMESTRING;
        case UIDeviceiPhone4GSMRevA:        return IPHONE_4_NAMESTRING;
        case UIDeviceiPhone4CDMA:           return IPHONE_4_NAMESTRING;
        case UIDeviceiPhone4S:              return IPHONE_4S_NAMESTRING;
        case UIDeviceiPhone5GSM:            return IPHONE_5_NAMESTRING;
        case UIDeviceiPhone5CDMA:           return IPHONE_5_NAMESTRING;
        case UIDeviceiPhone5CGSM:           return IPHONE_5C_NAMESTRING;
        case UIDeviceiPhone5CGSMCDMA:       return IPHONE_5C_NAMESTRING;
        case UIDeviceiPhone5SGSM:           return IPHONE_5S_NAMESTRING;
        case UIDeviceiPhone5SGSMCDMA:       return IPHONE_5S_NAMESTRING;
        case UIDeviceUnknowniPhone:         return IPHONE_UNKNOWN_NAMESTRING;
            
        case UIDeviceiPod1:                 return IPOD_1_NAMESTRING;
        case UIDeviceiPod2:                 return IPOD_2_NAMESTRING;
        case UIDeviceiPod3:                 return IPOD_3_NAMESTRING;
        case UIDeviceiPod4:                 return IPOD_4_NAMESTRING;
        case UIDeviceiPod5:                 return IPOD_5_NAMESTRING;
        case UIDeviceUnknowniPod:           return IPOD_UNKNOWN_NAMESTRING;
            
        case UIDeviceiPad1 :                return IPAD_1_NAMESTRING;
        case UIDeviceiPad2 :                return IPAD_2_NAMESTRING;
        case UIDeviceTheNewiPad :           return THE_NEW_IPAD_NAMESTRING;
        case UIDeviceiPad4G :               return IPAD_4G_NAMESTRING;
        case UIDeviceiPadAir :              return IPAD_AIR_NAMESTRING;
        case UIDeviceiPadAirLTE :           return IPAD_AIR_LTE_NAMESTRING;
        case UIDeviceiPadMini :             return IPAD_MINI_NAMESTRING;
        case UIDeviceUnknowniPad :          return IPAD_UNKNOWN_NAMESTRING;
            
        case UIDeviceAppleTV2 :             return APPLETV_2G_NAMESTRING;
        case UIDeviceAppleTV3 :             return APPLETV_3G_NAMESTRING;
        case UIDeviceAppleTV4 :             return APPLETV_4G_NAMESTRING;
        case UIDeviceUnknownAppleTV:        return APPLETV_UNKNOWN_NAMESTRING;
            
        case UIDeviceiPhoneSimulator:       return IPHONE_SIMULATOR_NAMESTRING;
        case UIDeviceiPhoneSimulatoriPhone: return IPHONE_SIMULATOR_IPHONE_NAMESTRING;
        case UIDeviceiPhoneSimulatoriPad:   return IPHONE_SIMULATOR_IPAD_NAMESTRING;
        case UIDeviceSimulatorAppleTV:      return SIMULATOR_APPLETV_NAMESTRING;
            
        case UIDeviceIFPGA:                 return IFPGA_NAMESTRING;
            
        default:                            return IOS_FAMILY_UNKNOWN_DEVICE;
    }
}

////////////////////////////////////////////////////////////////////////////////
+ (NSString *) platformStringForPlatform:(NSString *)platform
{
    NSUInteger platformType = [UIDevice platformTypeForString:platform];
    return [UIDevice platformStringForType:platformType];
}

////////////////////////////////////////////////////////////////////////////////
- (UIDeviceFamily) deviceFamily
{
    NSString *platform = [self platform];
    if ([platform hasPrefix:@"iPhone"]) return UIDeviceFamilyiPhone;
    if ([platform hasPrefix:@"iPod"]) return UIDeviceFamilyiPod;
    if ([platform hasPrefix:@"iPad"]) return UIDeviceFamilyiPad;
    if ([platform hasPrefix:@"AppleTV"]) return UIDeviceFamilyAppleTV;
    
    return UIDeviceFamilyUnknown;
}

////////////////////////////////////////////////////////////////////////////////
- (NSString *)deviceFamilyString
{
    NSString *platform = [self platform];
    if ([platform hasPrefix:@"iPhone"])
        return @"iPhone";
    if ([platform hasPrefix:@"iPod"])
        return @"iPod";
    if ([platform hasPrefix:@"iPad"])
        return @"iPad";
    if ([platform hasPrefix:@"AppleTV"])
        return @"AppleTV";
    return @"Unknown";
}

@end

@implementation WLKeychain

////////////////////////////////////////////////////////////////////////////////
+ (NSString *)appName 
{    
	NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    
	// Attempt to find a name for this application
	NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
	if (appName != nil)
		appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];	
    
    return appName;
}

////////////////////////////////////////////////////////////////////////////////
+ (NSString *)bundleIdentifier 
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
}

////////////////////////////////////////////////////////////////////////////////
+ (BOOL)setString:(NSString *)string forKey:(NSString *)key 
{
	if (string == nil || key == nil)
		return NO;
    
    key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
    
	// First check if it already exists, by creating a search dictionary and requesting that 
    // nothing be returned, and performing the search anyway.
	NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
	
	NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [existsQueryDictionary setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)(kSecClass)];
	
	// Add the keys to the search dict
    [existsQueryDictionary setObject:key forKey:(__bridge id)(kSecAttrAccount)];
	[existsQueryDictionary setObject:@"service" forKey:(__bridge id)(kSecAttrService)];
    [existsQueryDictionary setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey:(__bridge id)(kSecAttrAccessible)];
    
	OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), NULL);
	if (res == errSecItemNotFound) {
        if (string != nil) {
            NSMutableDictionary *addDict = existsQueryDictionary;
            [addDict setObject:data forKey:(__bridge id)(kSecValueData)];
            
            res = SecItemAdd((__bridge CFDictionaryRef)(addDict), NULL);
            NSAssert1(res == errSecSuccess, @"Received %d from SecItemAdd!", (int)res);
        }
	} 
    else if (res == errSecSuccess) {
		// Modify an existing one
		// Actually pull it now of the keychain at this point.
        NSDictionary *attributeDict = [NSDictionary dictionaryWithObject:data forKey:(__bridge id)(kSecValueData)];
        
		res = SecItemUpdate((__bridge CFDictionaryRef)(existsQueryDictionary), (__bridge CFDictionaryRef)(attributeDict));
		NSAssert1(res == errSecSuccess, @"SecItemUpdated returned %d!", (int)res);
		
	} 
    else
		NSAssert1(NO, @"Received %d from SecItemCopyMatching!", (int)res);
	
	return YES;
}

////////////////////////////////////////////////////////////////////////////////
+ (NSString*)getStringForKey:(NSString *)key 
{    
    key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
    
	NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
    [existsQueryDictionary setObject:(id)CFBridgingRelease(kSecClassGenericPassword) forKey:(id)CFBridgingRelease(kSecClass)];
	
	// Add the keys to the search dict
	[existsQueryDictionary setObject:@"service" forKey:(id)CFBridgingRelease(kSecAttrService)];
	[existsQueryDictionary setObject:key forKey:(id)CFBridgingRelease(kSecAttrAccount)];
    [existsQueryDictionary setObject:(id)CFBridgingRelease(kSecAttrAccessibleWhenUnlocked) forKey:(id)CFBridgingRelease(kSecAttrAccessible)];
	
	// We want the data back!
	NSData *data = nil;
    [existsQueryDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)(kSecReturnData)];
	
	OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), (CFTypeRef *)(void *)&data);
    
	if (res == errSecSuccess) {
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
		return string;
	}
    else
		NSAssert1(res == errSecItemNotFound, @"SecItemCopyMatching returned %d!", (int)res);
	
	return nil;
}

////////////////////////////////////////////////////////////////////////////////
+ (void)deleteStringForKey:(NSString *)key
{    
    key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
    
	NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
    [existsQueryDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
	
	// Add the keys to the search dict
	[existsQueryDictionary setObject:@"service" forKey:(__bridge id)kSecAttrService];
	[existsQueryDictionary setObject:key forKey:(__bridge id)kSecAttrAccount];
    [existsQueryDictionary setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
	
    SecItemDelete((__bridge CFDictionaryRef)existsQueryDictionary);
}

@end