File: GSHTTPURLHandle.m

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (2018 lines) | stat: -rw-r--r-- 53,663 bytes parent folder | download | duplicates (2)
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
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
/** GSHTTPURLHandle.m - Class GSHTTPURLHandle
   Copyright (C) 2000 Free Software Foundation, Inc.

   Written by: 		Mark Allison <mark@brainstorm.co.uk>
   Integrated by:	Richard Frith-Macdonald <rfm@gnu.org>
   Date:		November 2000 		

   This file is part of the GNUstep Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
*/

#import "common.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSEnumerator.h"
#import "Foundation/NSByteOrder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSException.h"
#import "Foundation/NSFileHandle.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSProcessInfo.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSURL.h"
#import "Foundation/NSURLHandle.h"
#import "Foundation/NSValue.h"
#import "GNUstepBase/GSMime.h"
#import "GNUstepBase/GSTLS.h"
#import "GNUstepBase/NSData+GNUstepBase.h"
#import "GNUstepBase/NSString+GNUstepBase.h"
#import "GNUstepBase/NSURL+GNUstepBase.h"
#import "NSCallBacks.h"
#import "GSURLPrivate.h"
#import "GSPrivate.h"

#ifdef	HAVE_SYS_FILE_H
#  include <sys/file.h>
#endif

#if	defined(HAVE_SYS_FCNTL_H)
#  include <sys/fcntl.h>
#elif	defined(HAVE_FCNTL_H)
#  include <fcntl.h>
#endif

#ifdef	HAVE_SYS_SOCKET_H
#  include <sys/socket.h>		// For MSG_PEEK, etc
#endif

@interface GSMimeHeader (HTTPRequest)
- (void) addToBuffer: (NSMutableData*)buf
             masking: (NSMutableData**)masked;
@end

/*
 * Implement map keys for strings with case insensitive comparisons,
 * so we can have case insensitive matching of http headers (correct
 * behavior), but actually preserve case of headers stored and written
 * in case the remote server is buggy and requires particular
 * captialisation of headers (some http software is faulty like that).
 */
static NSUInteger
_id_hash(void *table, NSString* o)
{
  return [[o uppercaseString] hash];
}

static BOOL
_id_is_equal(void *table, NSString *o, NSString *p)
{
  return ([o caseInsensitiveCompare: p] == NSOrderedSame) ? YES : NO;
}

typedef NSUInteger (*NSMT_hash_func_t)(NSMapTable *, const void *);
typedef BOOL (*NSMT_is_equal_func_t)(NSMapTable *, const void *, const void *);
typedef void (*NSMT_retain_func_t)(NSMapTable *, const void *);
typedef void (*NSMT_release_func_t)(NSMapTable *, void *);
typedef NSString *(*NSMT_describe_func_t)(NSMapTable *, const void *);

static const NSMapTableKeyCallBacks writeKeyCallBacks =
{
  (NSMT_hash_func_t) _id_hash,
  (NSMT_is_equal_func_t) _id_is_equal,
  (NSMT_retain_func_t) _NS_id_retain,
  (NSMT_release_func_t) _NS_id_release,
  (NSMT_describe_func_t) _NS_id_describe,
  NSNotAPointerMapKey
};

static NSString	*httpVersion = @"1.1";

@interface GSHTTPURLHandle : NSURLHandle
{
  BOOL			tunnel;
  BOOL			debug;
  BOOL			keepalive;
  BOOL			returnAll;
  BOOL                  inResponse;
  id<GSLogDelegate>     ioDelegate;
  unsigned char		challenged;
  NSFileHandle          *sock;
  NSTimeInterval        cacheAge;
  NSString              *urlKey;
  NSURL                 *url;
  NSURL                 *u;
  NSURL                 *proxyURL;
  NSMutableData         *dat;
  GSMimeParser		*parser;
  GSMimeDocument	*document;
  NSMutableDictionary   *pageInfo;
  NSMapTable            *wProperties;
  NSData		*wData;
  NSMutableDictionary   *request;
  unsigned int          bodyPos;
  unsigned int		redirects;
  enum {
    idle,
    connecting,
    writing,
    reading,
  } connectionState;
@public
  NSString      *in;
  NSString      *out;
}
+ (void) setMaxCached: (NSUInteger)limit;
- (void) _tryLoadInBackground: (NSURL*)fromURL;
- (id<GSLogDelegate>) setDebugLogDelegate: (id<GSLogDelegate>)d;
@end

/**
 * <p>
 *   This is a <em>PRIVATE</em> subclass of NSURLHandle.
 *   It is documented here in order to give you information about the
 *   default behavior of an NSURLHandle created to deal with a URL
 *   that has either the <code>http</code> or <code>https</code> scheme.
 *   The name and/or other implementation details of this class
 *   may be changed at any time.
 * </p>
 * <p>
 *   A GSHTTPURLHandle instance is used to manage connections to
 *   <code>http</code> and <code>https</code> URLs.
 *    Secure connections are handled automatically
 *   (using openSSL) for URLs with the scheme <code>https</code>.
 *   Connection via proxy server is supported, as is proxy tunneling
 *   for secure connections.  Basic parsing of <code>http</code>
 *   headers is performed to extract <code>http</code> status
 *   information, cookies etc.  Cookies are
 *   retained and automatically sent during subsequent requests where
 *   the cookie is valid.
 * </p>
 * <p>
 *   Header information from the current page may be obtained using
 *   -propertyForKey and -propertyForKeyIfAvailable.  <code>HTTP</code>
 *   status information can be retrieved as by calling either of these
 *   methods specifying one of the following keys:
 * </p>
 * <list>
 *   <item>
 *     NSHTTPPropertyStatusCodeKey - numeric status code
 *   </item>
 *   <item>
 *     NSHTTPPropertyStatusReasonKey - text describing status
 *   </item>
 *   <item>
 *     NSHTTPPropertyServerHTTPVersionKey - <code>http</code>
 *     version supported by remote server
 *   </item>
 * </list>
 * <p>
 *   According to MacOS-X headers, the following should also
 *   be supported, but currently are not:
 * </p>
 * <list>
 *   <item>NSHTTPPropertyRedirectionHeadersKey</item>
 *   <item>NSHTTPPropertyErrorPageDataKey</item>
 * </list>
 * <p>
 *   The omission of these headers is not viewed as important at
 *   present, since the MacOS-X public beta implementation doesn't
 *   work either.
 * </p>
 * <p>
 *   Other calls to -propertyForKey and -propertyForKeyIfAvailable may
 *   be made specifying a <code>http</code> header field name.
 *   For example specifying a key name of &quot;Content-Length&quot;
 *   would return the value of the &quot;Content-Length&quot; header
 *   field.
 * </p>
 * <p>
 *   [GSHTTPURLHandle-writeProperty:forKey:]
 *   can be used to specify the parameters
 *   for the <code>http</code> request.  The default request uses the
 *   &quot;GET&quot; method when fetching a page, and the
 *   &quot;POST&quot; method when using -writeData:.
 *   This can be over-ridden by calling -writeProperty:forKey: with
 *   the key name &quot;GSHTTPPropertyMethodKey&quot; and specifying an
 *   alternative method (i.e &quot;PUT&quot;).
 * </p>
 * <p>
 *   A Proxy may be specified by calling -writeProperty:forKey: to set a
 *   URL as the value for either https_proxy or http_proxy.<br />
 *   For backward compatibility a proxy may also be specified by calling
 *   -writeProperty:forKey:
 *   with the keys &quot;GSHTTPPropertyProxyHostKey&quot; and
 *   &quot;GSHTTPPropertyProxyPortKey&quot; to set the host and port
 *   of the proxy server respectively.<br />
 *   The proxy property can specify either the IP address or the hostname of
 *   the proxy server.  If an attempt is made to load a page via a
 *   secure connection when a proxy is specified, GSHTTPURLHandle will
 *   attempt to open an SSL Tunnel through the proxy.
 * </p>
 * <p>
 *   Requests to the remote server may be forced to be bound to a
 *   particular local IP address by using the key
 *   &quot;GSHTTPPropertyLocalHostKey&quot;  which must contain the
 *   IP address of a network interface on the local host.
 * </p>
 */
@implementation GSHTTPURLHandle

static NSMutableDictionary	*urlCache = nil;
static NSMutableArray		*urlOrder = nil;
static NSLock			*urlLock = nil;
static NSUInteger               maxCached = 16;

static Class			sslClass = 0;

static void
debugRead(GSHTTPURLHandle *handle, NSData *data)
{
  int   	len = (int)[data length];
  const uint8_t	*ptr = (const uint8_t*)[data bytes];
  uint8_t       *hex;
  NSUInteger    hl;
  int           pos;

  hl = ((len + 2) / 3) * 4;
  hex = malloc(hl + 1);
  hex[hl] = '\0';
  GSPrivateEncodeBase64(ptr, (NSUInteger)len, hex);
  for (pos = 0; pos < len; pos++)
    {
      if (0 == ptr[pos])
        {
          char  *esc = [data escapedRepresentation: 0];

          NSLog(@"Read for %p %@ of %d bytes (escaped) - '%s'\n<[%s]>",
            handle, handle->in, len, esc, hex); 
          free(esc);
          free(hex);
          return;
        }
    }
  NSLog(@"Read for %p %@ of %d bytes - '%*.*s'\n<[%s]>",
    handle, handle->in, len, len, len, ptr, hex); 
  free(hex);
}
static void
debugWrite(GSHTTPURLHandle *handle, NSData *data)
{
  int	        len = (int)[data length];
  const uint8_t	*ptr = (const uint8_t*)[data bytes];
  uint8_t       *hex;
  NSUInteger    hl;
  int           pos;

  hl = ((len + 2) / 3) * 4;
  hex = malloc(hl + 1);
  hex[hl] = '\0';
  GSPrivateEncodeBase64(ptr, (NSUInteger)len, hex);
  for (pos = 0; pos < len; pos++)
    {
      if (0 == ptr[pos])
        {
          char  *esc = [data escapedRepresentation: 0];

          NSLog(@"Write for %p %@ of %d bytes (escaped) - '%s'\n<[%s]>",
            handle, handle->out, len, esc, hex); 
          free(esc);
          free(hex);
          return;
        }
    }
  NSLog(@"Write for %p %@ of %d bytes - '%*.*s'\n<[%s]>",
    handle, handle->out, len, len, len, ptr, hex); 
  free(hex);
}

+ (NSURLHandle*) cachedHandleForURL: (NSURL*)newUrl
{
  NSURLHandle	*obj = nil;
  NSString      *s = [newUrl scheme];

  if ([s caseInsensitiveCompare: @"http"] == NSOrderedSame
    || [s caseInsensitiveCompare: @"https"] == NSOrderedSame)
    {
      NSString	*k = [newUrl cacheKey];

      //NSLog(@"Lookup for handle for '%@'", newUrl);
      [urlLock lock];
      obj = RETAIN([urlCache objectForKey: k]);
      if (obj != nil)
        {
          ASSIGN(((GSHTTPURLHandle*)obj)->url, newUrl);
	  [urlOrder removeObjectIdenticalTo: obj];
	  [urlOrder addObject: obj];
	}
      [urlLock unlock];
      //NSLog(@"Found handle %@", obj);
    }
  return AUTORELEASE(obj);
}

+ (void) initialize
{
  if (self == [GSHTTPURLHandle class])
    {
      urlCache = [NSMutableDictionary new];
      [[NSObject leakAt: &urlCache] release];
      urlOrder = [NSMutableArray new];
      [[NSObject leakAt: &urlOrder] release];
      urlLock = [NSLock new];
      [[NSObject leakAt: &urlLock] release];
      sslClass = [NSFileHandle sslClass];
    }
}

+ (void) setMaxCached: (NSUInteger)limit
{
  maxCached = limit;
}

- (void) _disconnect
{
  if (sock)
    {
      NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];

      [nc removeObserver: self name: nil object: sock];
      [sock closeFile];
      DESTROY(sock);
    }
  DESTROY(in);
  DESTROY(out);
  connectionState = idle;
}

- (void) dealloc
{
  [self _disconnect];
  DESTROY(out);
  DESTROY(in);
  DESTROY(u);
  DESTROY(urlKey);
  DESTROY(url);
  DESTROY(proxyURL);
  DESTROY(dat);
  DESTROY(parser);
  DESTROY(document);
  DESTROY(pageInfo);
  DESTROY(wData);
  if (wProperties != 0)
    {
      NSFreeMapTable(wProperties);
    }
  DESTROY(request);
  [super dealloc];
}

- (id) initWithURL: (NSURL*)newUrl
	    cached: (BOOL)cached
{
  if ((self = [super initWithURL: newUrl cached: cached]) != nil)
    {
      debug = GSDebugSet(@"NSURLHandle");
      dat = [NSMutableData new];
      pageInfo = [NSMutableDictionary new];
      wProperties = NSCreateMapTable(writeKeyCallBacks,
	NSObjectMapValueCallBacks, 8);
      request = [NSMutableDictionary new];

      ASSIGN(url, newUrl);
      ASSIGN(urlKey, [newUrl cacheKey]);
      connectionState = idle;
      if (cached == YES)
        {
	  GSHTTPURLHandle	*obj;

	  [urlLock lock];
	  obj = [urlCache objectForKey: urlKey];
	  [urlCache setObject: self forKey: urlKey];
	  if (obj != nil)
	    {
	      [urlOrder removeObjectIdenticalTo: obj];
	    }
	  [urlOrder addObject: self];
	  while ([urlOrder count] > maxCached)
	    {
	      obj = [urlOrder objectAtIndex: 0];
              obj->cacheAge = 0.0;      // Not to be re-cached
	      [urlCache removeObjectForKey: obj->urlKey];
	      [urlOrder removeObjectAtIndex: 0];
	    }
	  [urlLock unlock];
	  //NSLog(@"Cache handle %p for '%@'", self, newUrl);
	}
    }
  return self;
}

+ (BOOL) canInitWithURL: (NSURL*)newUrl
{
  NSString      *scheme = [newUrl scheme];

  if ([scheme isEqualToString: @"http"]
    || [scheme isEqualToString: @"https"])
    {
      return YES;
    }
  return NO;
}

- (void) bgdApply: (NSString*)basic
{
  NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];
  NSMutableString	*s;
  NSString              *key;
  NSString		*val;
  NSMutableData		*buf;
  NSMutableData		*masked = nil;
  NSString		*version;
  NSMapEnumerator       enumerator;

  RETAIN(self);
  if (debug)
    {
      NSLog(@"%@ %p %@ %s",
        NSStringFromSelector(_cmd), self, out,
        (keepalive ? "re-used connection" : "initial connection"));
    }

  s = [basic mutableCopy];
  if ([[u query] length] > 0)
    {
      [s appendFormat: @"?%@", [u query]];
    }

  version = [request objectForKey: NSHTTPPropertyServerHTTPVersionKey];
  if (version == nil)
    {
      version = httpVersion;
    }
  [s appendFormat: @" HTTP/%@\r\n", version];

  if ((id)NSMapGet(wProperties, (void*)@"Host") == nil)
    {
      NSString  *s = [u scheme];
      id	p = [u port];
      id	h = [u host];

      if (h == nil)
	{
	  h = @"";	// Must use an empty host header
	}
      if (([s isEqualToString: @"http"] && [p intValue] == 80)
        || ([s isEqualToString: @"https"] && [p intValue] == 443))
        {
          /* Some buggy systems object to the port being in the Host
           * header when it's the default (optional) value.  To keep
           * them happy let's omit it in those cases.
           */
          p = nil;
        }
      if (nil == p)
	{
          NSMapInsert(wProperties, (void*)@"Host", (void*)h);
	}
      else
	{
          NSMapInsert(wProperties, (void*)@"Host",
	    (void*)[NSString stringWithFormat: @"%@:%@", h, p]);
	}
    }

  /* Ensure we set the correct content length (may be zero)
   */
  if ((id)NSMapGet(wProperties, (void*)@"Content-Length") == nil)
    {
      NSMapInsert(wProperties, (void*)@"Content-Length",
        (void*)[NSString stringWithFormat: @"%"PRIuPTR, [wData length]]);
    }

  if ([wData length] > 0)
    {
      /*
       * Assume content type if not specified.
       */
      if ((id)NSMapGet(wProperties, (void*)@"Content-Type") == nil)
	{
	  NSMapInsert(wProperties, (void*)@"Content-Type",
	    (void*)@"application/x-www-form-urlencoded");
	}
    }

  if ((id)NSMapGet(wProperties, (void*)@"Authorization") == nil)
    {
      NSURLProtectionSpace	*space;

      /*
       * If we have username/password stored in the URL, and there is a
       * known protection space for that URL, we generate an authentication
       * header.
       */
      if ([u user] != nil
	&& (space = [GSHTTPAuthentication protectionSpaceForURL: u]) != nil)
	{
	  NSString		*auth;
	  GSHTTPAuthentication	*authentication;
	  NSURLCredential	*cred;
	  NSString		*method;

	  /* Create credential from user and password stored in the URL.
	   * Returns nil if we have no username or password.
	   */
	  cred = [[NSURLCredential alloc]
	    initWithUser: [u user]
	    password: [u password]
	    persistence: NSURLCredentialPersistenceForSession];

	  if (cred == nil)
	    {
	      authentication = nil;
	    }
	  else
	    {
	      /* Create authentication from credential ... returns nil if
	       * we have no credential.
	       */
	      authentication = [GSHTTPAuthentication
		authenticationWithCredential: cred
		inProtectionSpace: space];
	      RELEASE(cred);
	    }

	  method = [request objectForKey: GSHTTPPropertyMethodKey];
	  if (method == nil)
	    {
	      if ([wData length] > 0)
		{
		  method = @"POST";
		}
	      else
		{
		  method = @"GET";
		}
	    }

	  auth = [authentication authorizationForAuthentication: nil
	    method: method
	    path: [u pathWithEscapes]];
	  /* If authentication is nil then auth will also be nil
	   */
	  if (auth != nil)
	    {
	      [self writeProperty: auth forKey: @"Authorization"];
	    }
	}
    }

  buf = [[s dataUsingEncoding: NSISOLatin1StringEncoding] mutableCopy];

  enumerator = NSEnumerateMapTable(wProperties);
  while (NSNextMapEnumeratorPair(&enumerator, (void **)(&key), (void**)&val))
    {
      GSMimeHeader      *h;

      h = [[GSMimeHeader alloc] initWithName: key value: val parameters: nil];
      if (debug || masked)
	{
	  [h addToBuffer: buf masking: &masked];
  	}
      else
	{
	  [h addToBuffer: buf masking: NULL];
	}
      RELEASE(h);
    }
  NSEndMapTableEnumeration(&enumerator);

  [buf appendBytes: "\r\n" length: 2];
  if (masked)
    {
      [masked appendBytes: "\r\n" length: 2];
    }

  /*
   * Append any data to be sent
   */
  if (wData != nil)
    {
      [buf appendData: wData];
      if (masked)
	{
	  [masked appendData: wData];
	}
    }

  /*
   * Watch for write completion.
   */
  [nc addObserver: self
         selector: @selector(bgdWrite:)
             name: GSFileHandleWriteCompletionNotification
           object: sock];
  connectionState = writing;

  /*
   * Send request to server.
   */
  if (debug)
    {
      if (nil == masked)
	{
	  masked = buf;		// Just log unmasked data
	}
      if (NO == [ioDelegate putBytes: [masked bytes]
                            ofLength: [masked length]
                            byHandle: self])
        {
          debugWrite(self, masked);
        }
    }
  [sock writeInBackgroundAndNotify: buf];
  RELEASE(buf);
  RELEASE(s);
  DESTROY(self);
}

- (void) bgdRead: (NSNotification*) not
{
  NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];
  NSDictionary		*dict = [not userInfo];
  NSData		*d;
  NSRange		r;
  unsigned		readCount;

  RETAIN(self);

  if (debug)
    NSLog(@"%@ %p %s", NSStringFromSelector(_cmd), self, keepalive?"K":"");
  d = [dict objectForKey: NSFileHandleNotificationDataItem];
  readCount = [d length];
  if (debug)
    {
      if (NO == [ioDelegate getBytes: [d bytes]
                            ofLength: readCount
                            byHandle: self])
        {
          debugRead(self, d);
        }
    }

  if (connectionState == idle)
    {
      /*
       * We received an event on a handle which is not in use ...
       * it should just be the connection being closed by the other
       * end because of a timeout etc.
       */
      if (debug)
	{
          NSUInteger    length = [d length];

          if (length > 0)
            {
              if (nil == ioDelegate)
                {
                  NSLog(@"%@ %p %s Unexpected data (%*.*s) from remote!",
                    NSStringFromSelector(_cmd), self, keepalive?"K":"",
                    (int)[d length], (int)[d length], (char*)[d bytes]);
                }
              else
                {
                  NSLog(@"%@ %p %s Unexpected data from remote!",
                    NSStringFromSelector(_cmd), self, keepalive?"K":"");
                  if (NO == [ioDelegate getBytes: [d bytes]
                                        ofLength: length
                                        byHandle: self])
                    {
                      NSLog(@"%@ %p %s (%*.*s)",
                        NSStringFromSelector(_cmd), self, keepalive?"K":"",
                        (int)[d length], (int)[d length], (char*)[d bytes]);
                    }
                }
            }
	}
      [self _disconnect];
    }
  else if (0 == readCount && NO == inResponse && YES == keepalive)
    {
      /* On a keepalive connection where the remote end
       * dropped the connection without responding.  We
       * should try again.
       */
      if (connectionState != idle)
        {
          [self _disconnect];
          if (debug)
            {
              NSLog(@"%@ %p restart on new connection",
                NSStringFromSelector(_cmd), self);
            }
          [self _tryLoadInBackground: u];
        }
    }
  else if ([parser parse: d] == NO && [parser isComplete] == NO)
    {
      inResponse = YES;
      if (debug)
	{
	  NSLog(@"HTTP parse failure - %@", parser);
	}
      [self endLoadInBackground];
      [self backgroundLoadDidFailWithReason: @"Response parse failed"];
    }
  else
    {
      BOOL	complete;

      inResponse = YES;
      complete = [parser isComplete];
      if (complete == NO && [parser isInHeaders] == NO)
	{
	  GSMimeHeader	*info;
	  NSString	*enc;
	  NSString	*len;
	  int		status;

	  info = [document headerNamed: @"http"];
	  status = [[info objectForKey: NSHTTPPropertyStatusCodeKey] intValue];
	  len = [[document headerNamed: @"content-length"] value];
	  enc = [[document headerNamed: @"content-transfer-encoding"] value];
	  if (enc == nil)
	    {
	      enc = [[document headerNamed: @"transfer-encoding"] value];
	    }

	  if (status == 204 || status == 304)
	    {
	      complete = YES;	// No body expected.
	    }
	  else if ([enc isEqualToString: @"chunked"] == YES)	
	    {
	      complete = NO;	// Read chunked body data
	    }
	  else if (nil != len && [len intValue] == 0)
	    {
	      complete = YES;	// content-length explicitly zero
	    }
	  if (complete == NO && [d length] == 0)
	    {
	      complete = YES;	// Had EOF ... terminate
	    }
	}
      if (complete == YES)
	{
	  GSMimeHeader	*info;
	  NSString	*val;
	  NSNumber	*num;
	  float		ver;
	  int		code;

	  connectionState = idle;
	  [nc removeObserver: self name: nil object: sock];

	  ver = [[[document headerNamed: @"http"] value] floatValue];
	  if (ver < 1.1)
	    {
              [self _disconnect];
	    }
	  else if (nil != (val = [[document headerNamed: @"connection"] value]))
	    {
	      val = [val lowercaseString];
	      if (YES == [val isEqualToString: @"close"])
		{
                  [self _disconnect];
		}
	      else if ([val length] > 5)
		{
		  NSEnumerator	*e;

		  e = [[val componentsSeparatedByString: @","]
		    objectEnumerator];
		  while (nil != (val = [e nextObject]))
		    {
		      val = [val stringByTrimmingSpaces];
		      if (YES == [val isEqualToString: @"close"])
			{
                          [self _disconnect];
			  break;
			}
		    }
		}
	    }

	  /*
	   * Retrieve essential keys from document
	   */
	  info = [document headerNamed: @"http"];
	  num = [info objectForKey: NSHTTPPropertyStatusCodeKey];
	  code = [num intValue];
	  if (code == 401 && self->challenged < 2)
	    {
	      GSMimeHeader	*ah;

	      self->challenged++;	// Prevent repeated challenge/auth
	      if ((ah = [document headerNamed: @"WWW-Authenticate"]) != nil)
		{
	          NSURLProtectionSpace	*space;
		  NSString		*ac;
		  GSHTTPAuthentication	*authentication;
		  NSString		*method;
		  NSString		*auth;

		  ac = [ah value];
		  space = [GSHTTPAuthentication
		    protectionSpaceForAuthentication: ac requestURL: url];
		  if (space == nil)
		    {
		      authentication = nil;
		    }
		  else
		    {
		      NSURLCredential	*cred;

		      /*
		       * Create credential from user and password
		       * stored in the URL.
		       * Returns nil if we have no username or password.
		       */
		      cred = [[NSURLCredential alloc]
			initWithUser: [url user]
			password: [url password]
			persistence: NSURLCredentialPersistenceForSession];

		      if (cred == nil)
		        {
			  authentication = nil;
			}
		      else
		        {
			  /*
			   * Get the digest object and ask it for a header
			   * to use for authorisation.
			   * Returns nil if we have no credential.
			   */
			  authentication = [GSHTTPAuthentication
			    authenticationWithCredential: cred
			    inProtectionSpace: space];
			  RELEASE(cred);
			}
		    }

		  method = [request objectForKey: GSHTTPPropertyMethodKey];
		  if (method == nil)
		    {
		      if ([wData length] > 0)
			{
			  method = @"POST";
			}
		      else
			{
			  method = @"GET";
			}
		    }

		  auth = [authentication authorizationForAuthentication: ac
		    method: method
		    path: [url pathWithEscapes]];
		  if (auth != nil)
		    {
		      [self writeProperty: auth forKey: @"Authorization"];
		      [self _tryLoadInBackground: u];
                      RELEASE(self);
		      return;	// Retrying.
		    }
		}
	    }
	  if (num != nil)
	    {
	      [pageInfo setObject: num forKey: NSHTTPPropertyStatusCodeKey];
	    }
	  val = [info objectForKey: NSHTTPPropertyServerHTTPVersionKey];
	  if (val != nil)
	    {
	      [pageInfo setObject: val
			   forKey: NSHTTPPropertyServerHTTPVersionKey];
	    }
	  val = [info objectForKey: NSHTTPPropertyStatusReasonKey];
	  if (val != nil)
	    {
	      [pageInfo setObject: val forKey: NSHTTPPropertyStatusReasonKey];
	    }
	  /*
	   * Tell superclass that we have successfully loaded the data.
	   */
	  d = [parser data];
	  r = NSMakeRange(bodyPos, [d length] - bodyPos);
	  bodyPos = 0;
	  DESTROY(wData);
	  NSResetMapTable(wProperties);
          connectionState = idle;       // Finished I/O
	  if (returnAll || (code >= 200 && code < 300))
	    {
	      [self didLoadBytes: [d subdataWithRange: r]
		    loadComplete: YES];
	    }
	  else
	    {
	      [self didLoadBytes: [d subdataWithRange: r]
		    loadComplete: NO];
	      [self cancelLoadInBackground];
	    }
	}
      else
	{
	  /*
	   * Report partial data if possible.
	   */
	  if ([parser isInBody])
	    {
	      d = [parser data];
	      r = NSMakeRange(bodyPos, [d length] - bodyPos);
	      bodyPos = [d length];
	      [self didLoadBytes: [d subdataWithRange: r]
		    loadComplete: NO];
	    }
	}

      if (complete == NO && readCount == 0)
        {
	  /* The read failed ... dropped, but parsing is not complete.
	   * The request was sent, so we can't know whether it was
	   * lost in the network or the remote end received it and
	   * the response was lost.
	   */
	  if (debug)
	    {
	      NSLog(@"HTTP response not received - %@", parser);
	    }
	  [self endLoadInBackground];
          [self backgroundLoadDidFailWithReason: @"Response parse failed"];
	}

      if (sock != nil && connectionState == reading)
	{
          if ([sock readInProgress] == NO)
	    {
	      [sock readInBackgroundAndNotify];
	    }
	}
    }
  DESTROY(self);
}

- (void) bgdTunnelRead: (NSNotification*) not
{
  NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];
  NSDictionary		*dict = [not userInfo];
  NSData		*d;
  GSMimeParser		*p;
  unsigned		readCount;

  RETAIN(self);
  if (debug)
    {
      NSLog(@"%@ %p %s", NSStringFromSelector(_cmd), self, keepalive?"K":"");
    }
  d = [dict objectForKey: NSFileHandleNotificationDataItem];
  readCount = [d length];
  if (debug)
    {
      if (NO == [ioDelegate getBytes: [d bytes]
                            ofLength: [d length]
                            byHandle: self])
        {
          debugRead(self, d);
        }
    }

  if (readCount > 0)
    {
      inResponse = YES;
      [dat appendData: d];
    }
  else if (NO == inResponse)
    {
      /* remote end dropped the connection without responding
       */
      [self _disconnect];
      if (debug)
        {
          NSLog(@"%@ %p restart on new connection",
            NSStringFromSelector(_cmd), self);
        }
      [self _tryLoadInBackground: u];
      DESTROY(self);
      return;
    }

  p = [GSMimeParser new];
  [p parse: dat];
  if ([p isInBody] == YES || [d length] == 0)
    {
      GSMimeHeader	*info;
      NSString		*val;
      NSNumber		*num;

      [p parse: nil];
      info = [[p mimeDocument] headerNamed: @"http"];
      val = [info objectForKey: NSHTTPPropertyServerHTTPVersionKey];
      if (val != nil)
	[pageInfo setObject: val forKey: NSHTTPPropertyServerHTTPVersionKey];
      num = [info objectForKey: NSHTTPPropertyStatusCodeKey];
      if (num != nil)
	[pageInfo setObject: num forKey: NSHTTPPropertyStatusCodeKey];
      val = [info objectForKey: NSHTTPPropertyStatusReasonKey];
      if (val != nil)
	[pageInfo setObject: val forKey: NSHTTPPropertyStatusReasonKey];
      [nc removeObserver: self
	            name: NSFileHandleReadCompletionNotification
                  object: sock];
      [dat setLength: 0];
      tunnel = NO;
    }
  else
    {
      if ([sock readInProgress] == NO)
	{
	  [sock readInBackgroundAndNotify];
	}
    }
  RELEASE(p);
  DESTROY(self);
}

- (void) loadInBackground
{
  self->challenged = 0;
  [self _tryLoadInBackground: nil];
}

- (void) endLoadInBackground
{
  DESTROY(wData);
  NSResetMapTable(wProperties);

  /* Socket must be removed from I/O notifications and connection state
   * marked idle, but the socket is already idle it may be re-used for
   * another request.
   */
  if (sock)
    {
      NSNotificationCenter      *nc = [NSNotificationCenter defaultCenter];

      [nc removeObserver: self name: nil object: sock];
      if (connectionState != idle)
	{
	  [sock closeFile];	// Close to cancel any I/O in progress
	  DESTROY(sock);
	}
    }
  connectionState = idle;
  [super endLoadInBackground];
}


- (void) _apply
{
  NSString	*method;
  NSString	*path;
  NSString	*s;

  /*
   * Set up request - differs for proxy version unless tunneling via ssl.
   */
  path = [[u pathWithEscapes] stringByTrimmingSpaces];
  if ([path length] == 0)
    {
      path = @"/";
    }

  method = [request objectForKey: GSHTTPPropertyMethodKey];
  if (method == nil)
    {
      if ([wData length] > 0)
	{
	  method = @"POST";
	}
      else
	{
	  method = @"GET";
	}
    }

  if (proxyURL
    && [[u scheme] isEqualToString: @"https"] == NO)
    {
      if ([u port] == nil)
	{
	  s = [[NSString alloc] initWithFormat: @"%@ http://%@%@",
	    method, [u host], path];
	}
      else
	{
	  s = [[NSString alloc] initWithFormat: @"%@ http://%@:%@%@",
	    method, [u host], [u port], path];
	}
    }
  else    // no proxy
    {
      s = [[NSString alloc] initWithFormat: @"%@ %@",
	method, path];
    }

  [self bgdApply: s];
  RELEASE(s);
}


- (void) bgdConnect: (NSNotification*)notification
{
  NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];
  NSDictionary          *userInfo = [notification userInfo];
  NSString		*e;

  [nc removeObserver: self
                name: GSFileHandleConnectCompletionNotification
              object: sock];

  /*
   * See if the connection attempt caused an error.
   */
  e = [userInfo objectForKey: GSFileHandleNotificationError];
  if (e != nil)
    {
      NSLog(@"Unable to connect to %@:%@ via socket ... %@",
	[sock socketAddress], [sock socketService], e);
      /*
       * Tell superclass that the load failed - let it do housekeeping.
       */
      [self endLoadInBackground];
      [self backgroundLoadDidFailWithReason:
	[NSString stringWithFormat: @"Failed to connect: %@", e]];
      return;
    }

  ASSIGN(in, ([NSString stringWithFormat: @"(%@:%@ <-- %@:%@)",
    [sock socketLocalAddress], [sock socketLocalService],
    [sock socketAddress], [sock socketService]]));
  ASSIGN(out, ([NSString stringWithFormat: @"(%@:%@ --> %@:%@)",
    [sock socketLocalAddress], [sock socketLocalService],
    [sock socketAddress], [sock socketService]]));

  if (debug)
    {
      NSLog(@"%@ %p", NSStringFromSelector(_cmd), self);
    }

  /*
   * If SSL via proxy, set up tunnel first
   */
  if (proxyURL && [[u scheme] isEqualToString: @"https"])
    {
      NSRunLoop		*loop = [NSRunLoop currentRunLoop];
      NSString		*cmd;
      NSTimeInterval	last = 0.0;
      NSTimeInterval	limit = 0.01;
      NSData		*buf;
      NSDate		*when;
      int		status;
      NSString		*version;

      version = [request objectForKey: NSHTTPPropertyServerHTTPVersionKey];
      if (version == nil)
	{
	  version = httpVersion;
	}
      if ([u port] == nil)
	{
	  cmd = [NSString stringWithFormat: @"CONNECT %@:443 HTTP/%@\r\n\r\n",
	    [u host], version];
	}
      else
	{
	  cmd = [NSString stringWithFormat: @"CONNECT %@:%@ HTTP/%@\r\n\r\n",
	    [u host], [u port], version];
	}

      /*
       * Set up default status for if connection is lost.
       */
      [pageInfo setObject: @"1.0" forKey: NSHTTPPropertyServerHTTPVersionKey];
      [pageInfo setObject: [NSNumber numberWithInt: 503]
		   forKey: NSHTTPPropertyStatusCodeKey];
      [pageInfo setObject: @"Connection dropped by proxy server"
		   forKey: NSHTTPPropertyStatusReasonKey];

      tunnel = YES;
      [nc addObserver: self
	     selector: @selector(bgdWrite:)
                 name: GSFileHandleWriteCompletionNotification
               object: sock];

      buf = [cmd dataUsingEncoding: NSASCIIStringEncoding];
      if (debug)
        {
          if (NO == [ioDelegate putBytes: [buf bytes]
                                ofLength: [buf length]
                                byHandle: self])
            {
              debugWrite(self, buf);
            }
        }
      [sock writeInBackgroundAndNotify: buf];

      when = [NSDate alloc];
      while (tunnel == YES)
	{
	  if (limit < 1.0)
	    {
	      NSTimeInterval	tmp = limit;

	      limit += last;
	      last = tmp;
	    }
          when = [when initWithTimeIntervalSinceNow: limit];
	  [loop runUntilDate: when];
	}
      RELEASE(when);

      status = [[pageInfo objectForKey: NSHTTPPropertyStatusCodeKey] intValue];
      if (status != 200)
	{
	  [self endLoadInBackground];
	  [self backgroundLoadDidFailWithReason: @"Failed proxy tunneling"];
	  return;
	}
    }
  if ([[u scheme] isEqualToString: @"https"])
    {
      static NSArray            *keys = nil;
      NSMutableDictionary       *opts;
      NSUInteger                count;
      BOOL			success = NO;

      /* If we are an https connection, negotiate secure connection.
       * Make sure we are not an observer of the file handle while
       * it is connecting...
       */
      [nc removeObserver: self name: nil object: sock];

      if (nil == keys)
        {
          keys = [[NSArray alloc] initWithObjects:
            GSTLSCAFile,
            GSTLSCertificateFile,
            GSTLSCertificateKeyFile,
            GSTLSCertificateKeyPassword,
            GSTLSDebug,
            GSTLSIssuers,
            GSTLSOwners,
            GSTLSPriority,
            GSTLSRemoteHosts,
            GSTLSRevokeFile,
            GSTLSServerName,
            GSTLSVerify,
            nil];
        }
      count = [keys count];
      opts = [[NSMutableDictionary alloc] initWithCapacity: count];
      while (count-- > 0)
        {
          NSString      *key = [keys objectAtIndex: count];
          NSString      *str = [request objectForKey: key];

          if (nil != str)
            {
              [opts setObject: str forKey: key];
            }
        }

      /* If there is no value set for the server name, and the host in the
       * URL is a domain name rather than an address, we use that.
       */
      if (nil == [opts objectForKey: GSTLSServerName])
        {
          NSString      *host = [u host];
          unichar       c = [host length] == 0 ? 0 : [host characterAtIndex: 0];

          if (c != 0 && c != ':' && !isdigit(c))
            {
              [opts setObject: host forKey: GSTLSServerName];
            }
        }

      if (debug) [opts setObject: @"YES" forKey: GSTLSDebug];
      [sock sslSetOptions: opts];
      RELEASE(opts);
      if ([sock sslHandshakeEstablished: &success outgoing: YES])
	{
	  if (NO == success)
	    {
	      if (debug)
		NSLog(@"%@ %p %s Failed to make ssl connect",
		  NSStringFromSelector(_cmd), self, keepalive?"K":"");
	      [self endLoadInBackground];
	      [self backgroundLoadDidFailWithReason:
		@"Failed to make ssl connect"];
	      return;
	    }
	}
      else
	{
	  [nc addObserver: self
	         selector: @selector(bgdHandshake:)
		     name: NSFileHandleDataAvailableNotification
	           object: sock];
	  [sock waitForDataInBackgroundAndNotify];
	  return;
	}
    }

  [self _apply];
}

- (void) bgdHandshake: (NSNotification*)notification
{
  BOOL	success = NO;

  if ([sock sslHandshakeEstablished: &success outgoing: YES])
    { 
      if (success)
	{
	  NSNotificationCenter	*nc = [NSNotificationCenter defaultCenter];

	  [nc removeObserver: self
			name: NSFileHandleDataAvailableNotification
		      object: sock];
	  [self _apply];
	}
      else
	{ 
	  if (debug)
	    NSLog(@"%@ %p %s Failed to make ssl connect",
	      NSStringFromSelector(_cmd), self, keepalive?"K":"");
	  [self endLoadInBackground];
	  [self backgroundLoadDidFailWithReason:
	    @"Failed to make ssl connect"];
	}
    }
  else
    {
      [sock waitForDataInBackgroundAndNotify];
    }
}

- (void) bgdWrite: (NSNotification*)notification
{
  NSNotificationCenter	*nc;
  NSDictionary    	*userInfo = [notification userInfo];
  NSString        	*e;

  RETAIN(self);
  if (debug)
    NSLog(@"%@ %p %s", NSStringFromSelector(_cmd), self, keepalive?"K":"");
  e = [userInfo objectForKey: GSFileHandleNotificationError];
  if (e != nil)
    {
      tunnel = NO;
      if (keepalive == YES)
	{
	  /*
	   * The write failed ... connection dropped ... and we
	   * are re-using an existing connection (keepalive = YES)
	   * then we may try again with a new connection.
	   */
          [self _disconnect];
	  if (debug)
            {
              NSLog(@"%@ %p restart on new connection",
                NSStringFromSelector(_cmd), self);
            }
	  [self _tryLoadInBackground: u];
          RELEASE(self);
	  return;
	}
      NSLog(@"Failed to write command to socket - %@ %p %s",
	e, self, keepalive?"K":"");
      /*
       * Tell superclass that the load failed - let it do housekeeping.
       */
      [self endLoadInBackground];
      [self backgroundLoadDidFailWithReason:
	[NSString stringWithFormat: @"Failed to write request: %@", e]];
      DESTROY(self);
      return;
    }
  else
    {
      /*
       * Don't watch for write completions any more.
       */
      nc = [NSNotificationCenter defaultCenter];
      [nc removeObserver: self
		    name: GSFileHandleWriteCompletionNotification
		  object: sock];

      /*
       * Ok - write completed, let's read the response.
       */
      if (tunnel == YES)
	{
	  [nc addObserver: self
	         selector: @selector(bgdTunnelRead:)
		     name: NSFileHandleReadCompletionNotification
	           object: sock];
	}
      else
	{
	  bodyPos = 0;
	  [nc addObserver: self
	         selector: @selector(bgdRead:)
		     name: NSFileHandleReadCompletionNotification
	           object: sock];
	}
      if ([sock readInProgress] == NO)
	{
	  [sock readInBackgroundAndNotify];
	}
      connectionState = reading;
    }
  DESTROY(self);
}

/**
 *  If necessary, this method calls -loadInForeground to send a
 *  request to the webserver, and get a page back.  It then returns
 *  the property for the specified key -
 * <list>
 *   <item>
 *     NSHTTPPropertyStatusCodeKey - numeric status code returned
 *     by the last request.
 *   </item>
 *   <item>
 *     NSHTTPPropertyStatusReasonKey - text describing status of
 *     the last request
 *   </item>
 *   <item>
 *     NSHTTPPropertyServerHTTPVersionKey - <code>http</code>
 *     version supported by remote server
 *   </item>
 *   <item>
 *     Other keys are taken to be the names of <code>http</code>
 *     headers and the corresponding header value (or nil if there
 *     is none) is returned.
 *   </item>
 * </list>
 */
- (id) propertyForKey: (NSString*) propertyKey
{
  if (document == nil)
    [self loadInForeground];
  return [self propertyForKeyIfAvailable: propertyKey];
}

- (id) propertyForKeyIfAvailable: (NSString*) propertyKey
{
  id	result = [pageInfo objectForKey: propertyKey];

  if (result == nil)
    {
      NSString	*key = [propertyKey lowercaseString];
      NSArray	*array = [document headersNamed: key];

      if ([array count] == 0)
	{
	  return nil;
	}
      else if ([array count] == 1)
	{
	  GSMimeHeader	*hdr = [array objectAtIndex: 0];

	  result = [hdr value];
	}
      else
	{
	  NSEnumerator	*enumerator = [array objectEnumerator];
	  GSMimeHeader	*val;

	  result = [NSMutableArray arrayWithCapacity: [array count]];
	  while ((val = [enumerator nextObject]) != nil)
	    {
	      [result addObject: [val value]];
	    }
	}
    }
  return result;
}

- (int) setDebug: (int)flag
{
  int   old = debug;

  debug = flag ? YES : NO;
  return old;
}

- (id<GSLogDelegate>) setDebugLogDelegate: (id<GSLogDelegate>)d
{
  id<GSLogDelegate>     old = ioDelegate;

  NSAssert(nil == d || [d conformsToProtocol: @protocol(GSLogDelegate)],
    NSInvalidArgumentException);
  ioDelegate  = d;
  return old;
}

- (void) setReturnAll: (BOOL)flag
{
  returnAll = flag;
}

- (void) setURL: (NSURL*)newUrl
{
  NSAssert(connectionState == idle, NSInternalInconsistencyException);
  NSAssert([newUrl isKindOfClass: [NSURL class]], NSInvalidArgumentException);

  if (NO == [newUrl isEqual: url])
    {
      NSString      *k = [newUrl cacheKey];

      if (NO == [k isEqual: urlKey])
        {
          /* Changing the URL of a handle to one that's not cache-compatible
           * implies that the handle must be removed from the cache and also
           * that the underlying network connection can no longer be used.
           */
          [urlLock lock];
          if (self == [urlCache objectForKey: urlKey])
            {
              [urlCache removeObjectForKey: urlKey];
              [urlOrder removeObjectIdenticalTo: self];
            }
          [urlLock unlock];
          [self _disconnect];
          ASSIGN(urlKey, k);
        }
      ASSIGN(url, newUrl);
    }
}

- (void) _tryLoadInBackground: (NSURL*)fromURL
{
  NSNotificationCenter	*nc;
  NSString		*host = nil;
  NSString		*port = nil;
  NSString		*s;

  /*
   * Don't start a load if one is in progress.
   */
  if (connectionState != idle)
    {
      NSLog(@"Attempt to load an http handle which is not idle ... ignored");
      return;
    }

  inResponse = NO;
  [dat setLength: 0];
  RELEASE(document);
  RELEASE(parser);
  [pageInfo removeAllObjects];
  parser = [GSMimeParser new];
  document = RETAIN([parser mimeDocument]);

  /*
   * First time round, fromURL is nil, so we use the url ivar and
   * we notify that the load is begining.  On retries we get a real
   * value in fromURL to use.
   */
  if (fromURL == nil)
    {
      redirects = 0;
      ASSIGN(u, url);
      [self beginLoadInBackground];
    }
  else
    {
      ASSIGN(u, fromURL);
    }

  host = [u host];
  port = (id)[u port];
  if (port != nil)
    {
      port = [NSString stringWithFormat: @"%u", [port intValue]];
    }
  else
    {
      port = [u scheme];
    }
  if ([port isEqualToString: @"https"])
    {
      port = @"443";
    }
  else if ([port isEqualToString: @"http"])
    {
      port = @"80";
    }

  /* An existing socket with keepalive may have been closed by the other
   * end.
   * On unix systems we can simply peek on the file descriptor for a much
   * more efficient check.
   * On windows we use the same system, it is noted to be inefficient but
   * we don't care because we peek rare enough at each HTTP request.
   */
  if (sock != nil)
    {
      int fd = [sock fileDescriptor];

      if (debug)
        {
	  NSLog(@"%@ %p check for reusable socket",
	    NSStringFromSelector(_cmd), self);
	}
      if (fd >= 0)
        {
	  int		result;
	  unsigned char	c;

#if     !defined(MSG_DONTWAIT)
#define MSG_DONTWAIT    0
#endif
	  result = recv(fd, (void *)&c, 1, MSG_PEEK | MSG_DONTWAIT);
	  if (result == 0 || (result < 0 && errno != EAGAIN && errno != EINTR))
	    {
	      DESTROY(sock);
	    }
	}
      else
        {
	  DESTROY(sock);
	}
      if (debug)
	{
	  if (sock == nil)
	    {
	      NSLog(@"%@ %p socket closed by remote",
		NSStringFromSelector(_cmd), self);
	    }
	  else
	    {
	      NSLog(@"%@ %p socket is still open",
		NSStringFromSelector(_cmd), self);
	    }
	}
    }

  if (sock == nil)
    {
      NSURLProtectionSpace      *space;
      NSURL                     *proxy = nil;
      NSString                  *proxyStr = nil;

      keepalive = NO;	// New connection
      /*
       * If we have a local address specified,
       * tell the file handle to bind to it.
       */
      s = [request objectForKey: GSHTTPPropertyLocalHostKey];
      if ([s length] > 0)
	{
	  s = [NSString stringWithFormat: @"bind-%@", s];
	}
      else
	{
	  s = @"tcp";	// Bind to any.
	}

      space = [GSHTTPAuthentication protectionSpaceForURL: u];
      if ([space isProxy])
	{ 
          proxyStr = [NSString stringWithFormat: @"%@://%@:%u/",
            [u scheme], [space host], (unsigned)[space port]];
        }
      else
        {
          NSString      *ph;
          NSString      *pp;

          ph = [request objectForKey: GSHTTPPropertyProxyHostKey];
          pp = [request objectForKey: GSHTTPPropertyProxyPortKey];
          if (ph)
            {
              if (pp)
                {
                  proxyStr = [NSString stringWithFormat: @"%@://%@:%@/",
                    [u scheme], ph, pp];
                }
              else
                {
                  proxyStr = [NSString stringWithFormat: @"%@://%@/",
                    [u scheme], ph];
                }
            }

          /* The preferred proxy specification is by a URL set as a property
           */
          if ([[u scheme] isEqualToString: @"https"])
            {
              proxy = [request objectForKey: @"https_proxy"];
            }
          else
            {
              proxy = [request objectForKey: @"http_proxy"];
            }
        }
      if ([proxy isKindOfClass: [NSString class]])
        {
          proxyStr = (NSString*)proxy;
          proxy = nil;
        }

      /* A generic fallback for the entire process can come from
       * environment variables.
       */
      if (nil == proxy && nil == proxyStr)
        {
          NSDictionary  *env;
          NSString      *key;
  
          env = [[NSProcessInfo processInfo] environment];
          key = [[u scheme] stringByAppendingString: @"_proxy"];
          if (nil == (proxyStr = [env objectForKey: key]))
            {
              proxyStr = [env objectForKey: [key uppercaseString]];
            }
        }
      if (nil == proxy)
        {
          /* We make the proxy URL from a supplied string unless that is empty;
           * An empty string in the request can be used to disable the process
           * wide settings for that request..
           */
          if ([proxyStr length])
            {
              proxy = [NSURL URLWithString: proxyStr];
            }
        }

      /* Make sure the proxy URL has a port specified. The default port
       * depends on the scheme of the request (4430 for TLS, 8080 unencrypted).
       */
      if (proxy && [[proxy port] intValue] == 0)
        {
          NSURLComponents       *c;

          c = [NSURLComponents componentsWithURL: proxy
                         resolvingAgainstBaseURL: NO];
          
          if ([[u scheme] isEqualToString: @"https"])
            {
              [c setPort: [NSNumber numberWithInteger: 4430]];
            }
          else
            {
              [c setPort: [NSNumber numberWithInteger: 8080]];
            }
          proxy = [c URL];
        }
      ASSIGN(proxyURL, proxy);

      if (nil == proxyURL)
	{
	  if ([[u scheme] isEqualToString: @"https"])
	    {
	      NSString	*cert;
              NSString	*key;
              NSString	*pwd;

	      if (sslClass == 0)
		{
		  [self backgroundLoadDidFailWithReason: @"https not supported"
		    @" ... needs gnustep-base built with GNUTLS"];
		  return;
		}
	      sock = [sslClass fileHandleAsClientInBackgroundAtAddress: host
							       service: port
							      protocol: s];

              /* Map old SSL keys onto new.
               */
	      cert = [request objectForKey: GSHTTPPropertyCertificateFileKey];
	      if (nil != cert)
		{
                  [request setObject: cert
                              forKey: GSTLSCertificateFile];
                }
              key = [request objectForKey: GSHTTPPropertyKeyFileKey];
              if (nil != key)
                {
                  [request setObject: key
                              forKey: GSTLSCertificateKeyFile];
                }
              pwd = [request objectForKey: GSHTTPPropertyPasswordKey];
              if (nil != pwd)
                {
                  [request setObject: pwd
                              forKey: GSTLSCertificateKeyPassword];
                }
	    }
	  else
	    {
	      sock = [NSFileHandle fileHandleAsClientInBackgroundAtAddress: host
								   service: port
								  protocol: s];
	    }
	}
      else
	{
          port = [[proxyURL port] description];
          host = [proxyURL host];
          
	  if ([[u scheme] isEqualToString: @"https"])
	    {
	      if (sslClass == 0)
		{
		  [self backgroundLoadDidFailWithReason: @"https not supported"
		    @" ... needs gnustep-base built with GNUTLS"];
		  return;
		}
	      sock = [sslClass fileHandleAsClientInBackgroundAtAddress: host
							       service: port
							      protocol: s];
	    }
	  else
	    {
	      sock = [NSFileHandle
		fileHandleAsClientInBackgroundAtAddress: host
						service: port
					       protocol: s];
	    }
	}
      if (sock == nil)
	{
	  /*
	   * Tell superclass that the load failed - let it do housekeeping.
	   */
	  [self backgroundLoadDidFailWithReason:
	    [NSString stringWithFormat: @"Unable to connect to %@:%@ ... %@",
	    host, port, [NSError _last]]];
	  return;
	}
      RETAIN(sock);
      nc = [NSNotificationCenter defaultCenter];
      [nc addObserver: self
	     selector: @selector(bgdConnect:)
		 name: GSFileHandleConnectCompletionNotification
	       object: sock];
      connectionState = connecting;
      if (debug)
        {
          NSLog(@"%@ %p start connect to %@:%@",
	    NSStringFromSelector(_cmd), self, host, port);
	}
    }
  else
    {
      NSString	*method;
      NSString	*path;
      NSString	*basic;

      // Stop waiting for connection to be closed down.
      nc = [NSNotificationCenter defaultCenter];
      [nc removeObserver: self
		    name: NSFileHandleReadCompletionNotification
		  object: sock];

      /* Reusing a connection. Set flag to say that it has been kept
       * alive and we don't know if the other end has dropped it
       * until we write to it and read some response.
       */
      keepalive = YES;
      method = [request objectForKey: GSHTTPPropertyMethodKey];
      if (method == nil)
	{
	  if ([wData length] > 0)
	    {
	      method = @"POST";
	    }
	  else
	    {
	      method = @"GET";
	    }
	}
      path = [[u pathWithEscapes] stringByTrimmingSpaces];
      if ([path length] == 0)
	{
	  path = @"/";
	}
      basic = [NSString stringWithFormat: @"%@ %@", method, path];
      [self bgdApply: basic];
    }
}

/**
 * Writes the specified data as the body of an <code>http</code>
 * or <code>https</code> request to the web server.
 * Returns YES on success,
 * NO on failure.  By default, this method performs a POST operation.
 * On completion, the resource data for this handle is set to the
 * page returned by the request.
 */
- (BOOL) writeData: (NSData*)d
{
  ASSIGN(wData, d);
  return YES;
}

/**
 * Sets a property to be used in the next request made by this handle.
 * The property is set as a header in the next request, unless it is
 * one of the following -
 * <list>
 *   <item>
 *     GSHTTPPropertyBodyKey - set an NSData item to be sent to
 *     the server as the body of the request.
 *   </item>
 *   <item>
 *     GSHTTPPropertyMethodKey - override the default method of
 *     the request (eg. &quot;PUT&quot;).
 *   </item>
 *   <item>
 *     GSHTTPPropertyProxyHostKey - specify the name or IP address
 *     of a host to proxy through.  Obsolete ... use
 *     https_proxy or http_proxy to specify the URL of the proxy
 *   </item>
 *   <item>
 *     GSHTTPPropertyProxyPortKey - specify the port number to
 *     connect to on the proxy host.  If not give, this defaults
 *     to 8080 for <code>http</code> and 4430 for <code>https</code>.
 *     Obsolete ... use https_proxy or http_proxy to specify the URL
 *     of the proxy.
 *   </item>
 *   <item>
 *     Any GSTLS... key to control TLS behavior
 *   </item>
 *   <item>
 *     Any NSHTTPProperty... key
 *   </item>
 * </list>
 */
- (BOOL) writeProperty: (id) property forKey: (NSString*) propertyKey
{
  if (propertyKey == nil
    || [propertyKey isKindOfClass: [NSString class]] == NO)
    {
      [NSException raise: NSInvalidArgumentException
        format: @"%@ %p with invalid key", NSStringFromSelector(_cmd), self];
    }
  if ([propertyKey hasPrefix: @"GSHTTPProperty"]
    || [propertyKey hasPrefix: @"GSTLS"]
    || [propertyKey hasPrefix: @"NSHTTPProperty"])
    {
      if (property == nil)
	{
	  [request removeObjectForKey: propertyKey];
	}
      else
	{
	  [request setObject: property forKey: propertyKey];
	}
    }
  else
    {
      if (property == nil)
	{
	  NSMapRemove(wProperties, (void*)propertyKey);
	}
      else
	{
	  NSMapInsert(wProperties, (void*)propertyKey, (void*)property);
	}
    }
  return YES;
}

@end