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