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 (636 lines) | stat: -rw-r--r-- 17,429 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
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
626
627
628
629
630
631
632
633
634
635
636
/* 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
   Lesser 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>
   $Date$ $Revision$
   */

#import "common.h"
#import "Foundation/NSPortNameServer.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSException.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSDistributedLock.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSPort.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSThread.h"
#import "GNUstepBase/GSMime.h"

#import "GSPortPrivate.h"

#include <sys/stat.h>

#if	defined(HAVE_SYS_SIGNAL_H)
#  include	<sys/signal.h>
#elif	defined(HAVE_SIGNAL_H)
#  include	<signal.h>
#endif


#if	defined(HAVE_SYS_FCNTL_H)
#  include	<sys/fcntl.h>
#elif	defined(HAVE_FCNTL_H)
#  include	<fcntl.h>
#endif

#include <sys/un.h>

/* Older systems (Solaris) compatibility */
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#define PF_LOCAL PF_UNIX
#endif
#ifndef SUN_LEN
#define SUN_LEN(su) \
	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
#endif

@interface NSProcessInfo (private)
+ (BOOL) _exists: (int)pid;
@end

static NSRecursiveLock *serverLock = nil;
static NSMessagePortNameServer *defaultServer = nil;

/*
Maps NSMessagePort objects to NSMutableArray:s of NSString:s. The array
is an array of names the port has been registered under by _us_.

Note that this map holds the names the port has been registered under at
some time. If the name is been unregistered by some other program, we can't
update the table, so we have to deal with the case where the array contains
names that the port isn't registered under.

Since we _have_to_ deal with this anyway, we handle it in -removePort: and
-removePort:forName:, and we don't bother removing entries in the map when
unregistering a name not for a specific port.
*/
static NSMapTable *portToNamesMap;


@interface NSMessagePortNameServer (private)
+ (NSDistributedLock*) _fileLock;
+ (NSString *) _pathForName: (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;
  NSAutoreleasePool	*arp = [NSAutoreleasePool new];

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

+ (void) initialize
{
  if (self == [NSMessagePortNameServer class])
    {
      NSAutoreleasePool *pool = [NSAutoreleasePool new];
      NSFileManager	*mgr;
      NSString		*path;
      NSString		*pid;
      NSString		*file;
      NSEnumerator	*files;

      serverLock = [NSRecursiveLock new];
      /* Use NSNonOwnedPointerMapKeyCallBacks for the ports used as keys
       * since we want as pointer test for equality as we may be doing
       * lookup while dealocating the port (in which case the -isEqual:
       * method could fail).
       */
      portToNamesMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
        NSObjectMapValueCallBacks, 0);
      [self registerAtExit];

      /* It's possible that an old process, with the same process ID as
       * this one, got forcibly killed or crashed so that +atExit
       * was never called.
       * To deal with that unlikely situation, we need to remove all such
       * names which have been left over.
       */
      path = NSTemporaryDirectory();
      path = [path stringByAppendingPathComponent: @"NSMessagePort"];
      path = [path stringByAppendingPathComponent: @"names"];
      pid = [NSString stringWithFormat: @"%i",
	[[NSProcessInfo processInfo] processIdentifier]];
      mgr = [NSFileManager defaultManager];
      files = [[mgr directoryContentsAtPath: path] objectEnumerator];
      while ((file = [files nextObject]) != nil)
	{
          NSString	*old = [path stringByAppendingPathComponent: file];
          NSArray       *lines;
          NSString      *line;
          int           opid;
          BOOL          isDir = NO;

          if ([mgr fileExistsAtPath: old isDirectory: &isDir] == NO
            || YES == isDir)
            {
              continue; // Ignore removed file or lock directory
            }
	  lines = [[NSString stringWithContentsOfFile: old]
            componentsSeparatedByString: @"\n"];
          if ([lines count] > 1
            && (opid = [(line = [lines objectAtIndex: 1]) intValue]) > 0)
            {
              if (YES == [line isEqual: pid])
                {
                  NSDebugMLLog(@"NSMessagePort", @"Removing old name %@", old);
                  [mgr removeFileAtPath: old handler: nil];
                }
              else if (NO == [NSProcessInfo _exists: opid])
                {
                  NSDebugMLLog(@"NSMessagePort",
                    @"Removing old name %@ for process %d", old, opid);
                  [mgr removeFileAtPath: old handler: nil];
                }
            }
          else
            {
              NSDebugMLLog(@"NSMessagePort", @"Removing bad name %@", old);
              [mgr removeFileAtPath: old handler: nil];
            }
	}
      [pool release];
    }
}

/**
 *  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;
}

+ (NSDistributedLock*) _fileLock
{
  NSDistributedLock	*dl;

  dl = [NSDistributedLock lockWithPath: [self _pathForName: nil]];
  if ([dl tryLock] == NO)
    {
      NSDate	*limit = [NSDate dateWithTimeIntervalSinceNow: 2.0];

      while (dl != nil && [dl tryLock] == NO)
	{
	  if ([limit timeIntervalSinceNow] > 0.0)
	    {
	      [NSThread sleepForTimeInterval: 0.1];
	    }
	  else
	    {
              if ([[dl lockDate] timeIntervalSinceNow] < -15.0)
                {
                  NS_DURING
                    {
                      [dl breakLock];
                    }
                  NS_HANDLER
                    {
                      NSLog(@"Failed to break lock on names for "
                        @"NSMessagePortNameServer: %@", localException);
                      dl = nil;
                    }
                  NS_ENDHANDLER
                }
              else
                {
                  NSLog(@"Failed to lock names for NSMessagePortNameServer");
                  dl = nil;
                }
	    }
	}
    }
  return dl;
}

/* Return the full path for the supplied port name or, if it's nil,
 * the path for the distributed lock protecting all names.
 */
+ (NSString *) _pathForName: (NSString *)name
{
  static NSString	*base_path = nil;
  NSString		*path;
  NSData		*data;

  if (name == nil)
    {
      name = @"lock";
    }
  else
    {
      /*
       * Make sure name is representable as a filename ... assume base64 encoded
       * strings are valid on all filesystems.
       */
      data = [name dataUsingEncoding: NSUTF8StringEncoding];
      data = [GSMimeDocument encodeBase64: data];
      name = [[NSString alloc] initWithData: data
				   encoding: NSASCIIStringEncoding];
      IF_NO_ARC([name autorelease];)
    }
  [serverLock lock];
  if (!base_path)
    {
      NSDictionary	*attr;

      if (nil == (path = NSTemporaryDirectory()))
        {
          [serverLock unlock];
          return nil;
        }

      attr = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: 0700]
                                         forKey: NSFilePosixPermissions];

      path = [path stringByAppendingPathComponent: @"NSMessagePort"];
      [[NSFileManager defaultManager] createDirectoryAtPath: path
                                withIntermediateDirectories: YES
                                                 attributes: attr
                                                      error: NULL];

      path = [path stringByAppendingPathComponent: @"names"];
      [[NSFileManager defaultManager] createDirectoryAtPath: path
                                withIntermediateDirectories: YES
                                                 attributes: attr
                                                      error: NULL];

      base_path = RETAIN(path);
    }
  else
    {
      path = base_path;
    }
  [serverLock unlock];

  path = [path stringByAppendingPathComponent: name];
  return path;
}


+ (BOOL) _livePort: (NSString *)path
{
  FILE	*f;
  char	socket_path[512];
  int	len;
  int	pid;
  struct stat sb;

  NSDebugLLog(@"NSMessagePort", @"_livePort: %@", path);

  f = fopen([path fileSystemRepresentation], "rt");
  if (!f)
    {
      NSDebugLLog(@"NSMessagePort", @"not live, couldn't open %@ (%m)", path);
      return NO;
    }

  if (fstat(fileno(f), &sb) < 0)
    {
      NSDebugLLog(@"NSMessagePort", @"not live, couldn't stat %@ (%m)", path);
      fclose(f);
      return NO;
    }
  if (sb.st_uid != getuid() && sb.st_uid != geteuid())
    {
      NSDebugLLog(@"NSMessagePort", @"not live, %@ not owned by us", path);
      fclose(f);
      return NO;
    }
  if ((sb.st_mode & 0777) != 0600)
    {
      NSDebugLLog(@"NSMessagePort", @"not live, %@ not correct access", path);
      fclose(f);
      return NO;
    }

  fgets(socket_path, sizeof(socket_path), f);
  len = strlen(socket_path);
  if (len == 0 || socket_path[len - 1] != '\n')
    {
      fclose(f);
      NSDebugLLog(@"NSMessagePort", @"not live, couldn't get file in %@", path);
      return NO;
    }
  socket_path[len - 1] = '\0';

  if (fscanf(f, "%i", &pid) != 1)
    {
      fclose(f);
      NSDebugLLog(@"NSMessagePort", @"not live, couldn't read PID in %@", path);
      return NO;
    }

  fclose(f);

  if (stat(socket_path, &sb) < 0)
    {
      unlink([path fileSystemRepresentation]);
      NSDebugLLog(@"NSMessagePort", @"not live, couldn't stat socket (%m)");
      return NO;
    }

  if (kill(pid, 0) < 0)
    {
      unlink([path fileSystemRepresentation]);
      unlink(socket_path);
      NSDebugLLog(@"NSMessagePort", @"not live, no such process (%m)");
      return NO;
    }
  else
    {
      struct sockaddr_un sockAddr;
      int desc;

      memset(&sockAddr, '\0', sizeof(sockAddr));
      sockAddr.sun_family = AF_LOCAL;
      strncpy(sockAddr.sun_path, socket_path, sizeof(sockAddr.sun_path) - 1);

      if ((desc = socket(PF_LOCAL, SOCK_STREAM, PF_UNSPEC)) < 0)
	{
	  unlink([path fileSystemRepresentation]);
	  unlink(socket_path);
	  NSDebugLLog(@"NSMessagePort",
	    @"couldn't create socket, assuming not live (%m)");
	  return NO;
	}
      if (connect(desc, (struct sockaddr*)&sockAddr, SUN_LEN(&sockAddr)) < 0)
	{
          close(desc);
	  unlink([path fileSystemRepresentation]);
	  unlink(socket_path);
	  NSDebugLLog(@"NSMessagePort", @"not live, can't connect (%m)");
	  return NO;
	}
      close(desc);
      NSDebugLLog(@"NSMessagePort", @"port is live");
      return YES;
    }
}

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

- (NSPort*) portForName: (NSString *)name
		 onHost: (NSString *)host
{
  NSDistributedLock	*dl;
  NSString		*path;
  FILE			*f;
  char			socket_path[512];

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

  if ([host length] > 0)
    {
      NSLog(@"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 nil or an empty string).  To contact processes "
	@"owned by other users or on other hosts you must use an instance "
	@"of the NSSocketPortNameServer class.");
      if (NO == [host isEqualToString: @"*"])
	{
          return nil;
        }
    }

  path = [[self class] _pathForName: name];
  if ((dl = [[self class] _fileLock]) == nil)
    {
      [NSException raise: NSGenericException
		  format: @"Failed to lock names for NSMessagePortNameServer"];
    }
  if (![[self class] _livePort: path])
    {
      [dl unlock];
      NSDebugLLog(@"NSMessagePort", @"not a live port");
      return nil;
    }

  f = fopen([path fileSystemRepresentation], "rt");
  if (!f)
    {
      [dl unlock];
      NSDebugLLog(@"NSMessagePort", @"can't open file (%m)");
      return nil;
    }

  fgets(socket_path, sizeof(socket_path), f);
  if (strlen(socket_path) > 0) socket_path[strlen(socket_path) - 1] = 0;
  fclose(f);

  NSDebugLLog(@"NSMessagePort", @"got %s", socket_path);
  [dl unlock];

  return [NSMessagePort _portWithName: (unsigned char*)socket_path
			     listener: NO];
}

- (BOOL) registerPort: (NSPort *)port
	      forName: (NSString *)name
{
  int			fd;
  unsigned char		buf[32];
  NSDistributedLock	*dl;
  NSString		*path;
  const unsigned char	*socket_name;
  NSMutableArray	*a;

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

  path = [[self class] _pathForName: name];
  if ((dl = [[self class] _fileLock]) == nil)
    {
      [NSException raise: NSGenericException
		  format: @"Failed to lock names for NSMessagePortNameServer"];
    }
  if ([[self class] _livePort: path])
    {
      [dl unlock];
      NSDebugLLog(@"NSMessagePort", @"fail, is a live port (%@)", name);
      return NO;
    }

  fd = open([path fileSystemRepresentation], O_CREAT|O_EXCL|O_WRONLY, 0600);
  if (fd < 0)
    {
      [dl unlock];
      NSDebugLLog(@"NSMessagePort", @"fail, can't open file (%@) for %@",
	path, name);
      return NO;
    }

  socket_name = [(NSMessagePort *)port _name];

  write(fd, (char*)socket_name, strlen((char*)socket_name));
  write(fd, "\n", 1);
  snprintf((char*)buf, sizeof(buf), "%i\n", getpid());
  write(fd, (char*)buf, strlen((char*)buf));

  close(fd);

  [serverLock lock];
  a = NSMapGet(portToNamesMap, port);
  if (!a)
    {
      a = [[NSMutableArray alloc] init];
      NSMapInsert(portToNamesMap, port, a);
      RELEASE(a);
    }

  name = [name copy];
  [a addObject: name];
  [name release];
  [serverLock unlock];
  [dl unlock];

  return YES;
}

- (BOOL) removePortForName: (NSString *)name
{
  NSDistributedLock	*dl;
  NSString		*path;

  NSDebugLLog(@"NSMessagePort", @"removePortForName: %@", name);
  path = [[self class] _pathForName: name];
  if ((dl = [[self class] _fileLock]) == nil)
    {
      [NSException raise: NSGenericException
		  format: @"Failed to lock names for NSMessagePortNameServer"];
    }
  unlink([path fileSystemRepresentation]);
  [dl unlock];
  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(@"NSMessagePort", @"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
{
  FILE			*f;
  char			socket_path[512];
  NSDistributedLock	*dl;
  NSString		*path;
  const unsigned char	*port_path;

  NSDebugLLog(@"NSMessagePort", @"removePort: %@  forName: %@", port, name);

  path = [[self class] _pathForName: name];
  if ((dl = [[self class] _fileLock]) == nil)
    {
      [NSException raise: NSGenericException
		  format: @"Failed to lock names for NSMessagePortNameServer"];
    }
  f = fopen([path fileSystemRepresentation], "rt");
  if (!f)
    {
      [dl unlock];
      return YES;
    }
  fgets(socket_path, sizeof(socket_path), f);
  if (strlen(socket_path) > 0)
    {
      socket_path[strlen(socket_path) - 1] = 0;
    }
  fclose(f);
  port_path = [(NSMessagePort *)port _name];
  if (!strcmp((char*)socket_path, (char*)port_path))
    {
      unlink([path fileSystemRepresentation]);
    }
  [dl unlock];
  return YES;
}

@end