forked from lukhnos/objectiveflickr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLFHTTPRequest.m
782 lines (648 loc) · 24.6 KB
/
LFHTTPRequest.m
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//
// LFHTTPRequest.m
//
// Copyright (c) 2007-2009 Lithoglyph Inc. (http://lithoglyph.com)
// Copyright (c) 2007-2009 Lukhnos D. Liu (http://lukhnos.org)
//
// 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 <SystemConfiguration/SystemConfiguration.h>
#import "LFHTTPRequest.h"
// these typedefs are for this compilation unit only
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
typedef unsigned int NSUInteger;
typedef int NSInteger;
#define NSUIntegerMax UINT_MAX
#endif
NSString *const LFHTTPRequestConnectionError = @"HTTP request connection lost";
NSString *const LFHTTPRequestTimeoutError = @"HTTP request timeout";
const NSTimeInterval LFHTTPRequestDefaultTimeoutInterval = 10.0;
NSString *const LFHTTPRequestWWWFormURLEncodedContentType = @"application/x-www-form-urlencoded";
NSString *const LFHTTPRequestGETMethod = @"GET";
NSString *const LFHTTPRequestHEADMethod = @"HEAD";
NSString *const LFHTTPRequestPOSTMethod = @"POST";
// internal defaults
NSString *const LFHRDefaultUserAgent = nil;
const size_t LFHTTPRequestDefaultReadBufferSize = 16384;
const NSTimeInterval LFHTTPRequestDefaultTrackerFireInterval = 1.0;
void LFHRReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo);
@interface LFHTTPRequest (PrivateMethods)
- (void)cleanUp;
- (void)dealloc;
- (void)handleTimeout;
- (void)handleRequestMessageBodyTrackerTick:(NSTimer *)timer;
- (void)handleReceivedDataTrackerTick:(NSTimer *)timer;
- (void)readStreamHasBytesAvailable;
- (void)readStreamErrorOccurred;
- (void)readStreamEndEncountered;
@end
@implementation LFHTTPRequest (PrivateMethods)
- (void)cleanUp
{
if (_readStream) {
CFReadStreamUnscheduleFromRunLoop(_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFReadStreamClose(_readStream);
CFRelease(_readStream);
_readStream = NULL;
}
if (_receivedDataTracker) {
[_receivedDataTracker invalidate];
[_receivedDataTracker release];
_receivedDataTracker = nil;
}
if (_requestMessageBodyTracker) {
[_requestMessageBodyTracker invalidate];
[_requestMessageBodyTracker release];
_requestMessageBodyTracker = nil;
}
_requestMessageBodySize = 0;
_expectedDataLength = NSUIntegerMax;
_lastReceivedDataUpdateTime = 0.0;
_lastReceivedBytes = 0;
_lastSentDataUpdateTime = 0.0;
_lastSentBytes = 0;
}
- (void)dealloc
{
[self cleanUp];
[_userAgent release];
[_contentType release];
[_requestHeader release];
[_receivedData release];
[_receivedContentType release];
[_sessionInfo release];
_sessionInfo = nil;
free(_readBuffer);
[super dealloc];
}
- (void)finalize
{
[self cleanUp];
if (_readBuffer) {
free(_readBuffer);
_readBuffer = NULL;
}
[super finalize];
}
- (void)_exitRunLoop
{
#if TARGET_OS_IPHONE
[_synchronousMessagePort sendBeforeDate:[NSDate date] msgid:0 components:nil from:_synchronousMessagePort reserved:0];
#else
NSPortMessage *message = [[[NSPortMessage alloc] initWithSendPort:_synchronousMessagePort receivePort:_synchronousMessagePort components:nil] autorelease];
[message setMsgid:0];
[message sendBeforeDate:[NSDate date]];
#endif
}
- (void)handleTimeout
{
if (_shouldWaitUntilDone) {
[self _exitRunLoop];
}
[self cleanUp];
if ([_delegate respondsToSelector:@selector(httpRequest:didFailWithError:)]) {
[_delegate httpRequest:self didFailWithError:LFHTTPRequestTimeoutError];
}
}
- (void)handleRequestMessageBodyTrackerTick:(NSTimer *)timer
{
if (timer != _requestMessageBodyTracker) {
return;
}
// get the number of sent bytes
CFTypeRef sentBytesObject = CFReadStreamCopyProperty(_readStream, kCFStreamPropertyHTTPRequestBytesWrittenCount);
if (!sentBytesObject) {
// or should we send an error message?
return;
}
NSInteger signedSentBytes = 0;
CFNumberGetValue(sentBytesObject, kCFNumberCFIndexType, &signedSentBytes);
CFRelease(sentBytesObject);
if (signedSentBytes < 0) {
// or should we send an error message?
return;
}
// interestingly, this logic also works when ALL REQUEST MESSAGE BODY IS SENT
NSUInteger sentBytes = (NSUInteger)signedSentBytes;
if (sentBytes > _lastSentBytes) {
_lastSentBytes = sentBytes;
_lastSentDataUpdateTime = [NSDate timeIntervalSinceReferenceDate];
if ([_delegate respondsToSelector:@selector(httpRequest:sentBytes:total:)]) {
[_delegate httpRequest:self sentBytes:_lastSentBytes total:_requestMessageBodySize];
}
return;
}
if ([NSDate timeIntervalSinceReferenceDate] - _lastSentDataUpdateTime > _timeoutInterval) {
// remove ourselve from the runloop
[_requestMessageBodyTracker invalidate];
[self handleTimeout];
}
}
- (void)handleReceivedDataTrackerTick:(NSTimer *)timer
{
if (timer != _receivedDataTracker) {
return;
}
if ([NSDate timeIntervalSinceReferenceDate] - _lastReceivedDataUpdateTime > _timeoutInterval) {
// remove ourselves from the runloop
[_receivedDataTracker invalidate];
[self handleTimeout];
}
}
- (void)readStreamHasBytesAvailable
{
// to prevent from stray callbacks entering here
if (![self isRunning]) {
return;
}
if (!_receivedDataTracker) {
// self can be retained only by the timer (_requestMessageBodyTracker) so self can be deallocated while calling [_requestMessageBodyTracker invalidate]
// to avoid this problem:
[[self retain] autorelease];
// update one last time the total sent bytes
if ([_delegate respondsToSelector:@selector(httpRequest:sentBytes:total:)]) {
[_delegate httpRequest:self sentBytes:_lastSentBytes total:_lastSentBytes];
}
// stops _requestMessageBodyTracker
[_requestMessageBodyTracker invalidate];
[_requestMessageBodyTracker release];
_requestMessageBodyTracker = nil;
NSUInteger statusCode = 0;
CFURLRef finalURL = CFReadStreamCopyProperty(_readStream, kCFStreamPropertyHTTPFinalURL);
CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(_readStream, kCFStreamPropertyHTTPResponseHeader);
if (response) {
statusCode = (NSUInteger)CFHTTPMessageGetResponseStatusCode(response);
CFStringRef contentLengthString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Length"));
if (contentLengthString) {
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
_expectedDataLength = [(NSString *)contentLengthString intValue];
#else
if ([(NSString *)contentLengthString respondsToSelector:@selector(integerValue)]) {
_expectedDataLength = [(NSString *)contentLengthString integerValue];
}
else {
_expectedDataLength = [(NSString *)contentLengthString intValue];
}
#endif
CFRelease(contentLengthString);
}
[_receivedContentType release];
_receivedContentType = nil;
CFStringRef contentTypeString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Type"));
if (contentTypeString) {
_receivedContentType = [(NSString *)contentTypeString copy];
CFRelease(contentTypeString);
}
}
CFReadStreamRef presentReadStream = _readStream;
if ([_delegate respondsToSelector:@selector(httpRequest:didReceiveStatusCode:URL:responseHeader:)]) {
[_delegate httpRequest:self didReceiveStatusCode:statusCode URL:(NSURL *)finalURL responseHeader:response];
}
if (finalURL) {
CFRelease(finalURL);
}
if (response) {
CFRelease(response);
}
// better to see if we're still running... (we might be canceled by the delegate's httpRequest:didReceiveStatusCode:URL:responseHeader: !)
if (presentReadStream != _readStream) {
return;
}
// start tracking received bytes
_lastReceivedBytes = 0;
_lastReceivedDataUpdateTime = [NSDate timeIntervalSinceReferenceDate];
// now we fire _receivedDataTracker
_receivedDataTracker = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:LFHTTPRequestDefaultTrackerFireInterval target:self selector:@selector(handleReceivedDataTrackerTick:) userInfo:nil repeats:YES];
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
// this is 10.5 only
[[NSRunLoop currentRunLoop] addTimer:_receivedDataTracker forMode:NSRunLoopCommonModes];
#endif
[[NSRunLoop currentRunLoop] addTimer:_receivedDataTracker forMode:NSDefaultRunLoopMode];
// These two are defined in the AppKit, not in the Foundation
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
extern NSString *NSModalPanelRunLoopMode;
extern NSString *NSEventTrackingRunLoopMode;
[[NSRunLoop currentRunLoop] addTimer:_receivedDataTracker forMode:NSEventTrackingRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:_receivedDataTracker forMode:NSModalPanelRunLoopMode];
#endif
}
// sets a 25,600-byte block, approximately for 256 KBPS connection
CFIndex bytesRead = CFReadStreamRead(_readStream, _readBuffer, _readBufferSize);
if (bytesRead > 0) {
if ([_delegate respondsToSelector:@selector(httpRequest:writeReceivedBytes:size:expectedTotal:)]) {
[_delegate httpRequest:self writeReceivedBytes:_readBuffer size:bytesRead expectedTotal:_expectedDataLength];
_lastReceivedBytes += bytesRead;
_lastReceivedDataUpdateTime = [NSDate timeIntervalSinceReferenceDate];
}
else {
[_receivedData appendBytes:_readBuffer length:bytesRead];
_lastReceivedBytes = [_receivedData length];
_lastReceivedDataUpdateTime = [NSDate timeIntervalSinceReferenceDate];
if ([_delegate respondsToSelector:@selector(httpRequest:receivedBytes:expectedTotal:)]) {
[_delegate httpRequest:self receivedBytes:_lastReceivedBytes expectedTotal:_expectedDataLength];
}
}
}
}
- (void)readStreamEndEncountered
{
// to prevent from stray callbacks entering here
if (![self isRunning]) {
return;
}
// if no byte read, we need to present the header at least again, because readStreamHasBytesAvailable is never called
if (![_receivedData length] && ![_delegate respondsToSelector:@selector(httpRequest:writeReceivedBytes:size:expectedTotal:)]) {
if ([_delegate respondsToSelector:@selector(httpRequest:sentBytes:total:)]) {
[_delegate httpRequest:self sentBytes:_lastSentBytes total:_lastSentBytes];
}
// stops _requestMessageBodyTracker
[_requestMessageBodyTracker invalidate];
[_requestMessageBodyTracker release];
_requestMessageBodyTracker = nil;
NSUInteger statusCode = 0;
CFURLRef finalURL = CFReadStreamCopyProperty(_readStream, kCFStreamPropertyHTTPFinalURL);
CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(_readStream, kCFStreamPropertyHTTPResponseHeader);
if (response) {
statusCode = (NSUInteger)CFHTTPMessageGetResponseStatusCode(response);
CFStringRef contentLengthString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Length"));
if (contentLengthString) {
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
_expectedDataLength = [(NSString *)contentLengthString intValue];
#else
if ([(NSString *)contentLengthString respondsToSelector:@selector(integerValue)]) {
_expectedDataLength = [(NSString *)contentLengthString integerValue];
}
else {
_expectedDataLength = [(NSString *)contentLengthString intValue];
}
#endif
CFRelease(contentLengthString);
}
[_receivedContentType release];
_receivedContentType = nil;
CFStringRef contentTypeString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Type"));
if (contentTypeString) {
_receivedContentType = [(NSString *)contentTypeString copy];
CFRelease(contentTypeString);
}
}
if ([_delegate respondsToSelector:@selector(httpRequest:didReceiveStatusCode:URL:responseHeader:)]) {
[_delegate httpRequest:self didReceiveStatusCode:statusCode URL:(NSURL *)finalURL responseHeader:response];
}
if (finalURL) {
CFRelease(finalURL);
}
if (response) {
CFRelease(response);
}
}
[self cleanUp];
if ([_delegate respondsToSelector:@selector(httpRequestDidComplete:)]) {
[_delegate httpRequestDidComplete:self];
}
}
- (void)readStreamErrorOccurred
{
// to prevent from stray callbacks entering here
if (![self isRunning]) {
return;
}
[self cleanUp];
if ([_delegate respondsToSelector:@selector(httpRequest:didFailWithError:)]) {
[_delegate httpRequest:self didFailWithError:LFHTTPRequestConnectionError];
}
}
@end
@implementation LFHTTPRequest
- (id)init
{
if ((self = [super init])) {
_timeoutInterval = LFHTTPRequestDefaultTimeoutInterval;
_receivedData = [NSMutableData new];
_expectedDataLength = NSUIntegerMax;
_readBufferSize = LFHTTPRequestDefaultReadBufferSize;
_readBuffer = calloc(1, _readBufferSize);
NSAssert(_readBuffer, @"Must have enough memory for _readBuffer");
}
return self;
}
- (BOOL)isRunning
{
return !!_readStream;
}
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
- (BOOL)_performMethod:(NSString *)methodName onURL:(NSURL *)url withData:(NSData *)data orWithInputStream:(NSInputStream *)inputStream knownContentSize:(NSUInteger)byteStreamSize
#else
- (BOOL)_performMethod:(NSString *)methodName onURL:(NSURL *)url withData:(NSData *)data orWithInputStream:(NSInputStream *)inputStream knownContentSize:(unsigned int)byteStreamSize
#endif
{
if (!url) {
return NO;
}
if (_readStream) {
return NO;
}
CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, (CFStringRef)methodName, (CFURLRef)url, kCFHTTPVersion1_1);
if (!request) {
return NO;
}
// combine the header
NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];
if (_userAgent) {
[headerDictionary setObject:_userAgent forKey:@"User-Agent"];
}
if (_contentType) {
[headerDictionary setObject:_contentType forKey:@"Content-Type"];
}
if (inputStream) {
if (byteStreamSize && byteStreamSize != NSUIntegerMax) {
[headerDictionary setObject:[NSString stringWithFormat:@"%ju", (uintmax_t)byteStreamSize] forKey:@"Content-Length"];
_requestMessageBodySize = byteStreamSize;
}
else {
_requestMessageBodySize = NSUIntegerMax;
}
}
else {
if ([data length]) {
[headerDictionary setObject:[NSString stringWithFormat:@"%ju", (uintmax_t)[data length]] forKey:@"Content-Length"];
}
_requestMessageBodySize = [data length];
}
if (_requestHeader) {
[headerDictionary addEntriesFromDictionary:_requestHeader];
}
NSEnumerator *dictEnumerator = [headerDictionary keyEnumerator];
id key;
while ((key = [dictEnumerator nextObject])) {
CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)[key description], (CFStringRef)[headerDictionary objectForKey:key]);
}
if (!inputStream && data) {
CFHTTPMessageSetBody(request, (CFDataRef)data);
}
CFReadStreamRef tmpReadStream;
if (inputStream) {
tmpReadStream = CFReadStreamCreateForStreamedHTTPRequest(NULL, request, (CFReadStreamRef)inputStream);
}
else {
tmpReadStream = CFReadStreamCreateForHTTPRequest(NULL, request);
}
CFRelease(request);
if (!tmpReadStream) {
return NO;
}
CFReadStreamSetProperty(tmpReadStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue);
// apply current proxy settings
#if !TARGET_OS_IPHONE
CFDictionaryRef proxyDict = SCDynamicStoreCopyProxies(NULL); // kCFNetworkProxiesHTTPProxy
#else
CFDictionaryRef proxyDict = CFNetworkCopySystemProxySettings();
#endif
if (proxyDict) {
CFReadStreamSetProperty(tmpReadStream, kCFStreamPropertyHTTPProxy, proxyDict);
CFRelease(proxyDict);
}
CFStreamClientContext streamContext;
streamContext.version = 0;
streamContext.info = self;
streamContext.retain = 0;
streamContext.release = 0;
streamContext.copyDescription = 0;
CFOptionFlags eventFlags = kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
// open the stream with callback function
if (!CFReadStreamSetClient(tmpReadStream, eventFlags, LFHRReadStreamClientCallBack, &streamContext))
{
CFRelease(tmpReadStream);
return NO;
}
// detach and release the previous data buffer
if ([_receivedData length]) {
NSMutableData *tmp = _receivedData;
_receivedData = [NSMutableData new];
[tmp release];
}
CFReadStreamScheduleWithRunLoop(tmpReadStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
// we need to assign this in advance, because the callback might be called anytime between this and the next statement
_readStream = tmpReadStream;
_expectedDataLength = NSUIntegerMax;
// open the stream
Boolean result = CFReadStreamOpen(tmpReadStream);
if (!result) {
CFReadStreamUnscheduleFromRunLoop(tmpReadStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFRelease(tmpReadStream);
_readStream = NULL;
return NO;
}
_lastSentBytes = 0;
_lastSentDataUpdateTime = [NSDate timeIntervalSinceReferenceDate];
// we create _requestMessageBodyTracker (timer for tracking sent data) first
_requestMessageBodyTracker = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:LFHTTPRequestDefaultTrackerFireInterval target:self selector:@selector(handleRequestMessageBodyTrackerTick:) userInfo:nil repeats:YES];
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
// this is 10.5 only
[[NSRunLoop currentRunLoop] addTimer:_requestMessageBodyTracker forMode:NSRunLoopCommonModes];
#endif
[[NSRunLoop currentRunLoop] addTimer:_requestMessageBodyTracker forMode:NSDefaultRunLoopMode];
// These two are defined in the AppKit, not in the Foundation
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
extern NSString *NSModalPanelRunLoopMode;
extern NSString *NSEventTrackingRunLoopMode;
[[NSRunLoop currentRunLoop] addTimer:_requestMessageBodyTracker forMode:NSEventTrackingRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:_requestMessageBodyTracker forMode:NSModalPanelRunLoopMode];
#endif
if (_shouldWaitUntilDone) {
NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
NSString *currentMode = [currentRunLoop currentMode];
if (![currentMode length]) {
currentMode = NSDefaultRunLoopMode;
}
BOOL isReentrant = (_synchronousMessagePort != nil);
if (!isReentrant) {
_synchronousMessagePort = (NSMessagePort *)[[NSPort port] retain];
[currentRunLoop addPort:_synchronousMessagePort forMode:currentMode];
}
while ([self isRunning]) {
[currentRunLoop runMode:currentMode beforeDate:[NSDate distantFuture]];
}
if (!isReentrant) {
[currentRunLoop removePort:_synchronousMessagePort forMode:currentMode];
[_synchronousMessagePort release];
_synchronousMessagePort = nil;
}
else {
// sends another message to exit the runloop
[self _exitRunLoop];
}
}
return YES;
}
- (BOOL)performMethod:(NSString *)methodName onURL:(NSURL *)url withData:(NSData *)data
{
return [self _performMethod:methodName onURL:url withData:data orWithInputStream:nil knownContentSize:0];
}
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4
- (BOOL)performMethod:(NSString *)methodName onURL:(NSURL *)url withInputStream:(NSInputStream *)inputStream knownContentSize:(NSUInteger)byteStreamSize
#else
- (BOOL)performMethod:(NSString *)methodName onURL:(NSURL *)url withInputStream:(NSInputStream *)inputStream knownContentSize:(unsigned int)byteStreamSize
#endif
{
return [self _performMethod:methodName onURL:url withData:nil orWithInputStream:inputStream knownContentSize:byteStreamSize];
}
- (void)cancel
{
[self cancelWithoutDelegateMessage];
if ([_delegate respondsToSelector:@selector(httpRequestDidCancel:)]) {
[_delegate httpRequestDidCancel:self];
}
}
- (void)cancelWithoutDelegateMessage
{
[self cleanUp];
}
- (NSData *)getReceivedDataAndDetachFromRequest
{
NSData *returnedData = [_receivedData autorelease];
_receivedData = [NSMutableData new];
[_receivedContentType release];
_receivedContentType = nil;
return returnedData;
}
- (NSDictionary *)requestHeader
{
return [[_requestHeader copy] autorelease];
}
- (void)setRequestHeader:(NSDictionary *)requestHeader
{
if (![_requestHeader isEqualToDictionary:requestHeader]) {
NSDictionary *tmp = _requestHeader;
_requestHeader = [requestHeader copy];
[tmp release];
}
}
- (NSTimeInterval)timeoutInterval
{
return _timeoutInterval;
}
- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval
{
if (_timeoutInterval != timeoutInterval) {
_timeoutInterval = timeoutInterval;
}
}
- (NSString *)userAgent
{
return [[_userAgent copy] autorelease];
}
- (void)setUserAgent:(NSString *)userAgent
{
if ([_userAgent isEqualToString:userAgent]) {
return;
}
NSString *tmp = _userAgent;
_userAgent = [userAgent copy];
[tmp release];
}
- (NSString *)contentType
{
return [[_contentType copy] autorelease];
}
- (void)setContentType:(NSString *)contentType
{
if ([_contentType isEqualToString:contentType]) {
return;
}
NSString *tmp = _contentType;
_contentType = [contentType copy];
[tmp release];
}
- (NSData *)receivedData
{
return [[_receivedData retain] autorelease];
}
- (NSString *)receivedContentType
{
return [[_receivedContentType copy] autorelease];
}
- (NSUInteger)expectedDataLength
{
return _expectedDataLength;
}
- (id)delegate
{
return _delegate;
}
- (void)setDelegate:(id)delegate
{
if (delegate != _delegate) {
_delegate = delegate;
}
}
- (void)setSessionInfo:(id)aSessionInfo
{
id tmp = _sessionInfo;
_sessionInfo = [aSessionInfo retain];
[tmp release];
}
- (id)sessionInfo
{
return [[_sessionInfo retain] autorelease];
}
- (size_t)readBufferSize
{
return _readBufferSize;
}
- (void)setReadBufferSize:(size_t)newSize
{
NSAssert(![self isRunning], @"Cannot set read buffer size while the request is running");
NSAssert(newSize, @"Read buffer size must > 0");
_readBufferSize = newSize;
_readBuffer = realloc(_readBuffer, newSize);
NSAssert(_readBuffer, @"Must have enough memory for reallocing _readBuffer");
bzero(_readBuffer, newSize);
}
- (BOOL)shouldWaitUntilDone
{
return _shouldWaitUntilDone;
}
- (void)setShouldWaitUntilDone:(BOOL)waitUntilDone
{
_shouldWaitUntilDone = waitUntilDone;
}
@end
void LFHRReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo)
{
id pool = [NSAutoreleasePool new];
LFHTTPRequest *request = (LFHTTPRequest *)clientCallBackInfo;
switch (eventType) {
case kCFStreamEventHasBytesAvailable:
[request readStreamHasBytesAvailable];
break;
case kCFStreamEventEndEncountered:
[request readStreamEndEncountered];
break;
case kCFStreamEventErrorOccurred:
[request readStreamErrorOccurred];
break;
default:
break;
}
[pool drain];
}