File: NetConnection.m

package info (click to toggle)
gridlock.app 1.10-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,556 kB
  • sloc: objc: 10,334; ansic: 669; makefile: 12
file content (162 lines) | stat: -rw-r--r-- 6,123 bytes parent folder | download | duplicates (7)
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
/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#import "NetConnection.h"

// prevent hostile clients from sending arbitrarily large data by limiting length header to 5 chars
static int MAX_PLIST_LENGTH_CHARS = 5;

@implementation NetConnection

-(id)init {
  [super init];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(gotData:)
                                               name:NSFileHandleReadCompletionNotification
                                             object:nil];
  buffer = [[NSMutableData alloc] init];
  return self;
}

+(NetConnection *)connectionWithSocket:(NSFileHandle *)sock {
  // for some reason, the autorelease pool doesn't get cleared in a reasonable amount of time
  // so we schedule a release manually
  NetConnection *conn = [[NetConnection alloc] init];
  [conn setSocket:sock];
  [conn performSelector:@selector(release) withObject:nil afterDelay:0.0];
  return conn;
}

boolAccessor(isDisconnected, setIsDisconnected)
boolAccessor(isDeallocating, setIsDeallocating)
idAccessor(remoteUsername, setRemoteUsername)

-(void)release {
  [super release];
}

-(void)dealloc {
  [self setIsDeallocating:YES];
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  if (![self isDisconnected]) [self sendDisconnect];
  
  [self setSocket:nil];
  [buffer release];

  [super dealloc];
}

-(void)setSocket:(NSFileHandle *)fh {
  if (socket!=fh) {
    id oldsocket = socket;
    socket = [fh retain];
    //[oldsocket closeFile];
    [oldsocket release];
    [buffer setLength:0];
    incomingPlistLength = 0;
    [socket readInBackgroundAndNotify];
  }
}
-(NSFileHandle *)socket {
  return socket;
}

-(NSString *)remoteIPAddress {
  return [[self socket] remoteAddress];
}

-(BOOL)processBuffer {
  //NSLog(@"NetConnection processBuffer:%@", [[[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding] autorelease]);
  if (incomingPlistLength<=0) {
    // look for a colon and get the length from the preceding bytes
    char ch;
    int index = 0;
    BOOL found = NO;
    while (!found && index<[buffer length] && index<MAX_PLIST_LENGTH_CHARS) {
      [buffer getBytes:&ch range:NSMakeRange(index, 1)];
      if (ch==':') {
        NSData *lengthData = [buffer subdataWithRange:NSMakeRange(0,index)];
        NSString *lengthStr = [[[NSString alloc] initWithData:lengthData encoding:NSUTF8StringEncoding] autorelease];
        incomingPlistLength = [lengthStr intValue];
        if (incomingPlistLength>0) {
          // remove the length field so we're left with just the data
          [buffer replaceBytesInRange:NSMakeRange(0,index+1) withBytes:NULL length:0];
          found = YES;
          //NSLog(@"Read plist length:%d", incomingPlistLength);
        }
      }
      else {
        index++;
        if (index>=MAX_PLIST_LENGTH_CHARS) {
          NSLog(@"Failed to read plist length, terminating connection");
          return NO;
        }
      }
    }
  }
  if (incomingPlistLength>0 && incomingPlistLength<=[buffer length]) {
    // extract plist from buffer
    NSData *bufferData = [buffer subdataWithRange:NSMakeRange(0,incomingPlistLength)];
    NSString *plistStr = [[[NSString alloc] initWithData:bufferData encoding:NSUTF8StringEncoding] autorelease];
    id plist = [plistStr propertyList];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"NetConnectionReadPropertyListNotification" object:self userInfo:[NSDictionary dictionaryWithObject:plist forKey:@"plist"]];

    [buffer replaceBytesInRange:NSMakeRange(0,incomingPlistLength) withBytes:NULL length:0];
    incomingPlistLength = 0;
    if ([buffer length]>0) {
      // we have data left over, call this method again
      return [self processBuffer];
    }
  }
  return YES;
}

-(void)sendDisconnectNotification {
  if ([self isDeallocating]) return;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"NetConnectionTerminatedNotification" object:self userInfo:nil];
  
}

-(void)transmitPropertyList:(id)plist {
  NSString *plistString = [plist description];
  NSString *stringToSend = [NSString stringWithFormat:@"%d:%@", [plistString length], plistString];
  NSData *dataToSend = [stringToSend dataUsingEncoding:NSUTF8StringEncoding];
  [[self socket] writeData:dataToSend];
}

-(void)gotData:(NSNotification *)notification {
  if ([self isDeallocating]) return;
  if ([self socket]==[notification object]) {
    NSData *data = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
    if ([data length]>0) {
      [buffer appendData:data];
      if ([self processBuffer]) {
        [[self socket] readInBackgroundAndNotify];
      }
      else {
        [self sendDisconnect];
      }
    }
    else {
      //NSLog(@"Connection terminated");
      [self sendDisconnectNotification];
    }
  }
}

-(void)sendDisconnect {
  NSDictionary *dict = [NSDictionary dictionaryWithObject:@"1" forKey:@"disconnect"];
  [self transmitPropertyList:dict];
  [self setIsDisconnected:YES];
  [self sendDisconnectNotification];
}

@end