File: NSUserDefaults.m

package info (click to toggle)
gnustep-base 1.28.1%2Breally1.28.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 28,008 kB
  • sloc: objc: 223,137; ansic: 35,562; sh: 184; makefile: 128; cpp: 122; xml: 32
file content (625 lines) | stat: -rw-r--r-- 14,787 bytes parent folder | download | duplicates (3)
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
#import "common.h"

#import "Foundation/NSUserDefaults.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSException.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSProcessInfo.h"

#define	UNISTR(X) \
((const unichar*)[(X) cStringUsingEncoding: NSUnicodeStringEncoding])

extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);

@interface NSUserDefaults (Private)
- (id) initWithContentsOfFile: (NSString*)fielName;
@end

@interface NSUserDefaultsWin32 : NSUserDefaults
{
  NSString	*registryPrefix;
  NSMapTable	*registryInfo;
}
@end

@interface NSUserDefaults (Secrets)
- (id) initWithContentsOfFile: (NSString*)aPath;
- (BOOL) lockDefaultsFile: (BOOL*)wasLocked;
- (void) unlockDefaultsFile;
- (NSMutableDictionary*) readDefaults;
- (BOOL) wantToReadDefaultsSince: (NSDate*)lastSyncDate;
- (BOOL) writeDefaults: (NSDictionary*)defaults oldData: (NSDictionary*)oldData;
@end

struct NSUserDefaultsWin32_DomainInfo
{
  HKEY userKey;
  HKEY systemKey;
};

@implementation NSUserDefaultsWin32

- (void) dealloc
{
  DESTROY(registryPrefix);
  if (registryInfo != 0)
    {
      NSMapEnumerator	iter = NSEnumerateMapTable(registryInfo);
      NSString		*domain;
      struct NSUserDefaultsWin32_DomainInfo *dinfo;
  
      while (NSNextMapEnumeratorPair(&iter, (void**)&domain, (void**)&dinfo))
	{
	  LONG rc;

	  if (dinfo->userKey)
	    {
	      rc = RegCloseKey(dinfo->userKey);
	      if (rc != ERROR_SUCCESS)
		{
		  NSString	*dPath;

		  dPath = [registryPrefix stringByAppendingString: domain];
		  NSLog(@"Failed to close registry HKEY_CURRENT_USER\\%@ (%x)",
		    dPath, rc);
		}
	    }
	  if (dinfo->systemKey)
	    {
	      rc = RegCloseKey(dinfo->systemKey);
	      if (rc != ERROR_SUCCESS)
		{
		  NSString	*dPath;

		  dPath = [registryPrefix stringByAppendingString: domain];
		  NSLog(@"Failed to close registry HKEY_LOCAL_MACHINE\\%@ (%x)",
		    dPath, rc);
		}
	    }
	}
      NSEndMapTableEnumeration(&iter);
      NSResetMapTable(registryInfo);
      NSFreeMapTable(registryInfo);
      registryInfo = 0;
    }
  [super dealloc];
}

- (id) initWithUser: (NSString*)userName
{
  NSString	*path;
  NSRange	r;

  NSAssert([userName isEqual: NSUserName()],
    @"NSUserDefaultsWin32 doesn't support reading/writing to users other than the current user.");
	
  path = GSDefaultsRootForUser(userName);
  r = [path rangeOfString: @":REGISTRY:"];
  NSAssert(r.length > 0,
    @"NSUserDefaultsWin32 should only be used if defaults directory is :REGISTRY:");

  path = [path substringFromIndex: NSMaxRange(r)];
  if ([path length] == 0)
    {
      path = @"Software\\GNUstep\\";
    }
  else if ([path hasSuffix: @"\\"] == NO)
    {
      path = [path stringByAppendingString: @"\\"];
    }
  registryPrefix = RETAIN(path);
  self = [super initWithContentsOfFile: @":REGISTRY:"];
  return self;
}

- (BOOL) lockDefaultsFile: (BOOL*)wasLocked
{
  *wasLocked = NO;
  return YES;
}

- (NSMutableDictionary*) readDefaults
{
  NSArray		*allDomains;
  NSEnumerator		*iter;
  NSString		*persistentDomain;
  NSMutableDictionary	*newDict = nil;
  
  allDomains = [self persistentDomainNames];
  if ([allDomains count] == 0)
    {
      allDomains = [NSArray arrayWithObjects:
	[[NSProcessInfo processInfo] processName],
	NSGlobalDomain,
	nil];
    }
  
  if (registryInfo == 0)
    {
      registryInfo = NSCreateMapTable(NSObjectMapKeyCallBacks,
	NSOwnedPointerMapValueCallBacks, [allDomains count]);
    }

  newDict = [NSMutableDictionary dictionary];

  iter = [allDomains objectEnumerator];
  while ((persistentDomain = [iter nextObject]) != nil)
    {
      NSMutableDictionary *domainDict;
      struct NSUserDefaultsWin32_DomainInfo *dinfo;
      NSString *dPath;
      LONG rc;

      dinfo = NSMapGet(registryInfo, persistentDomain);
      if (dinfo == 0)
	{
	  dinfo = calloc(sizeof(struct NSUserDefaultsWin32_DomainInfo), 1);
	  NSMapInsertKnownAbsent(registryInfo, persistentDomain, dinfo);
	}
      dPath = [registryPrefix stringByAppendingString: persistentDomain];
      
      if (dinfo->userKey == 0)
	{
	  rc = RegOpenKeyExW(HKEY_CURRENT_USER,
	    UNISTR(dPath),
	    0,
	    STANDARD_RIGHTS_WRITE|STANDARD_RIGHTS_READ
	    |KEY_SET_VALUE|KEY_QUERY_VALUE,
	    &(dinfo->userKey));
	  if (rc == ERROR_FILE_NOT_FOUND)
	    {
	      dinfo->userKey = 0;
	    }
	  else if (rc != ERROR_SUCCESS)
	    {
	      NSLog(@"Failed to open registry HKEY_CURRENT_USER\\%@ (%x)",
		dPath, rc);
	      return nil;
	    }
	}
      if (dinfo->systemKey == 0)
	{
	  rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
	    UNISTR(dPath),
	    0,
	    STANDARD_RIGHTS_READ|KEY_QUERY_VALUE,
	    &(dinfo->systemKey));
	  if (rc == ERROR_FILE_NOT_FOUND)
	    {
	      dinfo->systemKey = 0;
	    }
	  else if (rc != ERROR_SUCCESS)
	    {
	      NSLog(@"Failed to open registry HKEY_LOCAL_MACHINE\\%@ (%x)",
		dPath, rc);
	      return nil;
	    }
	}
      
      domainDict = [newDict objectForKey: persistentDomain];
      if (domainDict == nil)
	{
	  domainDict = [NSMutableDictionary dictionary];
	  [newDict setObject: domainDict forKey: persistentDomain];
	}

      if (dinfo->systemKey)
	{
	  DWORD i = 0;
	  unichar *name = malloc(200);
	  unichar *data = malloc(1000);
	  DWORD namelenbuf = 100, datalenbuf = 1000;
	  DWORD type;

	  do
	    {
	      DWORD namelen = namelenbuf, datalen = datalenbuf;

	      rc = RegEnumValueW(dinfo->systemKey,
		i,
		name,
		&namelen,
		NULL,
		&type,
		(void*)data,
		&datalen);
	      if (rc == ERROR_SUCCESS)
		{
		  NS_DURING
		    {
		      id	v;
		      NSString	*k;

		      switch (type)
			{
			  case REG_SZ:
			    {
			      int datacharlen = datalen / 2;
			      if (datacharlen > 0 && data[datacharlen-1] == 0)
				datacharlen--;
				  
			      v = [NSString stringWithCharacters: data
							  length: datacharlen];
			    }
			    break;
			  case REG_BINARY:
			    {
			      v = [NSString stringWithCString: (char*)data
				encoding: NSASCIIStringEncoding];
			    }
			    break;
			  default:
			    NSLog(@"Bad registry type %d for '%S'", type, name);
			    v = 0;
			}
		      v = [v propertyList];
		      if (v)
			{
			  k = [NSString stringWithCharacters: name
						      length: namelen];
			  [domainDict setObject: v forKey: k];
			}
		    }
		  NS_HANDLER
		    NSLog(@"Bad registry value for '%S'", name);
		  NS_ENDHANDLER
		}
	      else if (rc == ERROR_MORE_DATA)
		{
		  if (namelen >= namelenbuf)
		    {
		      namelenbuf = namelen + 1;
		      name = realloc(name, namelenbuf * sizeof(unichar));
		    }
		  if (datalen >= datalenbuf)
		    {
		      datalenbuf = datalen + 1;
		      data = realloc(data, datalenbuf);
		    }
		  continue;
		}
	      else if (rc == ERROR_NO_MORE_ITEMS)
		{
		  break;
		}
	      else
		{
		  NSLog(@"RegEnumValueW error %d", rc);
		  break;
		}
	      i++;
	    } while (rc == ERROR_SUCCESS || rc == ERROR_MORE_DATA);
	  free(name);
	  free(data);
	}
      
      if (dinfo->userKey)
	{
	  DWORD i = 0;
	  unichar *name = malloc(200);
	  unichar *data = malloc(1000);
	  DWORD namelenbuf = 100, datalenbuf = 1000;
	  DWORD type;

	  do
	    {
	      DWORD namelen = namelenbuf, datalen = datalenbuf;

		  // RegEnumValueW returns the data as a wide string
		  // but returns the length in bytes.
		  // To add insult to injury, datalen includes the terminating
		  // NULL character, unless there isn't enough room, in which
		  // case it doesn't.
		  
	      rc = RegEnumValueW(dinfo->userKey,
		i,
		name,
		&namelen,
		NULL,
		&type,
		(void*)data,
		&datalen);
	      if (rc == ERROR_SUCCESS)
		{
		  NS_DURING
		    {
		      id	v;
		      NSString	*k;

		      switch (type)
			{
			  case REG_SZ:
			    {
			      int datacharlen = datalen / 2;
			      if (datacharlen > 0 && data[datacharlen-1] == 0)
				datacharlen--;
				  
			      v = [NSString stringWithCharacters: data
							  length: datacharlen];
			    }
			    break;
			  case REG_BINARY:
			    {
			      v = [NSString stringWithCString: (char*)data
				encoding: NSASCIIStringEncoding];
			    }
			    break;
			  default:
			    NSLog(@"Bad registry type %d for '%S'", type, name);
			    v = 0;
			}
		      v = [v propertyList];
		      if (v)
			{
			  k = [NSString stringWithCharacters: name
						      length: namelen];
			  [domainDict setObject: v forKey: k];
			}
		    }
		  NS_HANDLER
		    NSLog(@"Bad registry value for '%S'", name);
		  NS_ENDHANDLER
		}
	      else if (rc == ERROR_MORE_DATA)
		{
		  if (namelen >= namelenbuf)
		    {
		      namelenbuf = namelen + 1;
		      name = realloc(name, namelenbuf * sizeof(unichar));
		    }
		  if (datalen >= datalenbuf)
		    {
		      datalenbuf = datalen + 1;
		      data = realloc(data, datalenbuf);
		    }
		  continue;
		}
	      else if (rc == ERROR_NO_MORE_ITEMS)
		{
		  break;
		}
	      else
		{
		  NSLog(@"RegEnumValueW error %d", rc);
		  break;
		}
	      i++;
	    } while (rc == ERROR_SUCCESS || rc == ERROR_MORE_DATA);
	  free(name);
	  free(data);
	}
    }
  return newDict;
}

- (void) unlockDefaultsFile
{
  return;
}

- (BOOL) wantToReadDefaultsSince: (NSDate*)lastSyncDate
{
  if (lastSyncDate != nil && registryInfo != 0)
    {
      // Detect changes in the registry
      NSMapEnumerator	iter;
      NSString		*domain;
      struct NSUserDefaultsWin32_DomainInfo *dinfo;
      
      iter = NSEnumerateMapTable(registryInfo);
      while (NSNextMapEnumeratorPair(&iter, (void**)&domain, (void**)&dinfo))
	{
	  ULARGE_INTEGER lasttime;
	  LONG rc;
	  NSTimeInterval ti;
	  NSString	*dPath;

	  dPath = [registryPrefix stringByAppendingString: domain];

	  if (dinfo->userKey)
	    {
	      rc = RegQueryInfoKey(dinfo->userKey,
		NULL, NULL, NULL, NULL, NULL, NULL, NULL,
		NULL,NULL, NULL, (PFILETIME)&lasttime);
	      if (rc != ERROR_SUCCESS)
		{
		  NSString	*dName = [@"HKEY_CURRENT_USER\\"
		    stringByAppendingString: dPath];

		  NSLog(@"Failed to query modify time on registry %@ (%x)",
		    dName, rc);
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	      ti = -12622780800.0 + lasttime.QuadPart / 10000000.0;
	      if ([lastSyncDate timeIntervalSinceReferenceDate] < ti)
		{
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	    }
	  else
	    {
	      // If the key didn't exist, but now it does, we want to read it.
	      rc = RegOpenKeyExW(HKEY_CURRENT_USER,
		UNISTR(dPath),
		0,
		STANDARD_RIGHTS_WRITE|STANDARD_RIGHTS_READ
		|KEY_SET_VALUE|KEY_QUERY_VALUE,
		&(dinfo->userKey));
	      if (rc == ERROR_FILE_NOT_FOUND)
		{
		  dinfo->userKey = 0;
		}
	      else if (rc != ERROR_SUCCESS)
		{
		  NSString	*dName = [@"HKEY_CURRENT_USER\\"
		    stringByAppendingString: dPath];

		  NSLog(@"Failed to open registry %@ (%x)", dName, rc);
		}
	      else
		{
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	    }
	  if (dinfo->systemKey)
	    {
	      rc = RegQueryInfoKey(dinfo->systemKey,
		NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
		NULL, NULL, (PFILETIME)&lasttime);
	      if (rc != ERROR_SUCCESS)
		{
		  NSLog(@"Failed to query time on HKEY_LOCAL_MACHINE\\%@ (%x)",
		    dPath, rc);
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	      ti = -12622780800.0 + lasttime.QuadPart / 10000000.0;
	      if ([lastSyncDate timeIntervalSinceReferenceDate] < ti)
		{
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	    }
	  else
	    {
	      // If the key didn't exist, but now it does, we want to read it.
	      rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
		UNISTR(dPath),
		0,
		STANDARD_RIGHTS_READ|KEY_QUERY_VALUE,
		&(dinfo->systemKey));
	      if (rc == ERROR_FILE_NOT_FOUND)
		{
		  dinfo->systemKey = 0;
		}
	      else if (rc != ERROR_SUCCESS)
		{
		  NSLog(@"Failed to open registry HKEY_LOCAL_MACHINE\\%@ (%x)",
		    dPath, rc);
		}
	      else
		{
		  NSEndMapTableEnumeration(&iter);
		  return YES;
		}
	    }
	}
      NSEndMapTableEnumeration(&iter);
      return NO;
    }
  return YES;
}

- (BOOL) writeDefaults: (NSDictionary*)defaults oldData: (NSDictionary*)oldData
{
  NSEnumerator *iter;
  NSString *persistentDomain;
  
  if (registryInfo == 0)
    {
      registryInfo = NSCreateMapTable(NSObjectMapKeyCallBacks,
	NSOwnedPointerMapValueCallBacks, [defaults count]);
    }

  iter = [defaults keyEnumerator];
  while ((persistentDomain = [iter nextObject]) != nil)
    {
      struct NSUserDefaultsWin32_DomainInfo *dinfo;
      NSDictionary *domainDict;
      NSDictionary *oldDomainDict;
      NSString *dPath;
      LONG rc;
      NSEnumerator *valIter;
      NSString *valName;

      dinfo = NSMapGet(registryInfo, persistentDomain);
      if (dinfo == 0)
	{
	  dinfo = calloc(sizeof(struct NSUserDefaultsWin32_DomainInfo), 1);
	  NSMapInsertKnownAbsent(registryInfo, persistentDomain, dinfo);
	}

      domainDict = [defaults objectForKey: persistentDomain];
      oldDomainDict = [oldData objectForKey: persistentDomain];
      dPath = [registryPrefix stringByAppendingString: persistentDomain];
      
      if ([domainDict count] == 0)
	{
	  continue;
	}
      if (dinfo->userKey == 0)
	{
	  rc = RegCreateKeyExW(HKEY_CURRENT_USER,
	    UNISTR(dPath),
	    0,
	    (LPWSTR) L"",
	    REG_OPTION_NON_VOLATILE,
	    STANDARD_RIGHTS_WRITE|STANDARD_RIGHTS_READ|KEY_SET_VALUE
	    |KEY_QUERY_VALUE,
	    NULL,
	    &(dinfo->userKey),
	    NULL);
	  if (rc != ERROR_SUCCESS)
	    {
	      NSLog(@"Failed to create registry HKEY_CURRENT_USER\\%@ (%x)",
		dPath, rc);
	      return NO;
	    }
	}
      
      valIter = [domainDict keyEnumerator];
      while ((valName = [valIter nextObject]))
	{
	  id value = [domainDict objectForKey: valName];
	  id oldvalue = [oldDomainDict objectForKey: valName];

	  if (oldvalue == nil || [value isEqual: oldvalue] == NO)
	    {
	      NSString			*result = nil;
	      const unichar		*ptr;

	      GSPropertyListMake(value, nil, NO, NO, 0, &result);
	      ptr = UNISTR(result);
	      rc = RegSetValueExW(dinfo->userKey,
		UNISTR(valName),
		0,
		REG_SZ,
		(void*)ptr,
		2*(wcslen(ptr) + 1));
	      if (rc != ERROR_SUCCESS)
		{
		  NSLog(@"Failed to insert HKEY_CURRENT_USER\\%@\\%@ (%x)",
		    dPath, valName, rc);
		  return NO;
		}
	    }
	}
      // Enumerate over the oldvalues and delete the deleted keys.
      valIter = [oldDomainDict keyEnumerator];
      while ((valName = [valIter nextObject]) != nil)
	{
	  if ([domainDict objectForKey: valName] == nil)
	    {
	      // Delete value from registry
	      rc = RegDeleteValueW(dinfo->userKey, UNISTR(valName));
	      if (rc != ERROR_SUCCESS)
		{
		  NSLog(@"Failed to delete HKEY_CURRENT_USER\\%@\\%@ (%x)",
		    dPath, valName, rc);
		  return NO;
		}
	    }
	}
    }
  return YES;
}

@end