File: NSMessagePortNameServer.m

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (431 lines) | stat: -rw-r--r-- 10,933 bytes parent folder | download | duplicates (2)
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
/* Implementation of message port subclass of NSPortNameServer

   Copyright (C) 2005 Free Software Foundation, Inc.

   This file is part of the GNUstep Base Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the
   Free Software Foundation,
   Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
   <title>NSMessagePortNameServer class reference</title>
   */

#include "common.h"

#include "Foundation/NSPortNameServer.h"

#include "Foundation/NSAutoreleasePool.h"
#include "Foundation/NSDebug.h"
#include "Foundation/NSError.h"
#include "Foundation/NSException.h"
#include "Foundation/NSLock.h"
#include "Foundation/NSMapTable.h"
#include "Foundation/NSPathUtilities.h"
#include "Foundation/NSPort.h"
#include "Foundation/NSFileManager.h"
#include "Foundation/NSValue.h"
#include "Foundation/NSThread.h"
#include "Foundation/NSUserDefaults.h"

#include "GNUstepBase/GSMime.h"

#include "../GSPrivate.h"
#include "../GSPortPrivate.h"

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


static NSRecursiveLock *serverLock = nil;
static NSMessagePortNameServer *defaultServer = nil;
static NSMapTable *portToNamesMap;
static NSString	*registry;
static HKEY	key;

static SECURITY_ATTRIBUTES	security;

@interface NSMessagePortNameServer (private)
+ (NSString *) _query: (NSString *)name;
+ (NSString *) _translate: (NSString *)name;
@end


/**
 * Subclass of [NSPortNameServer] taking/returning instances of [NSMessagePort].
 * Port removal functionality is not supported; if you want to cancel a service,
 * you have to destroy the port (invalidate the [NSMessagePort] given to
 * [NSPortNameServer-registerPort:forName:]).
 */
@implementation NSMessagePortNameServer

- (void) atExit
{
  NSMapEnumerator mEnum;
  NSMessagePort	*port;
  NSString	*name;

  mEnum = NSEnumerateMapTable(portToNamesMap);
  while (NSNextMapEnumeratorPair(&mEnum, (void *)&port, (void *)&name))
    {
      [defaultServer removePort: port];
    }
  NSEndMapTableEnumeration(&mEnum);
  DESTROY(portToNamesMap);
  DESTROY(serverLock);
  RegCloseKey(key);
}

+ (void) initialize
{
  if (self == [NSMessagePortNameServer class])
    {
      int	rc;

      serverLock = [NSRecursiveLock new];
      portToNamesMap = NSCreateMapTable(NSNonRetainedObjectMapKeyCallBacks,
	NSObjectMapValueCallBacks, 0);
      [self registerAtExit];

      security.nLength = sizeof(SECURITY_ATTRIBUTES);
      security.lpSecurityDescriptor = 0;	// Default
      security.bInheritHandle = FALSE;

      registry = @"Software\\GNUstepNSMessagePort";
      rc = RegCreateKeyExW(
	HKEY_CURRENT_USER,
	UNISTR(registry),
	0,
	(LPWSTR) L"",
	REG_OPTION_VOLATILE,
	STANDARD_RIGHTS_WRITE|STANDARD_RIGHTS_READ|KEY_SET_VALUE
	|KEY_QUERY_VALUE|KEY_NOTIFY,
	&security,
	&key,
	NULL);
      if (rc == ERROR_SUCCESS)
	{
	  rc = RegFlushKey(key);
	  if (rc != ERROR_SUCCESS)
	    {
	      NSLog(@"Failed to flush registry HKEY_CURRENT_USER\\%@ (%x)",
		registry, rc);
	    }
	}
      else
	{
	  NSLog(@"Failed to create registry HKEY_CURRENT_USER\\%@ (%x)",
	    registry, rc);
	}
    }
}

/**
 *  Obtain single instance for this host.
 */
+ (id) sharedInstance
{
  if (defaultServer == nil)
    {
      [serverLock lock];
      if (defaultServer == nil)
	{
	  defaultServer = (NSMessagePortNameServer *)NSAllocateObject(self,
	    0, NSDefaultMallocZone());
	}
      [serverLock unlock];
    }
  return defaultServer;
}


+ (NSString *) _query: (NSString *)name
{
  NSString	*mailslotName;
  NSString	*translatedName;
  NSString	*mailslotPath;
  unsigned char	buf[1024];
  unsigned char	*ptr = buf;
  DWORD		max = 1024;
  DWORD		len = 1024;
  DWORD		type;
  HANDLE	h;
  int		rc;

  translatedName = [[self class] _translate: name];

#if 1
/* FIXME ... wierd hack.
 * It appears that RegQueryValueExW does not always read from the registry,
 * but will in fact return cached results (even if you close and re-open the
 * registry key between the calls to RegQueryValueExW).  This is a problem
 * if we look up a server which is not running, and then try to look it up
 * again when it is running, or if we have one address recorded but the server
 * has been restarted and is using a new address.
 * I couldn't find any mention of this behavior ... but accidentally discovered
 * that a call to OutputDebugStringW stops it ... presumably something in the
 * debug system invalidates whatever registry caching is being done.
 * Anyway, on my XP SP2 system, this next line is needed to fix things.
 *
 * You can test this by running a GNUstep application without starting
 * gdnc beforehand.  If the bug is occurring, the app will try to start gdnc
 * then poll to connect to it, and after 5 seconds will abort because it
 * hasn't seen the gdnc port registered even though gdnc did start.
 * If the hack has fixed the bug, the app will just pause briefly during
 * startup (as it starts gdnc) and then continue when it finds the server
 * port.
 */
OutputDebugStringW(L"");
#endif

  rc = RegQueryValueExW(
    key,
    UNISTR(translatedName),
    (LPDWORD)0,
    &type,
    (LPBYTE)ptr,
    &len);
  while (rc == ERROR_MORE_DATA)
    {
      if (ptr != buf)
        {
	  free(ptr);
	}
      max += 1024;
      ptr = malloc(max);
      len = max;
      rc = RegQueryValueExW(
	key,
	UNISTR(translatedName),
	(LPDWORD)0,
	&type,
	(LPBYTE)ptr,
	&len);
    }
  if (rc != ERROR_SUCCESS)
    {
      if (ptr != buf)
        {
	  free(ptr);
	}
      return nil;
    }

  mailslotName = [NSString stringWithUTF8String: (const char *) ptr];
  if (ptr != buf)
    {
      free(ptr);
    }

  /*
   * See if we can open the port mailslot ... if not, the query returned
   * an old name, and we can remove it.
   */
  mailslotPath = [NSString stringWithFormat:
    @"\\\\.\\mailslot\\GNUstep\\NSMessagePort\\%@", mailslotName];
  h = CreateFileW(
    UNISTR(mailslotPath),
    GENERIC_WRITE,
    FILE_SHARE_READ|FILE_SHARE_WRITE,
    &security,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    (HANDLE)0);
  if (h == INVALID_HANDLE_VALUE)
    {
      NSDebugLLog(@"NSMessagePortNameServer",
        @"Failed to open mailslot (%@) for write on port named %@ - %@",
	mailslotPath, name, [NSError _last]);
      //RegDeleteValueW(key, UNISTR(n));
      return nil;
    }
  else
    {
      CloseHandle(h);	// OK
      return mailslotName;
    }
}

+ (NSString *) _translate: (NSString *)name
{
  NSData		*data;

  /*
   * Make sure name is representable in the registry ...
   * assume base64 encoded strings are valid.
   */
  data = [name dataUsingEncoding: NSUTF8StringEncoding];
  data = [GSMimeDocument encodeBase64: data];
  name = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
  AUTORELEASE(name);
  return name;
}

- (NSPort*) portForName: (NSString *)name
{
  return [self portForName: name onHost: @""];
}

- (NSPort*) portForName: (NSString *)name
		 onHost: (NSString *)host
{
  NSString	*n;

  NSDebugLLog(@"NSMessagePortNameServer",
    @"portForName: %@ host: %@", name, host);

  if ([host length] != 0)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"Attempt to contact a named host using a "
	@"message port name server.  This name server can only be used "
	@"to contact processes owned by the same user on the local host "
	@"(host name must be an empty string).  To contact processes "
	@"owned by other users or on other hosts you must use an instance "
	@"of the NSSocketPortNameServer class."];
    }

  n = [[self class] _query: name];
  if (n == nil)
    {
      NSDebugLLog(@"NSMessagePortNameServer", @"got no port for %@", name);
      return nil;
    }
  else
    {
      NSDebugLLog(@"NSMessagePortNameServer", @"got %@ for %@", n, name);
      return AUTORELEASE([NSMessagePort newWithName: n]);
    }
}

- (BOOL) registerPort: (NSPort *)port
	      forName: (NSString *)name
{
  NSMutableArray	*a;
  NSString		*n;
  int			rc;
  const unsigned char	*str;

  NSDebugLLog(@"NSMessagePortNameServer", @"register %@ as %@\n", port, name);
  if ([port isKindOfClass: [NSMessagePort class]] == NO)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"Attempted to register a non-NSMessagePort (%@)",
	port];
      return NO;
    }

  if ([[self class] _query: name] != nil)
    {
      NSDebugLLog(@"NSMessagePortNameServer", @"fail, is a live port");
      return NO;
    }

  n = [[self class] _translate: name];
  str = (const unsigned char *) [[(NSMessagePort*)port name] UTF8String];

  rc = RegSetValueExW(
    key,
    UNISTR(n),
    0,
    REG_BINARY,
    str,
    strlen((const char*) str)+1);
  NSDebugLLog(@"NSMessagePortNameServer", @"Set port '%s' for %@", str, n);
  if (rc == ERROR_SUCCESS)
    {
      rc = RegFlushKey(key);
      if (rc != ERROR_SUCCESS)
	{
	  NSLog(@"Failed to flush registry HKEY_CURRENT_USER\\%@\\%@ (%x)",
	    registry, n, rc);
	}
    }
  else
    {
      NSLog(@"Failed to insert HKEY_CURRENT_USER\\%@\\%@ (%x) %@",
	registry, n, rc, [NSError _last]);
      return NO;
    }

  [serverLock lock];
  a = NSMapGet(portToNamesMap, port);
  if (a != nil)
    {
      a = [[NSMutableArray alloc] init];
      NSMapInsert(portToNamesMap, port, a);
      RELEASE(a);
    }
  [a addObject: [name copy]];
  [serverLock unlock];

  return YES;
}

- (BOOL) removePortForName: (NSString *)name
{
  NSString	*n;

  NSDebugLLog(@"NSMessagePortNameServer", @"removePortForName: %@", name);
  n = [[self class] _translate: name];
  (void)RegDeleteValueW(key, UNISTR(n));

  return YES;
}

- (NSArray *) namesForPort: (NSPort *)port
{
  NSMutableArray	*a;

  [serverLock lock];
  a = NSMapGet(portToNamesMap, port);
  a = [a copy];
  [serverLock unlock];
  return AUTORELEASE(a);
}

- (BOOL) removePort: (NSPort *)port
{
  NSMutableArray *a;
  int		i;

  NSDebugLLog(@"NSMessagePortNameServer", @"removePort: %@", port);

  [serverLock lock];
  a = NSMapGet(portToNamesMap, port);

  for (i = 0; i < [a count]; i++)
    {
      [self removePort: port  forName: [a objectAtIndex: i]];
    }

  NSMapRemove(portToNamesMap, port);
  [serverLock unlock];

  return YES;
}

- (BOOL) removePort: (NSPort*)port forName: (NSString*)name
{
  NSDebugLLog(@"NSMessagePortNameServer",
    @"removePort: %@  forName: %@", port, name);

  if ([self portForName: name onHost: @""] == port)
    {
      return [self removePortForName: name];
    }
  return NO;
}

@end