cog/Plugins/HTTPSource/HTTPSource.m

141 lines
2.5 KiB
Matlab
Raw Normal View History

//
// HTTPSource.m
// HTTPSource
//
// Created by Vincent Spader on 3/1/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//
#import "HTTPSource.h"
@implementation HTTPSource
- (BOOL)buffered
{
return NO;
}
- (BOOL)open:(NSURL *)url
{
[self setURL:url];
unsigned int port = [[url port] unsignedIntValue];
if (!port)
port = 80;
_socket = [[Socket alloc] initWithHost:[url host] port:port];
if (_socket) {
NSData *request = [[NSString stringWithFormat:@"GET %@ HTTP/1.0\nHOST: %@\n\n",[url path],[url host]] dataUsingEncoding:NSUTF8StringEncoding];
[_socket send:(void *)[request bytes] amount:[request length]];
2007-03-04 00:17:05 +00:00
pastHeader = NO;
}
return (_socket != nil);
}
- (NSDictionary *)properties
{
return nil;
}
- (BOOL)seekable
{
return NO;
}
- (BOOL)seek:(long)position whence:(int)whence
{
return NO;
}
- (long)tell
{
return byteCount;
}
- (int)read:(void *)buffer amount:(int)amount
{
2007-03-04 00:17:05 +00:00
if (!pastHeader) {
const int delimeter_size = 4; //\r\n\r\n
FILE *testFout = fopen("header.raw", "w");
int l = [_socket receive:buffer amount:amount];
uint8_t *f;
while(NULL == (f = (uint8_t *)strnstr((const char *)buffer, "\r\n\r\n", l))) {
fwrite(buffer, 1,l, testFout);
//Need to check for boundary conditions
memmove(buffer, (uint8_t *)buffer + (l - delimeter_size), delimeter_size);
l = delimeter_size + [_socket receive:((uint8_t *)buffer + delimeter_size) amount:(amount - delimeter_size)];
2007-03-04 00:17:05 +00:00
}
pastHeader = YES;
uint8_t *bufferOffset = f + delimeter_size;
uint8_t *bufferEnd = (uint8_t *)buffer + l;
int amountRemaining = bufferEnd - bufferOffset;
//For testing only
fwrite(buffer, 1, bufferOffset - (uint8_t *)buffer, testFout);
fclose(testFout);
testFout = fopen("test.raw", "w");
fwrite(bufferOffset, 1, amountRemaining, testFout);
fclose(testFout);
memmove(buffer,bufferOffset, amountRemaining);
return amountRemaining + [self read:((uint8_t *)buffer + amountRemaining) amount:(amount - amountRemaining)];
}
else {
int l = [_socket receive:buffer amount:amount];
//FOR TESTING ONLY
FILE *testFout = fopen("test.raw", "a");
fwrite(buffer, 1, l, testFout);
fclose(testFout);
if (l > 0)
byteCount += l;
return l;
2007-03-04 00:17:05 +00:00
}
}
- (void)close
{
[_socket close];
}
- (void)dealloc
{
[_socket release];
[_url release];
[super dealloc];
}
- (NSURL *)url
{
return _url;
}
- (void)setURL:(NSURL *)url
{
[url retain];
[_url release];
_url = url;
}
+ (NSArray *)schemes
{
return [NSArray arrayWithObject:@"http"];
}
@end