aboutsummaryrefslogtreecommitdiff
path: root/Foundation/GTMHTTPFetcher.m
blob: cac49dfc48737127b185719f99836feb09790aa1 (plain)
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
//
//  GTMHTTPFetcher.m
//
//  Copyright 2007-2008 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
// 
//  http://www.apache.org/licenses/LICENSE-2.0
// 
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#define GTMHTTPFETCHER_DEFINE_GLOBALS 1

#import "GTMHTTPFetcher.h"
#import "GTMDebugSelectorValidation.h"

@interface GTMHTTPFetcher (GTMHTTPFetcherLoggingInternal)
- (void)logFetchWithError:(NSError *)error;
- (void)logCapturePostStream;
@end

// Make sure that if logging is disabled, the InputStream logging is also
// diabled.
#if !GTM_HTTPFETCHER_ENABLE_LOGGING
# undef  GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
# define GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING 0
#endif // GTM_HTTPFETCHER_ENABLE_LOGGING

#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
#import "GTMProgressMonitorInputStream.h"
@interface GTMInputStreamLogger : GTMProgressMonitorInputStream
// GTMInputStreamLogger wraps any NSInputStream used for uploading so we can
// capture a copy of the data for the log
@end
#endif // !GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING

#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
@interface NSURLConnection (LeopardMethodsOnTigerBuilds)
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (void)start;
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
@end
#endif

NSString* const kGTMLastModifiedHeader = @"Last-Modified";
NSString* const kGTMIfModifiedSinceHeader = @"If-Modified-Since";


NSMutableArray* gGTMFetcherStaticCookies = nil;
Class gGTMFetcherConnectionClass = nil;
NSArray *gGTMFetcherDefaultRunLoopModes = nil;

const NSTimeInterval kDefaultMaxRetryInterval = 60. * 10.; // 10 minutes
                   
@interface GTMHTTPFetcher (PrivateMethods)
- (void)setCookies:(NSArray *)newCookies
           inArray:(NSMutableArray *)cookieStorageArray;
- (NSArray *)cookiesForURL:(NSURL *)theURL inArray:(NSMutableArray *)cookieStorageArray;
- (void)handleCookiesForResponse:(NSURLResponse *)response;
- (BOOL)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error;
- (void)retryTimerFired:(NSTimer *)timer;
- (void)destroyRetryTimer;
- (void)beginRetryTimer;
- (void)primeTimerWithNewTimeInterval:(NSTimeInterval)secs;
- (void)retryFetch;
@end

@implementation GTMHTTPFetcher

+ (GTMHTTPFetcher *)httpFetcherWithRequest:(NSURLRequest *)request {
  return [[[GTMHTTPFetcher alloc] initWithRequest:request] autorelease];
}

+ (void)initialize {
  if (!gGTMFetcherStaticCookies) {
    gGTMFetcherStaticCookies = [[NSMutableArray alloc] init];
  }
}

- (id)init {
  return [self initWithRequest:nil];
}

- (id)initWithRequest:(NSURLRequest *)request {
  if ((self = [super init]) != nil) {

    request_ = [request mutableCopy];
    
    [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic];        
  }
  return self;
}

// TODO: do we need finalize to call stopFetching?

- (void)dealloc {
  [self stopFetching]; // releases connection_

  [request_ release];
  [downloadedData_ release];
  [credential_ release];
  [proxyCredential_ release];
  [postData_ release];
  [postStream_ release];
  [loggedStreamData_ release];
  [response_ release];
  [userData_ release];
  [runLoopModes_ release];
  [fetchHistory_ release];
  [self destroyRetryTimer];
  
  [super dealloc];
}

#pragma mark -

// Begin fetching the URL.  |delegate| is not retained
// The delegate must provide and implement the finished and failed selectors.
//
// finishedSEL has a signature like:
//   - (void)fetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data
// failedSEL has a signature like:
//   - (void)fetcher:(GTMHTTPFetcher *)fetcher failedWithError:(NSError *)error

- (BOOL)beginFetchWithDelegate:(id)delegate
             didFinishSelector:(SEL)finishedSEL
               didFailSelector:(SEL)failedSEL {
  
  GTMAssertSelectorNilOrImplementedWithArguments(delegate, finishedSEL, @encode(GTMHTTPFetcher *), @encode(NSData *), NULL);
  GTMAssertSelectorNilOrImplementedWithArguments(delegate, failedSEL, @encode(GTMHTTPFetcher *), @encode(NSError *), NULL);
  GTMAssertSelectorNilOrImplementedWithArguments(delegate, receivedDataSEL_, @encode(GTMHTTPFetcher *), @encode(NSData *), NULL);
  GTMAssertSelectorNilOrImplementedWithReturnTypeAndArguments(delegate, retrySEL_, @encode(BOOL), @encode(GTMHTTPFetcher *), @encode(BOOL), @encode(NSError *), NULL);
    
  if (connection_ != nil) {
    _GTMDevAssert(connection_ != nil,
                  @"fetch object %@ being reused; this should never happen",
                  self);
    goto CannotBeginFetch;
  }
  
  if (request_ == nil) {
    _GTMDevAssert(request_ != nil, @"beginFetchWithDelegate requires a request");
    goto CannotBeginFetch;  
  }
  
  [downloadedData_ release];
  downloadedData_ = nil;
  
  [self setDelegate:delegate];
  finishedSEL_ = finishedSEL;
  failedSEL_ = failedSEL;
  
  if (postData_ || postStream_) {
    if ([request_ HTTPMethod] == nil || [[request_ HTTPMethod] isEqual:@"GET"]) {
      [request_ setHTTPMethod:@"POST"];
    }
    
    if (postData_) {
      [request_ setHTTPBody:postData_];
    } else {
      
      // if logging is enabled, it needs a buffer to accumulate data from any
      // NSInputStream used for uploading.  Logging will wrap the input
      // stream with a stream that lets us keep a copy the data being read.
      if ([GTMHTTPFetcher isLoggingEnabled] && postStream_ != nil) {
        loggedStreamData_ = [[NSMutableData alloc] init];
        [self logCapturePostStream];
      }
      
      [request_ setHTTPBodyStream:postStream_]; 
    }
  }
  
  if (fetchHistory_) {
    
    // If this URL is in the history, set the Last-Modified header field
    
    // if we have a history, we're tracking across fetches, so we don't
    // want to pull results from a cache
    [request_ setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    
    NSDictionary* lastModifiedDict = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
    NSString* urlString = [[request_ URL] absoluteString];
    NSString* lastModifiedStr = [lastModifiedDict objectForKey:urlString];
    
    // servers don't want last-modified-ifs on POSTs, so check for a body
    if (lastModifiedStr 
        && [request_ HTTPBody] == nil
        && [request_ HTTPBodyStream] == nil) {
      
      [request_ addValue:lastModifiedStr forHTTPHeaderField:kGTMIfModifiedSinceHeader];
    }
  }
  
  // get cookies for this URL from our storage array, if
  // we have a storage array
  if (cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
    
    NSArray *cookies = [self cookiesForURL:[request_ URL]];
    
    if ([cookies count]) {
      
      NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
      NSString *cookieHeader = [headerFields objectForKey:@"Cookie"]; // key used in header dictionary
      if (cookieHeader) {
        [request_ addValue:cookieHeader forHTTPHeaderField:@"Cookie"]; // header name
      }
    }
  }
  
  // finally, start the connection
	
  Class connectionClass = [[self class] connectionClass];
	
  NSArray *runLoopModes = nil;
  
  if ([[self class] doesSupportRunLoopModes]) {
    
    // use the connection-specific run loop modes, if they were provided,
    // or else use the GTMHTTPFetcher default run loop modes, if any
    if (runLoopModes_) {
      runLoopModes = runLoopModes_;
    } else  {
      runLoopModes = gGTMFetcherDefaultRunLoopModes;
    }
  }
  
  if ([runLoopModes count] == 0) {
    
    // if no run loop modes were specified, then we'll start the connection 
    // on the current run loop in the current mode
   connection_ = [[connectionClass connectionWithRequest:request_
                                                 delegate:self] retain];
  } else {
    
    // schedule on current run loop in the specified modes
    connection_ = [[connectionClass alloc] initWithRequest:request_
                                                  delegate:self 
                                          startImmediately:NO];
    
    for (NSUInteger idx = 0; idx < [runLoopModes count]; idx++) {
      NSString *mode = [runLoopModes objectAtIndex:idx];
      [connection_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode];
    }
    [connection_ start];
  }
  
  if (!connection_) {
    _GTMDevAssert(connection_ != nil,
                  @"beginFetchWithDelegate could not create a connection");
    goto CannotBeginFetch;
  }

  // we'll retain the delegate only during the outstanding connection (similar
  // to what Cocoa does with performSelectorOnMainThread:) since we'd crash
  // if the delegate was released in the interim.  We don't retain the selector
  // at other times, to avoid vicious retain loops.  This retain is balanced in
  // the -stopFetch method.
  [delegate_ retain];
  
  downloadedData_ = [[NSMutableData alloc] init];
  return YES;

CannotBeginFetch:

  if (failedSEL) {
    
    NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
                                         code:kGTMHTTPFetcherErrorDownloadFailed
                                     userInfo:nil];
    
    [[self retain] autorelease]; // in case the callback releases us

    [delegate performSelector:failedSEL_ 
                   withObject:self 
                   withObject:error];
  }
    
  return NO;
}

// Returns YES if this is in the process of fetching a URL, or waiting to 
// retry
- (BOOL)isFetching {
  return (connection_ != nil || retryTimer_ != nil); 
}

// Returns the status code set in connection:didReceiveResponse:
- (NSInteger)statusCode {
  
  NSInteger statusCode;
  
  if (response_ != nil 
    && [response_ respondsToSelector:@selector(statusCode)]) {
    
    statusCode = [(NSHTTPURLResponse *)response_ statusCode];
  } else {
    //  Default to zero, in hopes of hinting "Unknown" (we can't be
    //  sure that things are OK enough to use 200).
    statusCode = 0;
  }
  return statusCode;
}

// Cancel the fetch of the URL that's currently in progress.
- (void)stopFetching {
  [self destroyRetryTimer];

  if (connection_) {
    // in case cancelling the connection calls this recursively, we want
    // to ensure that we'll only release the connection and delegate once,
    // so first set connection_ to nil
    
    NSURLConnection* oldConnection = connection_;
    connection_ = nil;
    
    // this may be called in a callback from the connection, so use autorelease
    [oldConnection cancel];
    [oldConnection autorelease]; 

    // balance the retain done when the connection was opened
    [delegate_ release];
  }
}

- (void)retryFetch {
  
  id holdDelegate = [[delegate_ retain] autorelease];
  
  [self stopFetching];
  
  [self beginFetchWithDelegate:holdDelegate
             didFinishSelector:finishedSEL_
               didFailSelector:failedSEL_];
}

#pragma mark NSURLConnection Delegate Methods

//
// NSURLConnection Delegate Methods
//

// This method just says "follow all redirects", which _should_ be the default behavior,
// According to file:///Developer/ADC%20Reference%20Library/documentation/Cocoa/Conceptual/URLLoadingSystem
// but the redirects were not being followed until I added this method.  May be
// a bug in the NSURLConnection code, or the documentation.
//
// In OS X 10.4.8 and earlier, the redirect request doesn't
// get the original's headers and body. This causes POSTs to fail. 
// So we construct a new request, a copy of the original, with overrides from the
// redirect.
//
// Docs say that if redirectResponse is nil, just return the redirectRequest.

- (NSURLRequest *)connection:(NSURLConnection *)connection
             willSendRequest:(NSURLRequest *)redirectRequest
            redirectResponse:(NSURLResponse *)redirectResponse {

  if (redirectRequest && redirectResponse) {
    NSMutableURLRequest *newRequest = [[request_ mutableCopy] autorelease];
    // copy the URL
    NSURL *redirectURL = [redirectRequest URL];
    NSURL *url = [newRequest URL];
    
    // disallow scheme changes (say, from https to http)    
    NSString *redirectScheme = [url scheme];
    NSString *newScheme = [redirectURL scheme];
    NSString *newResourceSpecifier = [redirectURL resourceSpecifier];
    
    if ([redirectScheme caseInsensitiveCompare:@"http"] == NSOrderedSame
        && newScheme != nil
        && [newScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) {
      
      // allow the change from http to https
      redirectScheme = newScheme; 
    }
    
    NSString *newUrlString = [NSString stringWithFormat:@"%@:%@",
      redirectScheme, newResourceSpecifier];
    
    NSURL *newURL = [NSURL URLWithString:newUrlString];
    [newRequest setURL:newURL];

    // any headers in the redirect override headers in the original.
    NSDictionary *redirectHeaders = [redirectRequest allHTTPHeaderFields];
    if (redirectHeaders) {
      NSEnumerator *enumerator = [redirectHeaders keyEnumerator];
      NSString *key;
      while (nil != (key = [enumerator nextObject])) {
        NSString *value = [redirectHeaders objectForKey:key];
        [newRequest setValue:value forHTTPHeaderField:key];
      }
    }
    redirectRequest = newRequest;
    
    // save cookies from the response
    [self handleCookiesForResponse:redirectResponse];
    
    // log the response we just received
    [self setResponse:redirectResponse];
    [self logFetchWithError:nil];

    // update the request for future logging
    [self setRequest:redirectRequest];
}
  return redirectRequest;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  
  // this method is called when the server has determined that it
  // has enough information to create the NSURLResponse
  // it can be called multiple times, for example in the case of a 
  // redirect, so each time we reset the data.
  [downloadedData_ setLength:0];

  [self setResponse:response];

  // save cookies from the response
  [self handleCookiesForResponse:response];  
}


// handleCookiesForResponse: handles storage of cookies for responses passed to
// connection:willSendRequest:redirectResponse: and connection:didReceiveResponse:
- (void)handleCookiesForResponse:(NSURLResponse *)response {
  
  if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
    
    // do nothing special for NSURLConnection's default storage mechanism
    
  } else if ([response respondsToSelector:@selector(allHeaderFields)]) {
    
    // grab the cookies from the header as NSHTTPCookies and store them either
    // into our static array or into the fetchHistory
    
    NSDictionary *responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];
    if (responseHeaderFields) {
      
      NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseHeaderFields
                                                                forURL:[response URL]]; 
      if ([cookies count] > 0) {
        
        NSMutableArray *cookieArray = nil;
        
        // static cookies are stored in gGTMFetcherStaticCookies; fetchHistory 
        // cookies are stored in fetchHistory_'s kGTMHTTPFetcherHistoryCookiesKey
        
        if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodStatic) {
          
          cookieArray = gGTMFetcherStaticCookies;
          
        } else if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodFetchHistory
                   && fetchHistory_ != nil) {
          
          cookieArray = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryCookiesKey];
          if (cookieArray == nil) {
            cookieArray = [NSMutableArray array];
            [fetchHistory_ setObject:cookieArray forKey:kGTMHTTPFetcherHistoryCookiesKey];
          }
        }
        
        if (cookieArray) {
          @synchronized(cookieArray) {
            [self setCookies:cookies inArray:cookieArray];
          }
        }
      }
    }
  }
}

-(void)connection:(NSURLConnection *)connection
       didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  
  if ([challenge previousFailureCount] <= 2) {
    
    NSURLCredential *credential = credential_;
    
    if ([[challenge protectionSpace] isProxy] && proxyCredential_ != nil) {
      credential = proxyCredential_;
    }
    
    // Here, if credential is still nil, then we *could* try to get it from
    // NSURLCredentialStorage's defaultCredentialForProtectionSpace:.
    // We don't, because we're assuming:
    //
    // - for server credentials, we only want ones supplied by the program
    //   calling http fetcher
    // - for proxy credentials, if one were necessary and available in the
    //   keychain, it would've been found automatically by NSURLConnection
    //   and this challenge delegate method never would've been called
    //   anyway
    
    if (credential) {
      // try the credential
      [[challenge sender] useCredential:credential
             forAuthenticationChallenge:challenge];
      return;
    } 
  }
  
  // If we don't have credentials, or we've already failed auth 3x...
  [[challenge sender] cancelAuthenticationChallenge:challenge];
  
  // report the error, putting the challenge as a value in the userInfo
  // dictionary
  NSDictionary *userInfo = [NSDictionary dictionaryWithObject:challenge
                                                       forKey:kGTMHTTPFetcherErrorChallengeKey];
  
  NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
                                       code:kGTMHTTPFetcherErrorAuthenticationChallengeFailed
                                   userInfo:userInfo];
  
  [self connection:connection didFailWithError:error];  
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  [downloadedData_ appendData:data];
  
  if (receivedDataSEL_) {
   [delegate_ performSelector:receivedDataSEL_
                   withObject:self
                   withObject:downloadedData_];
  }
}

- (void)updateFetchHistory {
  
  if (fetchHistory_) {
    
    NSString* urlString = [[request_ URL] absoluteString];
    if ([response_ respondsToSelector:@selector(allHeaderFields)]) {
      NSDictionary *headers = [(NSHTTPURLResponse *)response_ allHeaderFields];
      NSString* lastModifiedStr = [headers objectForKey:kGTMLastModifiedHeader];
    
      // get the dictionary mapping URLs to last-modified dates
      NSMutableDictionary* lastModifiedDict = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
      if (!lastModifiedDict) {
        lastModifiedDict = [NSMutableDictionary dictionary];
        [fetchHistory_ setObject:lastModifiedDict forKey:kGTMHTTPFetcherHistoryLastModifiedKey];
      }

      NSMutableDictionary* datedDataCache = nil;
      if (shouldCacheDatedData_) {
        // get the dictionary mapping URLs to cached, dated data
        datedDataCache = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryDatedDataKey];
        if (!datedDataCache) {
          datedDataCache = [NSMutableDictionary dictionary];
          [fetchHistory_ setObject:datedDataCache forKey:kGTMHTTPFetcherHistoryDatedDataKey];
        }
      }
      
      NSInteger statusCode = [self statusCode];
      if (statusCode != kGTMHTTPFetcherStatusNotModified) {
        
        // save this last modified date string for successful results (<300)
        // If there's no last modified string, clear the dictionary 
        // entry for this URL. Also cache or delete the data, if appropriate 
        // (when datedDataCache is non-nil.)
        if (lastModifiedStr && statusCode < 300) {
          [lastModifiedDict setValue:lastModifiedStr forKey:urlString];
          [datedDataCache setValue:downloadedData_ forKey:urlString];
        } else { 
          [lastModifiedDict removeObjectForKey:urlString];
          [datedDataCache removeObjectForKey:urlString];
        }
      }
    }
  }
}

// for error 304's ("Not Modified") where we've cached the data, return status 
// 200 ("OK") to the caller (but leave the fetcher status as 304) 
// and copy the cached data to downloadedData_.  
// For other errors or if there's no cached data, just return the actual status.
- (NSInteger)statusAfterHandlingNotModifiedError {
  
  NSInteger status = [self statusCode];
  if (status == kGTMHTTPFetcherStatusNotModified && shouldCacheDatedData_) {
    
    // get the dictionary of URLs and data
    NSString* urlString = [[request_ URL] absoluteString];
    
    NSDictionary* datedDataCache = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryDatedDataKey];
    NSData* cachedData = [datedDataCache objectForKey:urlString];
    
    if (cachedData) {
      // copy our stored data, and forge the status to pass on to the delegate
      [downloadedData_ setData:cachedData];
      status = 200;
    }
  }
  return status;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  
  [self updateFetchHistory];

  [[self retain] autorelease]; // in case the callback releases us
  
  [self logFetchWithError:nil];
  
  NSInteger status = [self statusAfterHandlingNotModifiedError];
  
  if (status >= 300) {
    
    if ([self shouldRetryNowForStatus:status error:nil]) {
      
      [self beginRetryTimer];
      
    } else {
      // not retrying
      
      // did they want failure notifications?
      if (failedSEL_) {
        
        NSDictionary *userInfo =
          [NSDictionary dictionaryWithObject:downloadedData_
                                      forKey:kGTMHTTPFetcherStatusDataKey];
        NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain 
                                             code:status
                                         userInfo:userInfo];

        [delegate_ performSelector:failedSEL_ 
                        withObject:self 
                        withObject:error];
      }
      // we're done fetching
      [self stopFetching];
    }
    
  } else if (finishedSEL_) {
    
    // successful http status (under 300)
    [delegate_ performSelector:finishedSEL_
                    withObject:self
                    withObject:downloadedData_];
    [self stopFetching];
  }
  
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

  [self logFetchWithError:error];
  
  if ([self shouldRetryNowForStatus:0 error:error]) {
    
    [self beginRetryTimer];
    
  } else {    
  
    if (failedSEL_) {
      [[self retain] autorelease]; // in case the callback releases us

      [delegate_ performSelector:failedSEL_ 
                      withObject:self 
                      withObject:error];
    }
    
    [self stopFetching];
  }
}

#pragma mark Retries

- (BOOL)isRetryError:(NSError *)error {
  
  struct retryRecord {
    NSString *const domain;
    int code;
  };
  
  struct retryRecord retries[] = {
    { kGTMHTTPFetcherStatusDomain, 408 }, // request timeout
    { kGTMHTTPFetcherStatusDomain, 503 }, // service unavailable
    { kGTMHTTPFetcherStatusDomain, 504 }, // request timeout
    { NSURLErrorDomain, NSURLErrorTimedOut },
    { NSURLErrorDomain, NSURLErrorNetworkConnectionLost },
    { nil, 0 }
  };

  // NSError's isEqual always returns false for equal but distinct instances
  // of NSError, so we have to compare the domain and code values explicitly

  for (int idx = 0; retries[idx].domain != nil; idx++) {
    
    if ([[error domain] isEqual:retries[idx].domain]
        && [error code] == retries[idx].code) {
     
      return YES;
    }
  }
  return NO;
}


// shouldRetryNowForStatus:error: returns YES if the user has enabled retries
// and the status or error is one that is suitable for retrying.  "Suitable"
// means either the isRetryError:'s list contains the status or error, or the
// user's retrySelector: is present and returns YES when called.
- (BOOL)shouldRetryNowForStatus:(NSInteger)status
                          error:(NSError *)error {
  
  if ([self isRetryEnabled]) {
    
    if ([self nextRetryInterval] < [self maxRetryInterval]) {
      
      if (error == nil) {
        // make an error for the status
       error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain
                                   code:status
                               userInfo:nil]; 
      }
      
      BOOL willRetry = [self isRetryError:error];
      
      if (retrySEL_) {
        NSMethodSignature *signature = [delegate_ methodSignatureForSelector:retrySEL_];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setSelector:retrySEL_];
        [invocation setTarget:delegate_];
        [invocation setArgument:&self atIndex:2];
        [invocation setArgument:&willRetry atIndex:3];
        [invocation setArgument:&error atIndex:4];
        [invocation invoke];
        
        [invocation getReturnValue:&willRetry];
      }
      
      return willRetry;
    }
  }
  
  return NO;
}

- (void)beginRetryTimer {
  
  NSTimeInterval nextInterval = [self nextRetryInterval];
  NSTimeInterval maxInterval = [self maxRetryInterval];

  NSTimeInterval newInterval = MIN(nextInterval, maxInterval);
    
  [self primeTimerWithNewTimeInterval:newInterval];
}

- (void)primeTimerWithNewTimeInterval:(NSTimeInterval)secs {
  
  [self destroyRetryTimer];
  
  lastRetryInterval_ = secs;
  
  retryTimer_ = [NSTimer scheduledTimerWithTimeInterval:secs
                                  target:self
                                selector:@selector(retryTimerFired:)
                                userInfo:nil
                                 repeats:NO];
  [retryTimer_ retain];
}

- (void)retryTimerFired:(NSTimer *)timer {

  [self destroyRetryTimer];
  
  retryCount_++;

  [self retryFetch];
}

- (void)destroyRetryTimer {
  
  [retryTimer_ invalidate];
  [retryTimer_ autorelease];
  retryTimer_ = nil;  
}

- (unsigned int)retryCount {
  return retryCount_; 
}

- (NSTimeInterval)nextRetryInterval {
  // the next wait interval is the factor (2.0) times the last interval,  
  // but never less than the minimum interval
  NSTimeInterval secs = lastRetryInterval_ * retryFactor_;
  secs = MIN(secs, maxRetryInterval_);
  secs = MAX(secs, minRetryInterval_);
  
  return secs;
}

- (BOOL)isRetryEnabled {
  return isRetryEnabled_;  
}

- (void)setIsRetryEnabled:(BOOL)flag {
  
  if (flag && !isRetryEnabled_) {
    // We defer initializing these until the user calls setIsRetryEnabled
    // to avoid seeding the random number generator if it's not needed.
    // However, it means min and max intervals for this fetcher are reset
    // as a side effect of calling setIsRetryEnabled.
    //
    // seed the random value, and make an initial retry interval
    // random between 1.0 and 2.0 seconds
    srandomdev(); 
    [self setMinRetryInterval:0.0]; 
    [self setMaxRetryInterval:kDefaultMaxRetryInterval];
    [self setRetryFactor:2.0];
    lastRetryInterval_ = 0.0;
  }
  isRetryEnabled_ = flag; 
}; 

- (SEL)retrySelector {
  return retrySEL_; 
}

- (void)setRetrySelector:(SEL)theSelector {
  retrySEL_ = theSelector;  
}

- (NSTimeInterval)maxRetryInterval {
  return maxRetryInterval_;  
}

- (void)setMaxRetryInterval:(NSTimeInterval)secs {
  if (secs > 0) {
    maxRetryInterval_ = secs; 
  } else {
    maxRetryInterval_ = kDefaultMaxRetryInterval; 
  }
}

- (double)minRetryInterval {
  return minRetryInterval_;  
}

- (void)setMinRetryInterval:(NSTimeInterval)secs {
  if (secs > 0) {
    minRetryInterval_ = secs; 
  } else {
    // set min interval to a random value between 1.0 and 2.0 seconds
    // so that if multiple clients start retrying at the same time, they'll
    // repeat at different times and avoid overloading the server
    minRetryInterval_ = 1.0 + ((double)(random() & 0x0FFFF) / (double) 0x0FFFF);
  }
}

- (double)retryFactor {
  return retryFactor_; 
}

- (void)setRetryFactor:(double)multiplier {
  retryFactor_ = multiplier; 
}

#pragma mark Getters and Setters

- (NSMutableURLRequest *)request {
  return request_;  
}

- (void)setRequest:(NSURLRequest *)theRequest {
  [request_ autorelease];
  request_ = [theRequest mutableCopy];
}

- (NSURLCredential *)credential {
  return credential_;
}

- (void)setCredential:(NSURLCredential *)theCredential {
  [credential_ autorelease];
  credential_ = [theCredential retain]; 
}

- (NSURLCredential *)proxyCredential {
  return proxyCredential_;
}

- (void)setProxyCredential:(NSURLCredential *)theCredential {
  [proxyCredential_ autorelease];
  proxyCredential_ = [theCredential retain]; 
}

- (NSData *)postData {
  return postData_; 
}

- (void)setPostData:(NSData *)theData {
  [postData_ autorelease]; 
  postData_ = [theData retain];
}

- (NSInputStream *)postStream {
  return postStream_; 
}

- (void)setPostStream:(NSInputStream *)theStream {
  [postStream_ autorelease]; 
  postStream_ = [theStream retain];
}

- (GTMHTTPFetcherCookieStorageMethod)cookieStorageMethod {
  return cookieStorageMethod_; 
}

- (void)setCookieStorageMethod:(GTMHTTPFetcherCookieStorageMethod)method {
  
  cookieStorageMethod_ = method; 
  
  if (method == kGTMHTTPFetcherCookieStorageMethodSystemDefault) {
    [request_ setHTTPShouldHandleCookies:YES];
  } else {
    [request_ setHTTPShouldHandleCookies:NO];
  }
}

- (id)delegate {
  return delegate_; 
}

- (void)setDelegate:(id)theDelegate {
  
  // we retain delegate_ only during the life of the connection
  if (connection_) {
    [delegate_ autorelease];
    delegate_ = [theDelegate retain];
  } else {
    delegate_ = theDelegate; 
  }
}

- (SEL)receivedDataSelector {
  return receivedDataSEL_; 
}

- (void)setReceivedDataSelector:(SEL)theSelector {
  receivedDataSEL_ = theSelector;  
}

- (NSURLResponse *)response {
  return response_;
}

- (void)setResponse:(NSURLResponse *)response {
  [response_ autorelease];
  response_ = [response retain];
}

- (NSMutableDictionary *)fetchHistory {
  return fetchHistory_;
}

- (void)setFetchHistory:(NSMutableDictionary *)fetchHistory {
  [fetchHistory_ autorelease];
  fetchHistory_ = [fetchHistory retain];
  
  if (fetchHistory_ != nil) {
    [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodFetchHistory];
  } else {
    [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic];
  }
}

- (void)setShouldCacheDatedData:(BOOL)flag {
  shouldCacheDatedData_ = flag;
  if (!flag) {
    [self clearDatedDataHistory];
  }
}

- (BOOL)shouldCacheDatedData {
  return shouldCacheDatedData_; 
}

// delete last-modified dates and cached data from the fetch history
- (void)clearDatedDataHistory {
  [fetchHistory_ removeObjectForKey:kGTMHTTPFetcherHistoryLastModifiedKey];
  [fetchHistory_ removeObjectForKey:kGTMHTTPFetcherHistoryDatedDataKey]; 
}

- (id)userData {
  return userData_;
}

- (void)setUserData:(id)theObj {
  [userData_ autorelease]; 
  userData_ = [theObj retain];
}

- (NSArray *)runLoopModes {
  return runLoopModes_;
}

- (void)setRunLoopModes:(NSArray *)modes {
  [runLoopModes_ autorelease]; 
  runLoopModes_ = [modes retain];
}

+ (BOOL)doesSupportRunLoopModes {
  SEL sel = @selector(initWithRequest:delegate:startImmediately:);
  return [NSURLConnection instancesRespondToSelector:sel];
}

+ (NSArray *)defaultRunLoopModes {
  return gGTMFetcherDefaultRunLoopModes; 
}

+ (void)setDefaultRunLoopModes:(NSArray *)modes {
  [gGTMFetcherDefaultRunLoopModes autorelease];
  gGTMFetcherDefaultRunLoopModes = [modes retain];
}

+ (Class)connectionClass {
  if (gGTMFetcherConnectionClass == nil) {
    gGTMFetcherConnectionClass = [NSURLConnection class]; 
  }
  return gGTMFetcherConnectionClass; 
}

+ (void)setConnectionClass:(Class)theClass {
  gGTMFetcherConnectionClass = theClass;
}

#pragma mark Cookies

// return a cookie from the array with the same name, domain, and path as the 
// given cookie, or else return nil if none found
//
// Both the cookie being tested and all cookies in cookieStorageArray should
// be valid (non-nil name, domains, paths)
- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie
                               inArray:(NSArray *)cookieStorageArray {

  NSUInteger numberOfCookies = [cookieStorageArray count];
  NSString *name = [cookie name];
  NSString *domain = [cookie domain];
  NSString *path = [cookie path];
  
  _GTMDevAssert(name && domain && path,
                @"Invalid cookie (name:%@ domain:%@ path:%@)", 
                name, domain, path);
  
  for (NSUInteger idx = 0; idx < numberOfCookies; idx++) {
    
    NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];

    if ([[storedCookie name] isEqual:name]
        && [[storedCookie domain] isEqual:domain]
        && [[storedCookie path] isEqual:path]) {
      
      return storedCookie; 
    }
  }
  return nil;
}

// remove any expired cookies from the array, excluding cookies with nil
// expirations
- (void)removeExpiredCookiesInArray:(NSMutableArray *)cookieStorageArray {
  
  // count backwards since we're deleting items from the array
  for (NSInteger idx = [cookieStorageArray count] - 1; idx >= 0; idx--) {
    
    NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];
    
    NSDate *expiresDate = [storedCookie expiresDate];
    if (expiresDate && [expiresDate timeIntervalSinceNow] < 0) {
      [cookieStorageArray removeObjectAtIndex:idx];
    }
  }
}


// retrieve all cookies appropriate for the given URL, considering
// domain, path, cookie name, expiration, security setting.
// Side effect: removed expired cookies from the storage array
- (NSArray *)cookiesForURL:(NSURL *)theURL inArray:(NSMutableArray *)cookieStorageArray {
  
  [self removeExpiredCookiesInArray:cookieStorageArray];
  
  NSMutableArray *foundCookies = [NSMutableArray array];

  // we'll prepend "." to the desired domain, since we want the
  // actual domain "nytimes.com" to still match the cookie domain ".nytimes.com"
  // when we check it below with hasSuffix
  NSString *host = [theURL host];
  NSString *path = [theURL path];
  NSString *scheme = [theURL scheme];
  
  NSString *domain = nil;
  if ([host isEqual:@"localhost"]) {
    // the domain stored into NSHTTPCookies for localhost is "localhost.local"
    domain = @"localhost.local"; 
  } else {
    if (host) {
      domain = [@"." stringByAppendingString:host]; 
    }
  }
  
  NSUInteger numberOfCookies = [cookieStorageArray count];
  for (NSUInteger idx = 0; idx < numberOfCookies; idx++) {
    
    NSHTTPCookie *storedCookie = [cookieStorageArray objectAtIndex:idx];
    
    NSString *cookieDomain = [storedCookie domain];
    NSString *cookiePath = [storedCookie path];
    BOOL cookieIsSecure = [storedCookie isSecure];
    
    BOOL domainIsOK = [domain hasSuffix:cookieDomain];
    BOOL pathIsOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath];
    BOOL secureIsOK = (!cookieIsSecure) || [scheme isEqual:@"https"];
    
    if (domainIsOK && pathIsOK && secureIsOK) {
      [foundCookies addObject:storedCookie];
    }
  }
  return foundCookies;
}

// return cookies for the given URL using the current cookie storage method
- (NSArray *)cookiesForURL:(NSURL *)theURL {
  
  NSArray *cookies = nil;
  NSMutableArray *cookieStorageArray = nil;
  
  if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodStatic) {
    cookieStorageArray = gGTMFetcherStaticCookies;
  } else if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodFetchHistory) {
    cookieStorageArray = [fetchHistory_ objectForKey:kGTMHTTPFetcherHistoryCookiesKey];
  } else {
    // kGTMHTTPFetcherCookieStorageMethodSystemDefault
    cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:theURL];    
  }
  
  if (cookieStorageArray) {
    
    @synchronized(cookieStorageArray) {
      
      // cookiesForURL returns a new array of immutable NSCookie objects
      // from cookieStorageArray
      cookies = [self cookiesForURL:theURL
                            inArray:cookieStorageArray];
    }
  }
  return cookies;
}


// add all cookies in the array |newCookies| to the storage array,
// replacing cookies in the storage array as appropriate
// Side effect: removes expired cookies from the storage array
- (void)setCookies:(NSArray *)newCookies
           inArray:(NSMutableArray *)cookieStorageArray {
  
  [self removeExpiredCookiesInArray:cookieStorageArray];

  NSEnumerator *newCookieEnum = [newCookies objectEnumerator];
  NSHTTPCookie *newCookie;
  
  while ((newCookie = [newCookieEnum nextObject]) != nil) {
    
    if ([[newCookie name] length] > 0
        && [[newCookie domain] length] > 0
        && [[newCookie path] length] > 0) {

      // remove the cookie if it's currently in the array
      NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie
                                                   inArray:cookieStorageArray];
      if (oldCookie) {
        [cookieStorageArray removeObject:oldCookie];
      }
      
      // make sure the cookie hasn't already expired
      NSDate *expiresDate = [newCookie expiresDate];
      if ((!expiresDate) || [expiresDate timeIntervalSinceNow] > 0) {
        [cookieStorageArray addObject:newCookie];
      }
      
    } else {
      _GTMDevAssert(NO, @"Cookie incomplete: %@", newCookie); 
    }
  }
}
@end

#pragma mark Logging

// NOTE: Threads and Logging
//
// All the NSURLConnection callbacks happen on one thread, so we don't have
// to put any synchronization into the logging code.  Yes, the state around
// logging (it's directory, etc.) could use it, but for now, that's punted.


// We don't invoke Leopard methods on 10.4, because we check if the methods are
// implemented before invoking it, but we need to be able to compile without
// warnings.
// This declaration means if you target <=10.4, this method will compile
// without complaint in this source, so you must test with
// -respondsToSelector:, too.
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
@interface NSFileManager (LeopardMethodsOnTigerBuilds)
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;
@end
#endif
// The iPhone Foundation removes the deprecated removeFileAtPath:handler:
#if GTM_IPHONE_SDK
@interface NSFileManager (TigerMethodsOniPhoneBuilds)
- (BOOL)removeFileAtPath:(NSString *)path handler:(id)handler;
@end
#endif

@implementation GTMHTTPFetcher (GTMHTTPFetcherLogging)

// if GTM_HTTPFETCHER_ENABLE_LOGGING is defined by the user's project then
// logging code will be compiled into the framework

#if !GTM_HTTPFETCHER_ENABLE_LOGGING
- (void)logFetchWithError:(NSError *)error {}

+ (void)setLoggingDirectory:(NSString *)path {}
+ (NSString *)loggingDirectory {return nil;}

+ (void)setIsLoggingEnabled:(BOOL)flag {}
+ (BOOL)isLoggingEnabled {return NO;}

+ (void)setLoggingProcessName:(NSString *)str {}
+ (NSString *)loggingProcessName {return nil;}

+ (void)setLoggingDateStamp:(NSString *)str {}
+ (NSString *)loggingDateStamp {return nil;}

- (void)appendLoggedStreamData:(NSData *)newData {}
- (void)logCapturePostStream {}
#else // GTM_HTTPFETCHER_ENABLE_LOGGING

// fetchers come and fetchers go, but statics are forever
static BOOL gIsLoggingEnabled = NO;
static NSString *gLoggingDirectoryPath = nil;
static NSString *gLoggingDateStamp = nil;
static NSString* gLoggingProcessName = nil; 

+ (void)setLoggingDirectory:(NSString *)path {
  [gLoggingDirectoryPath autorelease];
  gLoggingDirectoryPath = [path copy];
}

+ (NSString *)loggingDirectory {
  
  if (!gLoggingDirectoryPath) {
    
#if GTM_IPHONE_SDK
    // default to a directory called GTMHTTPDebugLogs into a sandbox-safe
    // directory that a devloper can find easily, the application home
    NSArray *arr = [NSArray arrayWithObject:NSHomeDirectory()];
#else
    // default to a directory called GTMHTTPDebugLogs in the desktop folder
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory,
                                                       NSUserDomainMask, YES);
#endif
    
    if ([arr count] > 0) {
      NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs";
      
      NSString *desktopPath = [arr objectAtIndex:0];
      NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName];
      
      BOOL doesFolderExist;
      BOOL isDir = NO;
      NSFileManager *fileManager = [NSFileManager defaultManager];
      doesFolderExist = [fileManager fileExistsAtPath:logsFolderPath 
                                          isDirectory:&isDir];
      
      if (!doesFolderExist) {
        // make the directory
        doesFolderExist = [fileManager createDirectoryAtPath:logsFolderPath 
                                                  attributes:nil];
      }
      
      if (doesFolderExist) {
        // it's there; store it in the global
        gLoggingDirectoryPath = [logsFolderPath copy];
      }
    }
  }
  return gLoggingDirectoryPath;
}

+ (void)setIsLoggingEnabled:(BOOL)flag {
  gIsLoggingEnabled = flag;
}

+ (BOOL)isLoggingEnabled {
  return gIsLoggingEnabled;
}

+ (void)setLoggingProcessName:(NSString *)str {
  [gLoggingProcessName release];
  gLoggingProcessName = [str copy];
}

+ (NSString *)loggingProcessName {
  
  // get the process name (once per run) replacing spaces with underscores
  if (!gLoggingProcessName) {
    
    NSString *procName = [[NSProcessInfo processInfo] processName];
    NSMutableString *loggingProcessName;
    loggingProcessName = [[NSMutableString alloc] initWithString:procName];
    
    [loggingProcessName replaceOccurrencesOfString:@" " 
                                        withString:@"_" 
                                           options:0 
                                             range:NSMakeRange(0, [gLoggingProcessName length])];
    gLoggingProcessName = loggingProcessName;
  } 
  return gLoggingProcessName;
}

+ (void)setLoggingDateStamp:(NSString *)str {
  [gLoggingDateStamp release];
  gLoggingDateStamp = [str copy];
}

+ (NSString *)loggingDateStamp {
  // we'll pick one date stamp per run, so a run that starts at a later second
  // will get a unique results html file
  if (!gLoggingDateStamp) {    
    // produce a string like 08-21_01-41-23PM
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"M-dd_hh-mm-ssa"];
    
    gLoggingDateStamp = [[formatter stringFromDate:[NSDate date]] retain] ;    
  }
  return gLoggingDateStamp;
}

- (NSString *)cleanParameterFollowing:(NSString *)paramName
                           fromString:(NSString *)originalStr {
  // We don't want the password written to disk 
  //
  // find "&Passwd=" in the string, and replace it and the stuff that
  // follows it with "Passwd=_snip_"
  
  NSRange passwdRange = [originalStr rangeOfString:@"&Passwd="];
  if (passwdRange.location != NSNotFound) {
    
    // we found Passwd=; find the & that follows the parameter
    NSUInteger origLength = [originalStr length];
    NSRange restOfString = NSMakeRange(passwdRange.location+1, 
                                       origLength - passwdRange.location - 1);
    NSRange rangeOfFollowingAmp = [originalStr rangeOfString:@"&"
                                                     options:0
                                                       range:restOfString];
    NSRange replaceRange;
    if (rangeOfFollowingAmp.location == NSNotFound) {
      // found no other & so replace to end of string
      replaceRange = NSMakeRange(passwdRange.location, 
                                 rangeOfFollowingAmp.location - passwdRange.location);
    } else {
      // another parameter after &Passwd=foo
      replaceRange = NSMakeRange(passwdRange.location, 
                                 rangeOfFollowingAmp.location - passwdRange.location);
    }
    
    NSMutableString *result = [NSMutableString stringWithString:originalStr];
    NSString *replacement = [NSString stringWithFormat:@"%@_snip_", paramName];
    
    [result replaceCharactersInRange:replaceRange withString:replacement];
    return result;
  }
  return originalStr;
}

// stringFromStreamData creates a string given the supplied data
//
// If NSString can create a UTF-8 string from the data, then that is returned.
//
// Otherwise, this routine tries to find a MIME boundary at the beginning of
// the data block, and uses that to break up the data into parts. Each part
// will be used to try to make a UTF-8 string.  For parts that fail, a 
// replacement string showing the part header and <<n bytes>> is supplied
// in place of the binary data.

- (NSString *)stringFromStreamData:(NSData *)data {
  
  if (data == nil) return nil;
  
  // optimistically, see if the whole data block is UTF-8
  NSString *streamDataStr = [[[NSString alloc] initWithData:data
                                                   encoding:NSUTF8StringEncoding] autorelease];
  if (streamDataStr) return streamDataStr;
  
  // Munge a buffer by replacing non-ASCII bytes with underscores,
  // and turn that munged buffer an NSString.  That gives us a string
  // we can use with NSScanner.
  NSMutableData *mutableData = [NSMutableData dataWithData:data];
  unsigned char *bytes = [mutableData mutableBytes];
  
  for (NSUInteger idx = 0; idx < [mutableData length]; idx++) {
    if (bytes[idx] > 0x7F || bytes[idx] == 0) {
      bytes[idx] = '_';
    }
  }
  
  NSString *mungedStr = [[[NSString alloc] initWithData:mutableData
                                               encoding:NSUTF8StringEncoding] autorelease];
  if (mungedStr != nil) {
    
    // scan for the boundary string
    NSString *boundary = nil;
    NSScanner *scanner = [NSScanner scannerWithString:mungedStr];
    
    if ([scanner scanUpToString:@"\r\n" intoString:&boundary]
        && [boundary hasPrefix:@"--"]) {
      
      // we found a boundary string; use it to divide the string into parts
      NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary];
      
      // look at each of the munged parts in the original string, and try to 
      // convert those into UTF-8
      NSMutableArray *origParts = [NSMutableArray array];
      NSUInteger offset = 0;
      for (NSUInteger partIdx = 0; partIdx < [mungedParts count]; partIdx++) {
        
        NSString *mungedPart = [mungedParts objectAtIndex:partIdx];
        NSUInteger partSize = [mungedPart length];
        
        NSRange range = NSMakeRange(offset, partSize);
        NSData *origPartData = [data subdataWithRange:range];
        
        NSString *origPartStr = [[[NSString alloc] initWithData:origPartData
                                                       encoding:NSUTF8StringEncoding] autorelease];
        if (origPartStr) {
          // we could make this original part into UTF-8; use the string
          [origParts addObject:origPartStr];
        } else {
          // this part can't be made into UTF-8; scan the header, if we can
          NSString *header = nil;
          NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart];
          if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) {
            // we couldn't find a header
            header = @"";
          }
          
          // make a part string with the header and <<n bytes>>
          NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%u bytes>>\r",
                              header, partSize - [header length]];
          [origParts addObject:binStr];
        }
        offset += partSize + [boundary length];
      }
      
      // rejoin the original parts
      streamDataStr = [origParts componentsJoinedByString:boundary];
    }
  }  
  
  if (!streamDataStr) {
    // give up; just make a string showing the uploaded bytes
    streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", [data length]];
  }
  return streamDataStr;
}

// logFetchWithError is called following a successful or failed fetch attempt
//
// This method does all the work for appending to and creating log files

- (void)logFetchWithError:(NSError *)error {
  
  if (![[self class] isLoggingEnabled]) return;
  
  NSFileManager *fileManager = [NSFileManager defaultManager];
  
  // TODO:  add Javascript to display response data formatted in hex
  
  NSString *logDirectory = [[self class] loggingDirectory];
  NSString *processName = [[self class] loggingProcessName];
  NSString *dateStamp = [[self class] loggingDateStamp];
  
  // each response's NSData goes into its own xml or txt file, though all
  // responses for this run of the app share a main html file.  This 
  // counter tracks all fetch responses for this run of the app.
  static int zResponseCounter = 0; 
  zResponseCounter++;
  
  // file name for the html file containing plain text in a <textarea>
  NSString *responseDataUnformattedFileName = nil; 
  
  // file name for the "formatted" (raw) data file
  NSString *responseDataFormattedFileName = nil; 
  NSUInteger responseDataLength = [downloadedData_ length];
  
  NSURLResponse *response = [self response];
  NSString *responseBaseName = nil;
  
  // if there's response data, decide what kind of file to put it in based  
  // on the first bytes of the file or on the mime type supplied by the server
  if (responseDataLength) {
    NSString *responseDataExtn = nil;
    
    // generate a response file base name like
    //   SyncProto_http_response_10-16_01-56-58PM_3
    responseBaseName = [NSString stringWithFormat:@"%@_http_response_%@_%d",
                        processName, dateStamp, zResponseCounter];
    
    NSString *dataStr = [[[NSString alloc] initWithData:downloadedData_ 
                                               encoding:NSUTF8StringEncoding] autorelease];
    if (dataStr) {
      // we were able to make a UTF-8 string from the response data
      
      NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
      dataStr = [dataStr stringByTrimmingCharactersInSet:whitespaceSet];
      
      // save a plain-text version of the response data in an html cile  
      // containing a wrapped, scrollable <textarea>
      //
      // we'll use <textarea rows="33" cols="108" readonly=true wrap=soft>
      //   </textarea>  to fit inside our iframe
      responseDataUnformattedFileName = [responseBaseName stringByAppendingPathExtension:@"html"];
      NSString *textFilePath = [logDirectory stringByAppendingPathComponent:responseDataUnformattedFileName];
      
      NSString* wrapFmt = @"<textarea rows=\"33\" cols=\"108\" readonly=true"
      " wrap=soft>\n%@\n</textarea>";
      NSString* wrappedStr = [NSString stringWithFormat:wrapFmt, dataStr];
      [wrappedStr writeToFile:textFilePath 
                   atomically:NO 
                     encoding:NSUTF8StringEncoding 
                        error:nil];
      
      // now determine the extension for the "formatted" file, which is really 
      // the raw data written with an appropriate extension
      
      // for known file types, we'll write the data to a file with the
      // appropriate extension
      if ([dataStr hasPrefix:@"<?xml"]) {
        responseDataExtn = @"xml";
      } else if ([dataStr hasPrefix:@"<html"]) {
        responseDataExtn = @"html";
      } else {
        // add more types of identifiable text here
      }
      
    } else if ([[response MIMEType] isEqual:@"image/jpeg"]) {
      responseDataExtn = @"jpg";
    } else if ([[response MIMEType] isEqual:@"image/gif"]) {
      responseDataExtn = @"gif";
    } else if ([[response MIMEType] isEqual:@"image/png"]) {
      responseDataExtn = @"png";
    } else {
      // add more non-text types here
    }
    
    // if we have an extension, save the raw data in a file with that 
    // extension to be our "formatted" display file
    if (responseDataExtn) {
      responseDataFormattedFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn];
      NSString *formattedFilePath = [logDirectory stringByAppendingPathComponent:responseDataFormattedFileName];
      
      [downloadedData_ writeToFile:formattedFilePath atomically:NO];
    }
  }
  
  // we'll have one main html file per run of the app
  NSString *htmlName = [NSString stringWithFormat:@"%@_http_log_%@.html", 
                        processName, dateStamp];
  NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName];
  
  // if the html file exists (from logging previous fetches) we don't need
  // to re-write the header or the scripts
  BOOL didFileExist = [fileManager fileExistsAtPath:htmlPath];
  
  NSMutableString* outputHTML = [NSMutableString string];
  NSURLRequest *request = [self request];
  
  // we need file names for the various div's that we're going to show and hide,
  // names unique to this response's bundle of data, so we format our div
  // names with the counter that we incremented earlier
  NSString *requestHeadersName = [NSString stringWithFormat:@"RequestHeaders%d", zResponseCounter];
  NSString *postDataName = [NSString stringWithFormat:@"PostData%d", zResponseCounter];
  
  NSString *responseHeadersName = [NSString stringWithFormat:@"ResponseHeaders%d", zResponseCounter];
  NSString *responseDataDivName = [NSString stringWithFormat:@"ResponseData%d", zResponseCounter];
  NSString *dataIFrameID = [NSString stringWithFormat:@"DataIFrame%d", zResponseCounter];
  
  // we need a header to say we'll have UTF-8 text
  if (!didFileExist) {
    [outputHTML appendFormat:@"<html><head><meta http-equiv=\"content-type\" "
     "content=\"text/html; charset=UTF-8\"><title>%@ HTTP fetch log %@</title>",
     processName, dateStamp];
  }
  
  // write style sheets for each hideable element; each style sheet is 
  // customized with our current response number, since they'll share
  // the html page with other responses
  NSString *styleFormat = @"<style type=\"text/css\">div#%@ "
  "{ margin: 0px 20px 0px 20px; display: none; }</style>\n";
  
  [outputHTML appendFormat:styleFormat, requestHeadersName];
  [outputHTML appendFormat:styleFormat, postDataName];
  [outputHTML appendFormat:styleFormat, responseHeadersName];
  [outputHTML appendFormat:styleFormat, responseDataDivName];
  
  if (!didFileExist) {
    // write javascript functions.  The first one shows/hides the layer 
    // containing the iframe.
    NSString *scriptFormat = @"<script type=\"text/javascript\"> "
    "function toggleLayer(whichLayer){ var style2 = document.getElementById(whichLayer).style; "
    "style2.display = style2.display ? \"\":\"block\";}</script>\n";
    [outputHTML appendFormat:scriptFormat];
    
    // the second function is passed the src file; if it's what's shown, it 
    // toggles the iframe's visibility. If some other src is shown, it shows 
    // the iframe and loads the new source.  Note we want to load the source 
    // whenever we show the iframe too since Firefox seems to format it wrong 
    // when showing it if we don't reload it.
    NSString *toggleIFScriptFormat = @"<script type=\"text/javascript\"> "
    "function toggleIFrame(whichLayer,iFrameID,newsrc)"
    "{ \n var iFrameElem=document.getElementById(iFrameID); "
    "if (iFrameElem.src.indexOf(newsrc) != -1) { toggleLayer(whichLayer); } "
    "else { document.getElementById(whichLayer).style.display=\"block\"; } "
    "iFrameElem.src=newsrc; }</script>\n</head>\n<body>\n";
    [outputHTML appendFormat:toggleIFScriptFormat];
  }
  
  // now write the visible html elements
  
  // write the date & time
  [outputHTML appendFormat:@"<b>%@</b><br>", [[NSDate date] description]];
  
  // write the request URL
  [outputHTML appendFormat:@"<b>request:</b> %@ <i>URL:</i> <code>%@</code><br>\n",
   [request HTTPMethod], [request URL]];
  
  // write the request headers, toggleable
  NSDictionary *requestHeaders = [request allHTTPHeaderFields];
  if ([requestHeaders count]) {
    NSString *requestHeadersFormat = @"<a href=\"javascript:toggleLayer('%@');\">"
    "request headers (%d)</a><div id=\"%@\"><pre>%@</pre></div><br>\n";
    [outputHTML appendFormat:requestHeadersFormat,
     requestHeadersName, // layer name
     [requestHeaders count],
     requestHeadersName,
     [requestHeaders description]]; // description gives a human-readable dump
  } else {
    [outputHTML appendString:@"<i>Request headers: none</i><br>"];
  }
  
  // write the request post data, toggleable
  NSData *postData = postData_;
  if (loggedStreamData_) { 
    postData = loggedStreamData_;
  }
  
  if ([postData length]) {
    NSString *postDataFormat = @"<a href=\"javascript:toggleLayer('%@');\">"
    "posted data (%d bytes)</a><div id=\"%@\">%@</div><br>\n";
    NSString *postDataStr = [self stringFromStreamData:postData];
    if (postDataStr) {
      NSString *postDataTextAreaFmt = @"<pre>%@</pre>";
      if ([postDataStr rangeOfString:@"<"].location != NSNotFound) {
        postDataTextAreaFmt =  @"<textarea rows=\"15\" cols=\"100\""
        " readonly=true wrap=soft>\n%@\n</textarea>";
      } 
      NSString *cleanedPostData = [self cleanParameterFollowing:@"&Passwd=" 
                                                     fromString:postDataStr];
      NSString *postDataTextArea = [NSString stringWithFormat:
                                    postDataTextAreaFmt,  cleanedPostData];
      
      [outputHTML appendFormat:postDataFormat,
       postDataName, // layer name
       [postData length],
       postDataName,
       postDataTextArea];
    }
  } else {
    // no post data
  }
  
  // write the response status, MIME type, URL
  if (response) {
    NSString *statusString = @"";
    if ([response respondsToSelector:@selector(statusCode)]) {
      NSInteger status = [(NSHTTPURLResponse *)response statusCode];
      statusString = @"200";
      if (status != 200) {
        // purple for errors
        statusString = [NSString stringWithFormat:@"<FONT COLOR=\"#FF00FF\">%d</FONT>",
                        status];
      }
    }
    
    // show the response URL only if it's different from the request URL
    NSString *responseURLStr =  @"";
    NSURL *responseURL = [response URL];
    
    if (responseURL && ![responseURL isEqual:[request URL]]) {
      NSString *responseURLFormat = @"<br><FONT COLOR=\"#FF00FF\">response URL:"
      "</FONT> <code>%@</code>";
      responseURLStr = [NSString stringWithFormat:responseURLFormat,
                        [responseURL absoluteString]];
    }
    
    NSDictionary *responseHeaders = nil;
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
      responseHeaders = [(NSHTTPURLResponse *)response allHeaderFields];
    }
    [outputHTML appendFormat:@"<b>response:</b> <i>status:</i> %@ <i>  "
     "&nbsp;&nbsp;&nbsp;MIMEType:</i><code> %@</code>%@<br>\n",
     statusString,
     [response MIMEType], 
     responseURLStr,
     responseHeaders ? [responseHeaders description] : @""];
    
    // write the response headers, toggleable
    if ([responseHeaders count]) {
      
      NSString *cookiesSet = [responseHeaders objectForKey:@"Set-Cookie"];
      
      NSString *responseHeadersFormat = @"<a href=\"javascript:toggleLayer("
      "'%@');\">response headers (%d)  %@</a><div id=\"%@\"><pre>%@</pre>"
      "</div><br>\n";
      [outputHTML appendFormat:responseHeadersFormat,
       responseHeadersName,
       [responseHeaders count],
       (cookiesSet ? @"<i>sets cookies</i>" : @""),
       responseHeadersName,
       [responseHeaders description]];
      
    } else {
      [outputHTML appendString:@"<i>Response headers: none</i><br>\n"];
    }
  }
  
  // error
  if (error) {
    [outputHTML appendFormat:@"<b>error:</b> %@ <br>\n", [error description]];
  }
  
  // write the response data.  We have links to show formatted and text
  //   versions, but they both show it in the same iframe, and both
  //   links also toggle visible/hidden
  if (responseDataFormattedFileName || responseDataUnformattedFileName) {
    
    // response data, toggleable links -- formatted and text versions
    if (responseDataFormattedFileName) {
      [outputHTML appendFormat:@"response data (%d bytes) formatted <b>%@</b> ",
       responseDataLength, 
       [responseDataFormattedFileName pathExtension]];
      
      // inline (iframe) link
      NSString *responseInlineFormattedDataNameFormat = @"&nbsp;&nbsp;<a "
      "href=\"javascript:toggleIFrame('%@','%@','%@');\">inline</a>\n";
      [outputHTML appendFormat:responseInlineFormattedDataNameFormat,
       responseDataDivName, // div ID
       dataIFrameID, // iframe ID (for reloading)
       responseDataFormattedFileName]; // src to reload 
      
      // plain link (so the user can command-click it into another tab)
      [outputHTML appendFormat:@"&nbsp;&nbsp;<a href=\"%@\">stand-alone</a><br>\n",
       [responseDataFormattedFileName
        stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if (responseDataUnformattedFileName) {
      [outputHTML appendFormat:@"response data (%d bytes) plain text ",
       responseDataLength];
      
      // inline (iframe) link
      NSString *responseInlineDataNameFormat = @"&nbsp;&nbsp;<a href=\""
      "javascript:toggleIFrame('%@','%@','%@');\">inline</a> \n";
      [outputHTML appendFormat:responseInlineDataNameFormat,
       responseDataDivName, // div ID
       dataIFrameID, // iframe ID (for reloading)
       responseDataUnformattedFileName]; // src to reload 
      
      // plain link (so the user can command-click it into another tab)
      [outputHTML appendFormat:@"&nbsp;&nbsp;<a href=\"%@\">stand-alone</a><br>\n",
       [responseDataUnformattedFileName
        stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    // make the iframe
    NSString *divHTMLFormat = @"<div id=\"%@\">%@</div><br>\n";
    NSString *src = responseDataFormattedFileName ?  
    responseDataFormattedFileName : responseDataUnformattedFileName;
    NSString *escapedSrc = [src stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *iframeFmt = @" <iframe src=\"%@\" id=\"%@\" width=800 height=400>"
    "\n<a href=\"%@\">%@</a>\n </iframe>\n";
    NSString *dataIFrameHTML = [NSString stringWithFormat:iframeFmt,
                                escapedSrc, dataIFrameID, escapedSrc, src];
    [outputHTML appendFormat:divHTMLFormat, 
     responseDataDivName, dataIFrameHTML];
  } else {
    // could not parse response data; just show the length of it
    [outputHTML appendFormat:@"<i>Response data: %d bytes </i>\n", 
     responseDataLength];
  }
  
  [outputHTML appendString:@"<br><hr><p>"];
  
  // append the HTML to the main output file
  const char* htmlBytes = [outputHTML UTF8String];
  NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath 
                                                             append:YES];
  [stream open];
  [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)];
  [stream close];
  
  // make a symlink to the latest html
  NSString *symlinkName = [NSString stringWithFormat:@"%@_http_log_newest.html", 
                           processName];
  NSString *symlinkPath = [logDirectory stringByAppendingPathComponent:symlinkName];
  
  // removeFileAtPath might be going away, but removeItemAtPath does not exist
  // in 10.4
  if ([fileManager respondsToSelector:@selector(removeFileAtPath:handler:)]) {
    [fileManager removeFileAtPath:symlinkPath handler:nil];
  } else if ([fileManager respondsToSelector:@selector(removeItemAtPath:error:)]) {
    // To make the next line compile when targeting 10.4, we declare
    // removeItemAtPath:error: in an @interface above
    [fileManager removeItemAtPath:symlinkPath error:NULL];
  }
  
  [fileManager createSymbolicLinkAtPath:symlinkPath pathContent:htmlPath];
}

- (void)logCapturePostStream {

#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
  // This is called when beginning a fetch.  The caller should have already
  // verified that logging is enabled, and should have allocated 
  // loggedStreamData_ as a mutable object.
  
  // If we're logging, we need to wrap the upload stream with our monitor
  // stream subclass that will call us back with the bytes being read from the
  // stream
  
  // our wrapper will retain the old post stream
  [postStream_ autorelease];
  
  // length can be 
  postStream_ = [GTMInputStreamLogger inputStreamWithStream:postStream_
                                                     length:0];
  [postStream_ retain];

  // we don't really want monitoring callbacks; our subclass will be
  // calling our appendLoggedStreamData: method at every read instead
  [(GTMInputStreamLogger *)postStream_ setMonitorDelegate:self
                                                 selector:nil];
#endif // GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
}

- (void)appendLoggedStreamData:(NSData *)newData {
  [loggedStreamData_ appendData:newData];
}

#endif // GTM_HTTPFETCHER_ENABLE_LOGGING
@end

#if GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING
@implementation GTMInputStreamLogger
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
  
  // capture the read stream data, and pass it to the delegate to append to
  NSInteger result = [super read:buffer maxLength:len];
  if (result >= 0) {
    NSData *data = [NSData dataWithBytes:buffer length:result];
    [monitorDelegate_ appendLoggedStreamData:data];
  }
  return result;
}
@end
#endif // GTM_HTTPFETCHER_ENABLE_INPUTSTREAM_LOGGING