markd2/Hijacker

No Data returned

anonymouz4 opened this issue · 1 comments

The Pipe works, so if I would read it with

char str;
while (read(self->_pipe[kReadSide], &str, 1) > 0) {
	fprintf(stderr, "%c", str);
}

it works, but when used with CFSocketCreateWithNative(), it calls the selected callback with empty Data

Anyways, I fixed it this way:

// Monitor the reading side of the pipe.
NSFileHandle *wrapped_fh = [NSFileHandle.alloc initWithFileDescriptor: _pipe[kReadSide]];
[wrapped_fh waitForDataInBackgroundAndNotify];
	
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:wrapped_fh];

`+

- (void)receivedData:(NSNotification *)notif {
    NSFileHandle *fh = notif.object;
    NSData *data = fh.availableData;
    if (data.length > 0) { // if data is found, re-register for more data (and print)
	[fh waitForDataInBackgroundAndNotify];
	NSString *str = [NSString.alloc initWithData:data encoding:NSUTF8StringEncoding];
	[self notifyString:str];
    }
}

–––––––
EDIT:
Should be even better:

// Monitor the reading side of the pipe.
NSFileHandle *wrapped_fh = [NSFileHandle.alloc initWithFileDescriptor: _pipe[kReadSide]];
[wrapped_fh waitForDataInBackgroundAndNotify];

wrapped_fh.readabilityHandler = ^(NSFileHandle * _Nonnull fh) {
	NSData *data = fh.availableData;
	if (data.length > 0) { // if data is found, re-register for more data (and print)
		[fh waitForDataInBackgroundAndNotify];
		NSString *str = [NSString.alloc initWithData:data encoding:NSUTF8StringEncoding];
		dispatch_async(dispatch_get_main_queue(), ^{
			[self notifyString:str];
		});
	}
};