summaryrefslogtreecommitdiffstats
path: root/src/network/qhttp.cpp
blob: b8a110e58557753e0ad3d837b0803594eb6735f1 (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
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
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
/****************************************************************************
**
** Implementation of TQHttp and related classes.
**
** Created : 970521
**
** Copyright (C) 1997-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of the network module of the TQt GUI Toolkit.
**
** This file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the files LICENSE.GPL2
** and LICENSE.GPL3 included in the packaging of this file.
** Alternatively you may (at your option) use any later version
** of the GNU General Public License if such license has been
** publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free TQt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.TQPL
** included in the packaging of this file.  Licensees holding valid TQt
** Commercial licenses may use this file in accordance with the TQt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/

#include "ntqhttp.h"

#ifndef QT_NO_NETWORKPROTOCOL_HTTP

#include "ntqsocket.h"
#include "ntqtextstream.h"
#include "ntqmap.h"
#include "ntqstring.h"
#include "ntqstringlist.h"
#include "ntqcstring.h"
#include "ntqbuffer.h"
#include "ntqurloperator.h"
#include "ntqtimer.h"
#include "private/qinternal_p.h"

//#define TQHTTP_DEBUG

class TQHttpPrivate
{
public:
    TQHttpPrivate() :
	state( TQHttp::Unconnected ),
	error( TQHttp::NoError ),
	hostname( TQString::null ),
	port( 0 ),
	toDevice( 0 ),
	postDevice( 0 ),
	bytesDone( 0 ),
	chunkedSize( -1 ),
	idleTimer( 0 )
    {
	pending.setAutoDelete( TRUE );
    }

    TQSocket socket;
    TQPtrList<TQHttpRequest> pending;

    TQHttp::State state;
    TQHttp::Error error;
    TQString errorString;

    TQString hostname;
    Q_UINT16 port;

    TQByteArray buffer;
    TQIODevice* toDevice;
    TQIODevice* postDevice;

    uint bytesDone;
    uint bytesTotal;
    Q_LONG chunkedSize;

    TQHttpRequestHeader header;

    bool readHeader;
    TQString headerStr;
    TQHttpResponseHeader response;

    int idleTimer;

    TQMembuf rba;
};

class TQHttpRequest
{
public:
    TQHttpRequest()
    {
	id = ++idCounter;
    }
    virtual ~TQHttpRequest()
    { }

    virtual void start( TQHttp * ) = 0;
    virtual bool hasRequestHeader();
    virtual TQHttpRequestHeader requestHeader();

    virtual TQIODevice* sourceDevice() = 0;
    virtual TQIODevice* destinationDevice() = 0;

    int id;

private:
    static int idCounter;
};

int TQHttpRequest::idCounter = 0;

bool TQHttpRequest::hasRequestHeader()
{
    return FALSE;
}

TQHttpRequestHeader TQHttpRequest::requestHeader()
{
    return TQHttpRequestHeader();
}

/****************************************************
 *
 * TQHttpNormalRequest
 *
 ****************************************************/

class TQHttpNormalRequest : public TQHttpRequest
{
public:
    TQHttpNormalRequest( const TQHttpRequestHeader &h, TQIODevice *d, TQIODevice *t ) :
	header(h), to(t)
    {
	is_ba = FALSE;
	data.dev = d;
    }

    TQHttpNormalRequest( const TQHttpRequestHeader &h, TQByteArray *d, TQIODevice *t ) :
	header(h), to(t)
    {
	is_ba = TRUE;
	data.ba = d;
    }

    ~TQHttpNormalRequest()
    {
	if ( is_ba )
	    delete data.ba;
    }

    void start( TQHttp * );
    bool hasRequestHeader();
    TQHttpRequestHeader requestHeader();

    TQIODevice* sourceDevice();
    TQIODevice* destinationDevice();

protected:
    TQHttpRequestHeader header;

private:
    union {
	TQByteArray *ba;
	TQIODevice *dev;
    } data;
    bool is_ba;
    TQIODevice *to;
};

void TQHttpNormalRequest::start( TQHttp *http )
{
    http->d->header = header;

    if ( is_ba ) {
	http->d->buffer = *data.ba;
	if ( http->d->buffer.size() > 0 )
	    http->d->header.setContentLength( http->d->buffer.size() );

	http->d->postDevice = 0;
    } else {
	http->d->buffer = TQByteArray();

	if ( data.dev && ( data.dev->isOpen() || data.dev->open(IO_ReadOnly) ) ) {
	    http->d->postDevice = data.dev;
	    if ( http->d->postDevice->size() > 0 )
		http->d->header.setContentLength( http->d->postDevice->size() );
	} else {
	    http->d->postDevice = 0;
	}
    }

    if ( to && ( to->isOpen() || to->open(IO_WriteOnly) ) )
	http->d->toDevice = to;
    else
	http->d->toDevice = 0;

    http->sendRequest();
}

bool TQHttpNormalRequest::hasRequestHeader()
{
    return TRUE;
}

TQHttpRequestHeader TQHttpNormalRequest::requestHeader()
{
    return header;
}

TQIODevice* TQHttpNormalRequest::sourceDevice()
{
    if ( is_ba )
	return 0;
    return data.dev;
}

TQIODevice* TQHttpNormalRequest::destinationDevice()
{
    return to;
}

/****************************************************
 *
 * TQHttpPGHRequest
 * (like a TQHttpNormalRequest, but for the convenience
 * functions put(), get() and head() -- i.e. set the
 * host header field correctly before sending the
 * request)
 *
 ****************************************************/

class TQHttpPGHRequest : public TQHttpNormalRequest
{
public:
    TQHttpPGHRequest( const TQHttpRequestHeader &h, TQIODevice *d, TQIODevice *t ) :
	TQHttpNormalRequest( h, d, t )
    { }

    TQHttpPGHRequest( const TQHttpRequestHeader &h, TQByteArray *d, TQIODevice *t ) :
	TQHttpNormalRequest( h, d, t )
    { }

    ~TQHttpPGHRequest()
    { }

    void start( TQHttp * );
};

void TQHttpPGHRequest::start( TQHttp *http )
{
    header.setValue( "Host", http->d->hostname );
    TQHttpNormalRequest::start( http );
}

/****************************************************
 *
 * TQHttpSetHostRequest
 *
 ****************************************************/

class TQHttpSetHostRequest : public TQHttpRequest
{
public:
    TQHttpSetHostRequest( const TQString &h, Q_UINT16 p ) :
	hostname(h), port(p)
    { }

    void start( TQHttp * );

    TQIODevice* sourceDevice()
    { return 0; }
    TQIODevice* destinationDevice()
    { return 0; }

private:
    TQString hostname;
    Q_UINT16 port;
};

void TQHttpSetHostRequest::start( TQHttp *http )
{
    http->d->hostname = hostname;
    http->d->port = port;
    http->finishedWithSuccess();
}

/****************************************************
 *
 * TQHttpCloseRequest
 *
 ****************************************************/

class TQHttpCloseRequest : public TQHttpRequest
{
public:
    TQHttpCloseRequest()
    { }
    void start( TQHttp * );

    TQIODevice* sourceDevice()
    { return 0; }
    TQIODevice* destinationDevice()
    { return 0; }
};

void TQHttpCloseRequest::start( TQHttp *http )
{
    http->close();
}

/****************************************************
 *
 * TQHttpHeader
 *
 ****************************************************/

/*!
    \class TQHttpHeader ntqhttp.h
    \brief The TQHttpHeader class contains header information for HTTP.
\if defined(commercial)
    It is part of the <a href="commercialeditions.html">TQt Enterprise Edition</a>.
\endif

    \ingroup io
    \module network

    In most cases you should use the more specialized derivatives of
    this class, TQHttpResponseHeader and TQHttpRequestHeader, rather
    than directly using TQHttpHeader.

    TQHttpHeader provides the HTTP header fields. A HTTP header field
    consists of a name followed by a colon, a single space, and the
    field value. (See RFC 1945.) Field names are case-insensitive. A
    typical header field looks like this:
    \code
    content-type: text/html
    \endcode

    In the API the header field name is called the "key" and the
    content is called the "value". You can get and set a header
    field's value by using its key with value() and setValue(), e.g.
    \code
    header.setValue( "content-type", "text/html" );
    TQString contentType = header.value( "content-type" );
    \endcode

    Some fields are so common that getters and setters are provided
    for them as a convenient alternative to using \l value() and
    \l setValue(), e.g. contentLength() and contentType(),
    setContentLength() and setContentType().

    Each header key has a \e single value associated with it. If you
    set the value for a key which already exists the previous value
    will be discarded.

    \sa TQHttpRequestHeader TQHttpResponseHeader
*/

/*!
    \fn int TQHttpHeader::majorVersion() const

    Returns the major protocol-version of the HTTP header.
*/

/*!
    \fn int TQHttpHeader::minorVersion() const

    Returns the minor protocol-version of the HTTP header.
*/

/*!
	Constructs an empty HTTP header.
*/
TQHttpHeader::TQHttpHeader()
    : valid( TRUE )
{
}

/*!
	Constructs a copy of \a header.
*/
TQHttpHeader::TQHttpHeader( const TQHttpHeader& header )
    : valid( header.valid )
{
    values = header.values;
}

/*!
    Constructs a HTTP header for \a str.

    This constructor parses the string \a str for header fields and
    adds this information. The \a str should consist of one or more
    "\r\n" delimited lines; each of these lines should have the format
    key, colon, space, value.
*/
TQHttpHeader::TQHttpHeader( const TQString& str )
    : valid( TRUE )
{
    parse( str );
}

/*!
    Destructor.
*/
TQHttpHeader::~TQHttpHeader()
{
}

/*!
    Assigns \a h and returns a reference to this http header.
*/
TQHttpHeader& TQHttpHeader::operator=( const TQHttpHeader& h )
{
    values = h.values;
    valid = h.valid;
    return *this;
}

/*!
    Returns TRUE if the HTTP header is valid; otherwise returns FALSE.

    A TQHttpHeader is invalid if it was created by parsing a malformed string.
*/
bool TQHttpHeader::isValid() const
{
    return valid;
}

/*! \internal
    Parses the HTTP header string \a str for header fields and adds
    the keys/values it finds. If the string is not parsed successfully
    the TQHttpHeader becomes \link isValid() invalid\endlink.

    Returns TRUE if \a str was successfully parsed; otherwise returns FALSE.

    \sa toString()
*/
bool TQHttpHeader::parse( const TQString& str )
{
    TQStringList lst;
    int pos = str.find( '\n' );
    if ( pos > 0 && str.at( pos - 1 ) == '\r' )
	lst = TQStringList::split( "\r\n", str.stripWhiteSpace(), FALSE );
    else
	lst = TQStringList::split( "\n", str.stripWhiteSpace(), FALSE );

    if ( lst.isEmpty() )
	return TRUE;

    TQStringList lines;
    TQStringList::Iterator it = lst.begin();
    for( ; it != lst.end(); ++it ) {
	if ( !(*it).isEmpty() ) {
	    if ( (*it)[0].isSpace() ) {
		if ( !lines.isEmpty() ) {
		    lines.last() += " ";
		    lines.last() += (*it).stripWhiteSpace();
		}
	    } else {
		lines.append( (*it) );
	    }
	}
    }

    int number = 0;
    it = lines.begin();
    for( ; it != lines.end(); ++it ) {
	if ( !parseLine( *it, number++ ) ) {
	    valid = FALSE;
	    return FALSE;
	}
    }
    return TRUE;
}

/*! \internal
*/
void TQHttpHeader::setValid( bool v )
{
    valid = v;
}

/*!
    Returns the value for the entry with the given \a key. If no entry
    has this \a key, an empty string is returned.

    \sa setValue() removeValue() hasKey() keys()
*/
TQString TQHttpHeader::value( const TQString& key ) const
{
    return values[ key.lower() ];
}

/*!
    Returns a list of the keys in the HTTP header.

    \sa hasKey()
*/
TQStringList TQHttpHeader::keys() const
{
    return values.keys();
}

/*!
    Returns TRUE if the HTTP header has an entry with the given \a
    key; otherwise returns FALSE.

    \sa value() setValue() keys()
*/
bool TQHttpHeader::hasKey( const TQString& key ) const
{
    return values.contains( key.lower() );
}

/*!
    Sets the value of the entry with the \a key to \a value.

    If no entry with \a key exists, a new entry with the given \a key
    and \a value is created. If an entry with the \a key already
    exists, its value is discarded and replaced with the given \a
    value.

    \sa value() hasKey() removeValue()
*/
void TQHttpHeader::setValue( const TQString& key, const TQString& value )
{
    values[ key.lower() ] = value;
}

/*!
    Removes the entry with the key \a key from the HTTP header.

    \sa value() setValue()
*/
void TQHttpHeader::removeValue( const TQString& key )
{
    values.remove( key.lower() );
}

/*! \internal
    Parses the single HTTP header line \a line which has the format
    key, colon, space, value, and adds key/value to the headers. The
    linenumber is \a number. Returns TRUE if the line was successfully
    parsed and the key/value added; otherwise returns FALSE.

    \sa parse()
*/
bool TQHttpHeader::parseLine( const TQString& line, int )
{
    int i = line.find( ":" );
    if ( i == -1 )
	return FALSE;

    values.insert( line.left( i ).stripWhiteSpace().lower(), line.mid( i + 1 ).stripWhiteSpace() );

    return TRUE;
}

/*!
    Returns a string representation of the HTTP header.

    The string is suitable for use by the constructor that takes a
    TQString. It consists of lines with the format: key, colon, space,
    value, "\r\n".
*/
TQString TQHttpHeader::toString() const
{
    if ( !isValid() )
	return "";

    TQString ret = "";

    TQMap<TQString,TQString>::ConstIterator it = values.begin();
    for( ; it != values.end(); ++it )
	ret += it.key() + ": " + it.data() + "\r\n";

    return ret;
}

/*!
    Returns TRUE if the header has an entry for the special HTTP
    header field \c content-length; otherwise returns FALSE.

    \sa contentLength() setContentLength()
*/
bool TQHttpHeader::hasContentLength() const
{
    return hasKey( "content-length" );
}

/*!
    Returns the value of the special HTTP header field \c
    content-length.

    \sa setContentLength() hasContentLength()
*/
uint TQHttpHeader::contentLength() const
{
    return values[ "content-length" ].toUInt();
}

/*!
    Sets the value of the special HTTP header field \c content-length
    to \a len.

    \sa contentLength() hasContentLength()
*/
void TQHttpHeader::setContentLength( int len )
{
    values[ "content-length" ] = TQString::number( len );
}

/*!
    Returns TRUE if the header has an entry for the the special HTTP
    header field \c content-type; otherwise returns FALSE.

    \sa contentType() setContentType()
*/
bool TQHttpHeader::hasContentType() const
{
    return hasKey( "content-type" );
}

/*!
    Returns the value of the special HTTP header field \c content-type.

    \sa setContentType() hasContentType()
*/
TQString TQHttpHeader::contentType() const
{
    TQString type = values[ "content-type" ];
    if ( type.isEmpty() )
	return TQString::null;

    int pos = type.find( ";" );
    if ( pos == -1 )
	return type;

    return type.left( pos ).stripWhiteSpace();
}

/*!
    Sets the value of the special HTTP header field \c content-type to
    \a type.

    \sa contentType() hasContentType()
*/
void TQHttpHeader::setContentType( const TQString& type )
{
    values[ "content-type" ] = type;
}

/****************************************************
 *
 * TQHttpResponseHeader
 *
 ****************************************************/

/*!
    \class TQHttpResponseHeader ntqhttp.h
    \brief The TQHttpResponseHeader class contains response header information for HTTP.
\if defined(commercial)
    It is part of the <a href="commercialeditions.html">TQt Enterprise Edition</a>.
\endif

    \ingroup io
    \module network

    This class is used by the TQHttp class to report the header
    information that the client received from the server.

    HTTP responses have a status code that indicates the status of the
    response. This code is a 3-digit integer result code (for details
    see to RFC 1945). In addition to the status code, you can also
    specify a human-readable text that describes the reason for the
    code ("reason phrase"). This class allows you to get the status
    code and the reason phrase.

    \sa TQHttpRequestHeader TQHttp
*/

/*!
    Constructs an empty HTTP response header.
*/
TQHttpResponseHeader::TQHttpResponseHeader()
{
    setValid( FALSE );
}

/*!
    Constructs a HTTP response header with the status code \a code,
    the reason phrase \a text and the protocol-version \a majorVer and
    \a minorVer.
*/
TQHttpResponseHeader::TQHttpResponseHeader( int code, const TQString& text, int majorVer, int minorVer )
    : TQHttpHeader(), statCode( code ), reasonPhr( text ), majVer( majorVer ), minVer( minorVer )
{
}

/*!
    Constructs a copy of \a header.
*/
TQHttpResponseHeader::TQHttpResponseHeader( const TQHttpResponseHeader& header )
    : TQHttpHeader( header ), statCode( header.statCode ), reasonPhr( header.reasonPhr ), majVer( header.majVer ), minVer( header.minVer )
{
}

/*!
    Constructs a HTTP response header from the string \a str. The
    string is parsed and the information is set. The \a str should
    consist of one or more "\r\n" delimited lines; the first line should be the
    status-line (format: HTTP-version, space, status-code, space,
    reason-phrase); each of remaining lines should have the format key, colon,
    space, value.
*/
TQHttpResponseHeader::TQHttpResponseHeader( const TQString& str )
    : TQHttpHeader()
{
    parse( str );
}

/*!
    Sets the status code to \a code, the reason phrase to \a text and
    the protocol-version to \a majorVer and \a minorVer.

    \sa statusCode() reasonPhrase() majorVersion() minorVersion()
*/
void TQHttpResponseHeader::setStatusLine( int code, const TQString& text, int majorVer, int minorVer )
{
    setValid( TRUE );
    statCode = code;
    reasonPhr = text;
    majVer = majorVer;
    minVer = minorVer;
}

/*!
    Returns the status code of the HTTP response header.

    \sa reasonPhrase() majorVersion() minorVersion()
*/
int TQHttpResponseHeader::statusCode() const
{
    return statCode;
}

/*!
    Returns the reason phrase of the HTTP response header.

    \sa statusCode() majorVersion() minorVersion()
*/
TQString TQHttpResponseHeader::reasonPhrase() const
{
    return reasonPhr;
}

/*!
    Returns the major protocol-version of the HTTP response header.

    \sa minorVersion() statusCode() reasonPhrase()
*/
int TQHttpResponseHeader::majorVersion() const
{
    return majVer;
}

/*!
    Returns the minor protocol-version of the HTTP response header.

    \sa majorVersion() statusCode() reasonPhrase()
*/
int TQHttpResponseHeader::minorVersion() const
{
    return minVer;
}

/*! \reimp
*/
bool TQHttpResponseHeader::parseLine( const TQString& line, int number )
{
    if ( number != 0 )
	return TQHttpHeader::parseLine( line, number );

    TQString l = line.simplifyWhiteSpace();
    if ( l.length() < 10 )
	return FALSE;

    if ( l.left( 5 ) == "HTTP/" && l[5].isDigit() && l[6] == '.' &&
	    l[7].isDigit() && l[8] == ' ' && l[9].isDigit() ) {
	majVer = l[5].latin1() - '0';
	minVer = l[7].latin1() - '0';

	int pos = l.find( ' ', 9 );
	if ( pos != -1 ) {
	    reasonPhr = l.mid( pos + 1 );
	    statCode = l.mid( 9, pos - 9 ).toInt();
	} else {
	    statCode = l.mid( 9 ).toInt();
	    reasonPhr = TQString::null;
	}
    } else {
	return FALSE;
    }

    return TRUE;
}

/*! \reimp
*/
TQString TQHttpResponseHeader::toString() const
{
    TQString ret( "HTTP/%1.%2 %3 %4\r\n%5\r\n" );
    return ret.arg( majVer ).arg ( minVer ).arg( statCode ).arg( reasonPhr ).arg( TQHttpHeader::toString() );
}

/****************************************************
 *
 * TQHttpRequestHeader
 *
 ****************************************************/

/*!
    \class TQHttpRequestHeader ntqhttp.h
    \brief The TQHttpRequestHeader class contains request header information for
\if defined(commercial)
    It is part of the <a href="commercialeditions.html">TQt Enterprise Edition</a>.
\endif
    HTTP.
\if defined(commercial_edition)
    It is part of the <a href="commercialeditions.html">TQt Enterprise Edition</a>.
\endif

    \ingroup io
    \module network

    This class is used in the TQHttp class to report the header
    information if the client requests something from the server.

    HTTP requests have a method which describes the request's action.
    The most common requests are "GET" and "POST". In addition to the
    request method the header also includes a request-URI to specify
    the location for the method to use.

    The method, request-URI and protocol-version can be set using a
    constructor or later using setRequest(). The values can be
    obtained using method(), path(), majorVersion() and
    minorVersion().

    This class is a TQHttpHeader subclass so that class's functions,
    e.g. \link TQHttpHeader::setValue() setValue()\endlink, \link
    TQHttpHeader::value() value()\endlink, etc. are also available.

    \sa TQHttpResponseHeader TQHttp

    \important value() setValue()
*/

/*!
    Constructs an empty HTTP request header.
*/
TQHttpRequestHeader::TQHttpRequestHeader()
    : TQHttpHeader()
{
    setValid( FALSE );
}

/*!
    Constructs a HTTP request header for the method \a method, the
    request-URI \a path and the protocol-version \a majorVer and \a minorVer.
*/
TQHttpRequestHeader::TQHttpRequestHeader( const TQString& method, const TQString& path, int majorVer, int minorVer )
    : TQHttpHeader(), m( method ), p( path ), majVer( majorVer ), minVer( minorVer )
{
}

/*!
    Constructs a copy of \a header.
*/
TQHttpRequestHeader::TQHttpRequestHeader( const TQHttpRequestHeader& header )
    : TQHttpHeader( header ), m( header.m ), p( header.p ), majVer( header.majVer ), minVer( header.minVer )
{
}

/*!
    Constructs a HTTP request header from the string \a str. The \a
    str should consist of one or more "\r\n" delimited lines; the first line
    should be the request-line (format: method, space, request-URI, space
    HTTP-version); each of the remaining lines should have the format key,
    colon, space, value.
*/
TQHttpRequestHeader::TQHttpRequestHeader( const TQString& str )
    : TQHttpHeader()
{
    parse( str );
}

/*!
    This function sets the request method to \a method, the
    request-URI to \a path and the protocol-version to \a majorVer and
    \a minorVer.

    \sa method() path() majorVersion() minorVersion()
*/
void TQHttpRequestHeader::setRequest( const TQString& method, const TQString& path, int majorVer, int minorVer )
{
    setValid( TRUE );
    m = method;
    p = path;
    majVer = majorVer;
    minVer = minorVer;
}

/*!
    Returns the method of the HTTP request header.

    \sa path() majorVersion() minorVersion() setRequest()
*/
TQString TQHttpRequestHeader::method() const
{
    return m;
}

/*!
    Returns the request-URI of the HTTP request header.

    \sa method() majorVersion() minorVersion() setRequest()
*/
TQString TQHttpRequestHeader::path() const
{
    return p;
}

/*!
    Returns the major protocol-version of the HTTP request header.

    \sa minorVersion() method() path() setRequest()
*/
int TQHttpRequestHeader::majorVersion() const
{
    return majVer;
}

/*!
    Returns the minor protocol-version of the HTTP request header.

    \sa majorVersion() method() path() setRequest()
*/
int TQHttpRequestHeader::minorVersion() const
{
    return minVer;
}

/*! \reimp
*/
bool TQHttpRequestHeader::parseLine( const TQString& line, int number )
{
    if ( number != 0 )
	return TQHttpHeader::parseLine( line, number );

    TQStringList lst = TQStringList::split( " ", line.simplifyWhiteSpace() );
    if ( lst.count() > 0 ) {
	m = lst[0];
	if ( lst.count() > 1 ) {
	    p = lst[1];
	    if ( lst.count() > 2 ) {
		TQString v = lst[2];
		if ( v.length() >= 8 && v.left( 5 ) == "HTTP/" &&
			v[5].isDigit() && v[6] == '.' && v[7].isDigit() ) {
		    majVer = v[5].latin1() - '0';
		    minVer = v[7].latin1() - '0';
		    return TRUE;
		}
	    }
	}
    }

    return FALSE;
}

/*! \reimp
*/
TQString TQHttpRequestHeader::toString() const
{
    TQString first( "%1 %2");
    TQString last(" HTTP/%3.%4\r\n%5\r\n" );
    return first.arg( m ).arg( p ) +
	last.arg( majVer ).arg( minVer ).arg( TQHttpHeader::toString());
}


/****************************************************
 *
 * TQHttp
 *
 ****************************************************/
/*!
    \class TQHttp ntqhttp.h
    \brief The TQHttp class provides an implementation of the HTTP protocol.
\if defined(commercial)
    It is part of the <a href="commercialeditions.html">TQt Enterprise Edition</a>.
\endif

    \ingroup io
    \module network

    This class provides two different interfaces: one is the
    TQNetworkProtocol interface that allows you to use HTTP through the
    TQUrlOperator abstraction. The other is a direct interface to HTTP
    that allows you to have more control over the requests and that
    allows you to access the response header fields.

    Don't mix the two interfaces, since the behavior is not
    well-defined.

    If you want to use TQHttp with the TQNetworkProtocol interface, you
    do not use it directly, but rather through a TQUrlOperator, for
    example:

    \code
    TQUrlOperator op( "http://www.trolltech.com" );
    op.get( "index.html" );
    \endcode

    This code will only work if the TQHttp class is registered; to
    register the class, you must call qInitNetworkProtocols() before
    using a TQUrlOperator with HTTP.

    The TQNetworkProtocol interface for HTTP only supports the
    operations operationGet() and operationPut(), i.e.
    TQUrlOperator::get() and TQUrlOperator::put(), if you use it with a
    TQUrlOperator.

    The rest of this descrption describes the direct interface to
    HTTP.

    The class works asynchronously, so there are no blocking
    functions. If an operation cannot be executed immediately, the
    function will still return straight away and the operation will be
    scheduled for later execution. The results of scheduled operations
    are reported via signals. This approach depends on the event loop
    being in operation.

    The operations that can be scheduled (they are called "requests"
    in the rest of the documentation) are the following: setHost(),
    get(), post(), head() and request().

    All of these requests return a unique identifier that allows you
    to keep track of the request that is currently executed. When the
    execution of a request starts, the requestStarted() signal with
    the identifier is emitted and when the request is finished, the
    requestFinished() signal is emitted with the identifier and a bool
    that indicates if the request finished with an error.

    To make an HTTP request you must set up suitable HTTP headers. The
    following example demonstrates, how to request the main HTML page
    from the Trolltech home page (i.e. the URL
    http://www.trolltech.com/index.html):

    \code
    TQHttpRequestHeader header( "GET", "/index.html" );
    header.setValue( "Host", "www.trolltech.com" );
    http->setHost( "www.trolltech.com" );
    http->request( header );
    \endcode

    For the common HTTP requests \c GET, \c POST and \c HEAD, TQHttp
    provides the convenience functions get(), post() and head(). They
    already use a reasonable header and if you don't have to set
    special header fields, they are easier to use. The above example
    can also be written as:

    \code
    http->setHost( "www.trolltech.com" ); // id == 1
    http->get( "/index.html" );           // id == 2
    \endcode

    For this example the following sequence of signals is emitted
    (with small variations, depending on network traffic, etc.):

    \code
    requestStarted( 1 )
    requestFinished( 1, FALSE )

    requestStarted( 2 )
    stateChanged( Connecting )
    stateChanged( Sending )
    dataSendProgress( 77, 77 )
    stateChanged( Reading )
    responseHeaderReceived( responseheader )
    dataReadProgress( 5388, 0 )
    readyRead( responseheader )
    dataReadProgress( 18300, 0 )
    readyRead( responseheader )
    stateChanged( Connected )
    requestFinished( 2, FALSE )

    done( FALSE )

    stateChanged( Closing )
    stateChanged( Unconnected )
    \endcode

    The dataSendProgress() and dataReadProgress() signals in the above
    example are useful if you want to show a \link TQProgressBar
    progressbar\endlink to inform the user about the progress of the
    download. The second argument is the total size of data. In
    certain cases it is not possible to know the total amount in
    advance, in which case the second argument is 0. (If you connect
    to a TQProgressBar a total of 0 results in a busy indicator.)

    When the response header is read, it is reported with the
    responseHeaderReceived() signal.

    The readyRead() signal tells you that there is data ready to be
    read. The amount of data can then be queried with the
    bytesAvailable() function and it can be read with the readBlock()
    or readAll() functions.

    If an error occurs during the execution of one of the commands in
    a sequence of commands, all the pending commands (i.e. scheduled,
    but not yet executed commands) are cleared and no signals are
    emitted for them.

    For example, if you have the following sequence of reqeusts

    \code
    http->setHost( "www.foo.bar" );       // id == 1
    http->get( "/index.html" );           // id == 2
    http->post( "register.html", data );  // id == 3
    \endcode

    and the get() request fails because the host lookup fails, then
    the post() request is never executed and the signals would look
    like this:

    \code
    requestStarted( 1 )
    requestFinished( 1, FALSE )

    requestStarted( 2 )
    stateChanged( HostLookup )
    requestFinished( 2, TRUE )

    done( TRUE )

    stateChanged( Unconnected )
    \endcode

    You can then get details about the error with the error() and
    errorString() functions. Note that only unexpected behaviour, like
    network failure is considered as an error. If the server response
    contains an error status, like a 404 response, this is reported as
    a normal response case. So you should always check the \link
    TQHttpResponseHeader::statusCode() status code \endlink of the
    response header.

    The functions currentId() and currentRequest() provide more
    information about the currently executing request.

    The functions hasPendingRequests() and clearPendingRequests()
    allow you to query and clear the list of pending requests.

    \sa \link network.html TQt Network Documentation \endlink TQNetworkProtocol, TQUrlOperator TQFtp
*/

/*!
    Constructs a TQHttp object.
*/
TQHttp::TQHttp()
{
    init();
}

/*!
    Constructs a TQHttp object. The parameters \a parent and \a name
    are passed on to the TQObject constructor.
*/
TQHttp::TQHttp( TQObject* parent, const char* name )
{
    if ( parent )
	parent->insertChild( this );
    setName( name );
    init();
}

/*!
    Constructs a TQHttp object. Subsequent requests are done by
    connecting to the server \a hostname on port \a port. The
    parameters \a parent and \a name are passed on to the TQObject
    constructor.

    \sa setHost()
*/
TQHttp::TQHttp( const TQString &hostname, Q_UINT16 port, TQObject* parent, const char* name )
{
    if ( parent )
	parent->insertChild( this );
    setName( name );
    init();

    d->hostname = hostname;
    d->port = port;
}

void TQHttp::init()
{
    bytesRead = 0;
    d = new TQHttpPrivate;
    d->errorString = tr( "Unknown error" );

    connect( &d->socket, SIGNAL( connected() ),
	    this, SLOT( slotConnected() ) );
    connect( &d->socket, SIGNAL( connectionClosed() ),
	    this, SLOT( slotClosed() ) );
    connect( &d->socket, SIGNAL( delayedCloseFinished() ),
	    this, SLOT( slotClosed() ) );
    connect( &d->socket, SIGNAL( readyRead() ),
	    this, SLOT( slotReadyRead() ) );
    connect( &d->socket, SIGNAL( error(int) ),
	    this, SLOT( slotError(int) ) );
    connect( &d->socket, SIGNAL( bytesWritten(int) ),
	    this, SLOT( slotBytesWritten(int) ) );

    d->idleTimer = startTimer( 0 );
}

/*!
    Destroys the TQHttp object. If there is an open connection, it is
    closed.
*/
TQHttp::~TQHttp()
{
    abort();
    delete d;
}

/*!
    \enum TQHttp::State

    This enum is used to specify the state the client is in:

    \value Unconnected There is no connection to the host.
    \value HostLookup A host name lookup is in progress.
    \value Connecting An attempt to connect to the host is in progress.
    \value Sending The client is sending its request to the server.
    \value Reading The client's request has been sent and the client
    is reading the server's response.
    \value Connected The connection to the host is open, but the client is
    neither sending a request, nor waiting for a response.
    \value Closing The connection is closing down, but is not yet
    closed. (The state will be \c Unconnected when the connection is
    closed.)

    \sa stateChanged() state()
*/

/*!  \enum TQHttp::Error

    This enum identifies the error that occurred.

    \value NoError No error occurred.
    \value HostNotFound The host name lookup failed.
    \value ConnectionRefused The server refused the connection.
    \value UnexpectedClose The server closed the connection unexpectedly.
    \value InvalidResponseHeader The server sent an invalid response header.
    \value WrongContentLength The client could not read the content correctly
    because an error with respect to the content length occurred.
    \value Aborted The request was aborted with abort().
    \value UnknownError An error other than those specified above
    occurred.

    \sa error()
*/

/*!
    \fn void TQHttp::stateChanged( int state )

    This signal is emitted when the state of the TQHttp object changes.
    The argument \a state is the new state of the connection; it is
    one of the \l State values.

    This usually happens when a request is started, but it can also
    happen when the server closes the connection or when a call to
    closeConnection() succeeded.

    \sa get() post() head() request() closeConnection() state() State
*/

/*!
    \fn void TQHttp::responseHeaderReceived( const TQHttpResponseHeader& resp )

    This signal is emitted when the HTTP header of a server response
    is available. The header is passed in \a resp.

    \sa get() post() head() request() readyRead()
*/

/*!
    \fn void TQHttp::readyRead( const TQHttpResponseHeader& resp )

    This signal is emitted when there is new response data to read.

    If you specified a device in the request where the data should be
    written to, then this signal is \e not emitted; instead the data
    is written directly to the device.

    The response header is passed in \a resp.

    You can read the data with the readAll() or readBlock() functions

    This signal is useful if you want to process the data in chunks as
    soon as it becomes available. If you are only interested in the
    complete data, just connect to the requestFinished() signal and
    read the data then instead.

    \sa get() post() request() readAll() readBlock() bytesAvailable()
*/

/*!
    \fn void TQHttp::dataSendProgress( int done, int total )

    This signal is emitted when this object sends data to a HTTP
    server to inform it about the progress of the upload.

    \a done is the amount of data that has already arrived and \a
    total is the total amount of data. It is possible that the total
    amount of data that should be transferred cannot be determined, in
    which case \a total is 0.(If you connect to a TQProgressBar, the
    progress bar shows a busy indicator if the total is 0).

    \warning \a done and \a total are not necessarily the size in
    bytes, since for large files these values might need to be
    "scaled" to avoid overflow.

    \sa dataReadProgress() post() request() TQProgressBar::setProgress()
*/

/*!
    \fn void TQHttp::dataReadProgress( int done, int total )

    This signal is emitted when this object reads data from a HTTP
    server to indicate the current progress of the download.

    \a done is the amount of data that has already arrived and \a
    total is the total amount of data. It is possible that the total
    amount of data that should be transferred cannot be determined, in
    which case \a total is 0.(If you connect to a TQProgressBar, the
    progress bar shows a busy indicator if the total is 0).

    \warning \a done and \a total are not necessarily the size in
    bytes, since for large files these values might need to be
    "scaled" to avoid overflow.

    \sa dataSendProgress() get() post() request() TQProgressBar::setProgress()
*/

/*!
    \fn void TQHttp::requestStarted( int id )

    This signal is emitted when processing the request identified by
    \a id starts.

    \sa requestFinished() done()
*/

/*!
    \fn void TQHttp::requestFinished( int id, bool error )

    This signal is emitted when processing the request identified by
    \a id has finished. \a error is TRUE if an error occurred during
    the processing; otherwise \a error is FALSE.

    \sa requestStarted() done() error() errorString()
*/

/*!
    \fn void TQHttp::done( bool error )

    This signal is emitted when the last pending request has finished;
    (it is emitted after the last request's requestFinished() signal).
    \a error is TRUE if an error occurred during the processing;
    otherwise \a error is FALSE.

    \sa requestFinished() error() errorString()
*/

/*!
    Aborts the current request and deletes all scheduled requests.

    For the current request, the requestFinished() signal with the \c
    error argument \c TRUE is emitted. For all other requests that are
    affected by the abort(), no signals are emitted.

    Since this slot also deletes the scheduled requests, there are no
    requests left and the done() signal is emitted (with the \c error
    argument \c TRUE).

    \sa clearPendingRequests()
*/
void TQHttp::abort()
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r == 0 )
	return;

    finishedWithError( tr("Request aborted"), Aborted );
    clearPendingRequests();
    d->socket.clearPendingData();
    close();
}

/*!
    Returns the number of bytes that can be read from the response
    content at the moment.

    \sa get() post() request() readyRead() readBlock() readAll()
*/
Q_ULONG TQHttp::bytesAvailable() const
{
#if defined(TQHTTP_DEBUG)
    qDebug( "TQHttp::bytesAvailable(): %d bytes", (int)d->rba.size() );
#endif
    return d->rba.size();
}

/*!
    Reads \a maxlen bytes from the response content into \a data and
    returns the number of bytes read. Returns -1 if an error occurred.

    \sa get() post() request() readyRead() bytesAvailable() readAll()
*/
Q_LONG TQHttp::readBlock( char *data, Q_ULONG maxlen )
{
    if ( data == 0 && maxlen != 0 ) {
#if defined(QT_CHECK_NULL)
	qWarning( "TQHttp::readBlock: Null pointer error" );
#endif
	return -1;
    }
    if ( maxlen >= d->rba.size() )
	maxlen = d->rba.size();
    d->rba.consumeBytes( maxlen, data );

    d->bytesDone += maxlen;
#if defined(TQHTTP_DEBUG)
    qDebug( "TQHttp::readBlock(): read %d bytes (%d bytes done)", (int)maxlen, d->bytesDone );
#endif
    return maxlen;
}

/*!
    Reads all the bytes from the response content and returns them.

    \sa get() post() request() readyRead() bytesAvailable() readBlock()
*/
TQByteArray TQHttp::readAll()
{
    Q_ULONG avail = bytesAvailable();
    TQByteArray tmp( avail );
    Q_LONG read = readBlock( tmp.data(), avail );
    tmp.resize( read );
    return tmp;
}

/*!
    Returns the identifier of the HTTP request being executed or 0 if
    there is no request being executed (i.e. they've all finished).

    \sa currentRequest()
*/
int TQHttp::currentId() const
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r == 0 )
	return 0;
    return r->id;
}

/*!
    Returns the request header of the HTTP request being executed. If
    the request is one issued by setHost() or closeConnection(), it
    returns an invalid request header, i.e.
    TQHttpRequestHeader::isValid() returns FALSE.

    \sa currentId()
*/
TQHttpRequestHeader TQHttp::currentRequest() const
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r != 0 && r->hasRequestHeader() )
	return r->requestHeader();
    return TQHttpRequestHeader();
}

/*!
    Returns the TQIODevice pointer that is used as the data source of the HTTP
    request being executed. If there is no current request or if the request
    does not use an IO device as the data source, this function returns 0.

    This function can be used to delete the TQIODevice in the slot connected to
    the requestFinished() signal.

    \sa currentDestinationDevice() post() request()
*/
TQIODevice* TQHttp::currentSourceDevice() const
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( !r )
	return 0;
    return r->sourceDevice();
}

/*!
    Returns the TQIODevice pointer that is used as to store the data of the HTTP
    request being executed. If there is no current request or if the request
    does not store the data to an IO device, this function returns 0.

    This function can be used to delete the TQIODevice in the slot connected to
    the requestFinished() signal.

    \sa currentDestinationDevice() get() post() request()
*/
TQIODevice* TQHttp::currentDestinationDevice() const
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( !r )
	return 0;
    return r->destinationDevice();
}

/*!
    Returns TRUE if there are any requests scheduled that have not yet
    been executed; otherwise returns FALSE.

    The request that is being executed is \e not considered as a
    scheduled request.

    \sa clearPendingRequests() currentId() currentRequest()
*/
bool TQHttp::hasPendingRequests() const
{
    return d->pending.count() > 1;
}

/*!
    Deletes all pending requests from the list of scheduled requests.
    This does not affect the request that is being executed. If
    you want to stop this this as well, use abort().

    \sa hasPendingRequests() abort()
*/
void TQHttp::clearPendingRequests()
{
    TQHttpRequest *r = 0;
    if ( d->pending.count() > 0 )
	r = d->pending.take( 0 );
    d->pending.clear();
    if ( r )
	d->pending.append( r );
}

/*!
    Sets the HTTP server that is used for requests to \a hostname on
    port \a port.

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    \sa get() post() head() request() requestStarted() requestFinished() done()
*/
int TQHttp::setHost(const TQString &hostname, Q_UINT16 port )
{
    return addRequest( new TQHttpSetHostRequest( hostname, port ) );
}

/*!
    Sends a get request for \a path to the server set by setHost() or
    as specified in the constructor.

    \a path must be an absolute path like \c /index.html or an
    absolute URI like \c http://www.trolltech.com/index.html.

    If the IO device \a to is 0 the readyRead() signal is emitted
    every time new content data is available to read.

    If the IO device \a to is not 0, the content data of the response
    is written directly to the device. Make sure that the \a to
    pointer is valid for the duration of the operation (it is safe to
    delete it when the requestFinished() signal is emitted).

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    \sa setHost() post() head() request() requestStarted() requestFinished() done()
*/
int TQHttp::get( const TQString& path, TQIODevice* to )
{
    TQHttpRequestHeader header( "GET", path );
    header.setValue( "Connection", "Keep-Alive" );
    return addRequest( new TQHttpPGHRequest( header, (TQIODevice*)0, to ) );
}

/*!
    Sends a post request for \a path to the server set by setHost() or
    as specified in the constructor.

    \a path must be an absolute path like \c /index.html or an
    absolute URI like \c http://www.trolltech.com/index.html.

    The incoming data comes via the \a data IO device.

    If the IO device \a to is 0 the readyRead() signal is emitted
    every time new content data is available to read.

    If the IO device \a to is not 0, the content data of the response
    is written directly to the device. Make sure that the \a to
    pointer is valid for the duration of the operation (it is safe to
    delete it when the requestFinished() signal is emitted).

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    \sa setHost() get() head() request() requestStarted() requestFinished() done()
*/
int TQHttp::post( const TQString& path, TQIODevice* data, TQIODevice* to  )
{
    TQHttpRequestHeader header( "POST", path );
    header.setValue( "Connection", "Keep-Alive" );
    return addRequest( new TQHttpPGHRequest( header, data, to ) );
}

/*!
    \overload

    \a data is used as the content data of the HTTP request.
*/
int TQHttp::post( const TQString& path, const TQByteArray& data, TQIODevice* to )
{
    TQHttpRequestHeader header( "POST", path );
    header.setValue( "Connection", "Keep-Alive" );
    return addRequest( new TQHttpPGHRequest( header, new TQByteArray(data), to ) );
}

/*!
    Sends a header request for \a path to the server set by setHost()
    or as specified in the constructor.

    \a path must be an absolute path like \c /index.html or an
    absolute URI like \c http://www.trolltech.com/index.html.

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    \sa setHost() get() post() request() requestStarted() requestFinished() done()
*/
int TQHttp::head( const TQString& path )
{
    TQHttpRequestHeader header( "HEAD", path );
    header.setValue( "Connection", "Keep-Alive" );
    return addRequest( new TQHttpPGHRequest( header, (TQIODevice*)0, 0 ) );
}

/*!
    Sends a request to the server set by setHost() or as specified in
    the constructor. Uses the \a header as the HTTP request header.
    You are responsible for setting up a header that is appropriate
    for your request.

    The incoming data comes via the \a data IO device.

    If the IO device \a to is 0 the readyRead() signal is emitted
    every time new content data is available to read.

    If the IO device \a to is not 0, the content data of the response
    is written directly to the device. Make sure that the \a to
    pointer is valid for the duration of the operation (it is safe to
    delete it when the requestFinished() signal is emitted).

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    \sa setHost() get() post() head() requestStarted() requestFinished() done()
*/
int TQHttp::request( const TQHttpRequestHeader &header, TQIODevice *data, TQIODevice *to )
{
    return addRequest( new TQHttpNormalRequest( header, data, to ) );
}

/*!
    \overload

    \a data is used as the content data of the HTTP request.
*/
int TQHttp::request( const TQHttpRequestHeader &header, const TQByteArray &data, TQIODevice *to  )
{
    return addRequest( new TQHttpNormalRequest( header, new TQByteArray(data), to ) );
}

/*!
    Closes the connection; this is useful if you have a keep-alive
    connection and want to close it.

    For the requests issued with get(), post() and head(), TQHttp sets
    the connection to be keep-alive. You can also do this using the
    header you pass to the request() function. TQHttp only closes the
    connection to the HTTP server if the response header requires it
    to do so.

    The function does not block and returns immediately. The request
    is scheduled, and its execution is performed asynchronously. The
    function returns a unique identifier which is passed by
    requestStarted() and requestFinished().

    When the request is started the requestStarted() signal is
    emitted. When it is finished the requestFinished() signal is
    emitted.

    If you want to close the connection immediately, you have to use
    abort() instead.

    \sa stateChanged() abort() requestStarted() requestFinished() done()
*/
int TQHttp::closeConnection()
{
    return addRequest( new TQHttpCloseRequest() );
}

int TQHttp::addRequest( TQHttpRequest *req )
{
    d->pending.append( req );

    if ( d->pending.count() == 1 )
	// don't emit the requestStarted() signal before the id is returned
	TQTimer::singleShot( 0, this, SLOT(startNextRequest()) );

    return req->id;
}

void TQHttp::startNextRequest()
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r == 0 )
	return;

    d->error = NoError;
    d->errorString = tr( "Unknown error" );

    if ( bytesAvailable() )
	readAll(); // clear the data
    emit requestStarted( r->id );
    r->start( this );
}

void TQHttp::sendRequest()
{
    if ( d->hostname.isNull() ) {
	finishedWithError( tr("No server set to connect to"), UnknownError );
	return;
    }

    killIdleTimer();

    // Do we need to setup a new connection or can we reuse an
    // existing one ?
    if ( d->socket.peerName() != d->hostname || d->socket.peerPort() != d->port
        || d->socket.state() != TQSocket::Connection ) {
	setState( TQHttp::Connecting );
	d->socket.connectToHost( d->hostname, d->port );
    } else {
        slotConnected();
    }

}

void TQHttp::finishedWithSuccess()
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r == 0 )
	return;

    emit requestFinished( r->id, FALSE );
    d->pending.removeFirst();
    if ( d->pending.isEmpty() ) {
	emit done( FALSE );
    } else {
	startNextRequest();
    }
}

void TQHttp::finishedWithError( const TQString& detail, int errorCode )
{
    TQHttpRequest *r = d->pending.getFirst();
    if ( r == 0 )
	return;

    d->error = (Error)errorCode;
    d->errorString = detail;
    emit requestFinished( r->id, TRUE );

    d->pending.clear();
    emit done( TRUE );
}

void TQHttp::slotClosed()
{
    if ( d->state == Closing )
	return;

    if ( d->state == Reading ) {
	if ( d->response.hasKey( "content-length" ) ) {
	    // We got Content-Length, so did we get all bytes?
	    if ( d->bytesDone+bytesAvailable() != d->response.contentLength() ) {
		finishedWithError( tr("Wrong content length"), WrongContentLength );
	    }
	}
    } else if ( d->state == Connecting || d->state == Sending ) {
	finishedWithError( tr("Server closed connection unexpectedly"), UnexpectedClose );
    }

    d->postDevice = 0;
    setState( Closing );
    d->idleTimer = startTimer( 0 );
}

void TQHttp::slotConnected()
{
    if ( d->state != Sending ) {
	d->bytesDone = 0;
	setState( Sending );
    }

    TQString str = d->header.toString();
    d->bytesTotal = str.length();
    d->socket.writeBlock( str.latin1(), d->bytesTotal );
#if defined(TQHTTP_DEBUG)
    qDebug( "TQHttp: write request header:\n---{\n%s}---", str.latin1() );
#endif

    if ( d->postDevice ) {
	d->bytesTotal += d->postDevice->size();
    } else {
	d->bytesTotal += d->buffer.size();
	d->socket.writeBlock( d->buffer.data(), d->buffer.size() );
	d->buffer = TQByteArray(); // save memory
    }
}

void TQHttp::slotError( int err )
{
    d->postDevice = 0;

    if ( d->state == Connecting || d->state == Reading || d->state == Sending ) {
	switch ( err ) {
	    case TQSocket::ErrConnectionRefused:
		finishedWithError( tr("Connection refused"), ConnectionRefused );
		break;
	    case TQSocket::ErrHostNotFound:
		finishedWithError( tr("Host %1 not found").arg(d->socket.peerName()), HostNotFound );
		break;
	    default:
		finishedWithError( tr("HTTP request failed"), UnknownError );
		break;
	}
    }

    close();
}

void TQHttp::slotBytesWritten( int written )
{
    d->bytesDone += written;
    emit dataSendProgress( d->bytesDone, d->bytesTotal );

    if ( !d->postDevice )
	return;

    if ( d->socket.bytesToWrite() == 0 ) {
	int max = TQMIN( 4096, d->postDevice->size() - d->postDevice->at() );
	TQByteArray arr( max );

	int n = d->postDevice->readBlock( arr.data(), max );
	if ( n != max ) {
	    qWarning("Could not read enough bytes from the device");
	    close();
	    return;
	}
	if ( d->postDevice->atEnd() ) {
	    d->postDevice = 0;
	}

	d->socket.writeBlock( arr.data(), max );
    }
}

void TQHttp::slotReadyRead()
{
    if ( d->state != Reading ) {
	setState( Reading );
	d->buffer = TQByteArray();
	d->readHeader = TRUE;
	d->headerStr = "";
	d->bytesDone = 0;
	d->chunkedSize = -1;
    }

    while ( d->readHeader ) {
	bool end = FALSE;
	TQString tmp;
	while ( !end && d->socket.canReadLine() ) {
	    tmp = d->socket.readLine();
	    if ( tmp == "\r\n" || tmp == "\n" )
		end = TRUE;
	    else
		d->headerStr += tmp;
	}

	if ( !end )
	    return;

#if defined(TQHTTP_DEBUG)
	qDebug( "TQHttp: read response header:\n---{\n%s}---", d->headerStr.latin1() );
#endif
	d->response = TQHttpResponseHeader( d->headerStr );
	d->headerStr = "";
#if defined(TQHTTP_DEBUG)
	qDebug( "TQHttp: read response header:\n---{\n%s}---", d->response.toString().latin1() );
#endif
	// Check header
	if ( !d->response.isValid() ) {
	    finishedWithError( tr("Invalid HTTP response header"), InvalidResponseHeader );
	    close();
	    return;
	}

	// The 100-continue header is ignored, because when using the
	// POST method, we send both the request header and data in
	// one chunk.
	if (d->response.statusCode() != 100) {
	    d->readHeader = FALSE;
	    if ( d->response.hasKey( "transfer-encoding" ) &&
		 d->response.value( "transfer-encoding" ).lower().contains( "chunked" ) )
		d->chunkedSize = 0;

	    emit responseHeaderReceived( d->response );
	}
    }

    if ( !d->readHeader ) {
	bool everythingRead = FALSE;

	if ( currentRequest().method() == "HEAD" ) {
	    everythingRead = TRUE;
	} else {
	    Q_ULONG n = d->socket.bytesAvailable();
	    TQByteArray *arr = 0;
	    if ( d->chunkedSize != -1 ) {
		// transfer-encoding is chunked
		for ( ;; ) {
		    // get chunk size
		    if ( d->chunkedSize == 0 ) {
			if ( !d->socket.canReadLine() )
			    break;
			TQString sizeString = d->socket.readLine();
			int tPos = sizeString.find( ';' );
			if ( tPos != -1 )
			    sizeString.truncate( tPos );
			bool ok;
			d->chunkedSize = sizeString.toInt( &ok, 16 );
			if ( !ok ) {
			    finishedWithError( tr("Invalid HTTP chunked body"), WrongContentLength );
			    close();
                            delete arr;
			    return;
			}
			if ( d->chunkedSize == 0 ) // last-chunk
			    d->chunkedSize = -2;
		    }

		    // read trailer
		    while ( d->chunkedSize == -2 && d->socket.canReadLine() ) {
			TQString read = d->socket.readLine();
			if ( read == "\r\n" || read == "\n" )
			    d->chunkedSize = -1;
		    }
		    if ( d->chunkedSize == -1 ) {
			everythingRead = TRUE;
			break;
		    }

		    // make sure that you can read the terminating CRLF,
		    // otherwise wait until next time...
		    n = d->socket.bytesAvailable();
		    if ( n == 0 )
			break;
		    if ( (Q_LONG)n == d->chunkedSize || (Q_LONG)n == d->chunkedSize+1 ) {
			n = d->chunkedSize - 1;
			if ( n == 0 )
			    break;
		    }

		    // read data
		    uint toRead = TQMIN( (Q_LONG)n, (d->chunkedSize < 0 ? (Q_LONG)n : d->chunkedSize) );
		    if ( !arr )
			arr = new TQByteArray( 0 );
		    uint oldArrSize = arr->size();
		    arr->resize( oldArrSize + toRead );
		    Q_LONG read = d->socket.readBlock( arr->data()+oldArrSize, toRead );
		    arr->resize( oldArrSize + read );

		    d->chunkedSize -= read;

		    if ( d->chunkedSize == 0 && n - read >= 2 ) {
			// read terminating CRLF
			char tmp[2];
			d->socket.readBlock( tmp, 2 );
			if ( tmp[0] != '\r' || tmp[1] != '\n' ) {
			    finishedWithError( tr("Invalid HTTP chunked body"), WrongContentLength );
			    close();
			    return;
			}
		    }
		}
	    } else if ( d->response.hasContentLength() ) {
		n = TQMIN( d->response.contentLength() - d->bytesDone, n );
		if ( n > 0 ) {
		    arr = new TQByteArray( n );
		    Q_LONG read = d->socket.readBlock( arr->data(), n );
		    arr->resize( read );
		}
		if ( d->bytesDone + bytesAvailable() + n == d->response.contentLength() )
		    everythingRead = TRUE;
	    } else if ( n > 0 ) {
		// workaround for VC++ bug
		TQByteArray temp = d->socket.readAll();
		arr = new TQByteArray( temp );
	    }

	    if ( arr ) {
		n = arr->size();
		if ( d->toDevice ) {
		    d->toDevice->writeBlock( arr->data(), n );
		    delete arr;
		    d->bytesDone += n;
#if defined(TQHTTP_DEBUG)
		    qDebug( "TQHttp::slotReadyRead(): read %ld bytes (%d bytes done)", n, d->bytesDone );
#endif
		    if ( d->response.hasContentLength() )
			emit dataReadProgress( d->bytesDone, d->response.contentLength() );
		    else
			emit dataReadProgress( d->bytesDone, 0 );
		} else {
		    d->rba.append( arr );
#if defined(TQHTTP_DEBUG)
		    qDebug( "TQHttp::slotReadyRead(): read %ld bytes (%ld bytes done)", n, d->bytesDone + bytesAvailable() );
#endif
		    if ( d->response.hasContentLength() )
			emit dataReadProgress( d->bytesDone + bytesAvailable(), d->response.contentLength() );
		    else
			emit dataReadProgress( d->bytesDone + bytesAvailable(), 0 );
		    emit readyRead( d->response );
		}
	    }
	}

	if ( everythingRead ) {
	    // Handle "Connection: close"
	    if ( d->response.value("connection").lower() == "close" ) {
		close();
	    } else {
		setState( Connected );
		// Start a timer, so that we emit the keep alive signal
		// "after" this method returned.
		d->idleTimer = startTimer( 0 );
	    }
	}
    }
}

/*!
    Returns the current state of the object. When the state changes,
    the stateChanged() signal is emitted.

    \sa State stateChanged()
*/
TQHttp::State TQHttp::state() const
{
    return d->state;
}

/*!
    Returns the last error that occurred. This is useful to find out
    what happened when receiving a requestFinished() or a done()
    signal with the \c error argument \c TRUE.

    If you start a new request, the error status is reset to \c NoError.
*/
TQHttp::Error TQHttp::error() const
{
    return d->error;
}

/*!
    Returns a human-readable description of the last error that
    occurred. This is useful to present a error message to the user
    when receiving a requestFinished() or a done() signal with the \c
    error argument \c TRUE.
*/
TQString TQHttp::errorString() const
{
    return d->errorString;
}

/*! \reimp
*/
void TQHttp::timerEvent( TQTimerEvent *e )
{
    if ( e->timerId() == d->idleTimer ) {
	killTimer( d->idleTimer );
	d->idleTimer = 0;

	if ( d->state == Connected ) {
	    finishedWithSuccess();
	} else if ( d->state != Unconnected ) {
	    setState( Unconnected );
	    finishedWithSuccess();
	}
    } else {
	TQObject::timerEvent( e );
    }
}

void TQHttp::killIdleTimer()
{
    killTimer( d->idleTimer );
    d->idleTimer = 0;
}

void TQHttp::setState( int s )
{
#if defined(TQHTTP_DEBUG)
    qDebug( "TQHttp state changed %d -> %d", d->state, s );
#endif
    d->state = (State)s;
    emit stateChanged( s );
}

void TQHttp::close()
{
    // If no connection is open -> ignore
    if ( d->state == Closing || d->state == Unconnected )
	return;

    d->postDevice = 0;
    setState( Closing );

    // Already closed ?
    if ( !d->socket.isOpen() ) {
	d->idleTimer = startTimer( 0 );
    } else {
	// Close now.
	d->socket.close();

	// Did close succeed immediately ?
	if ( d->socket.state() == TQSocket::Idle ) {
	    // Prepare to emit the requestFinished() signal.
	    d->idleTimer = startTimer( 0 );
	}
    }
}

/**********************************************************************
 *
 * TQHttp implementation of the TQNetworkProtocol interface
 *
 *********************************************************************/
/*! \reimp
*/
int TQHttp::supportedOperations() const
{
    return OpGet | OpPut;
}

/*! \reimp
*/
void TQHttp::operationGet( TQNetworkOperation *op )
{
    connect( this, SIGNAL(readyRead(const TQHttpResponseHeader&)),
	    this, SLOT(clientReply(const TQHttpResponseHeader&)) );
    connect( this, SIGNAL(done(bool)),
	    this, SLOT(clientDone(bool)) );
    connect( this, SIGNAL(stateChanged(int)),
	    this, SLOT(clientStateChanged(int)) );

    bytesRead = 0;
    op->setState( StInProgress );
    TQUrl u( operationInProgress()->arg( 0 ) );
    TQHttpRequestHeader header( "GET", u.encodedPathAndQuery(), 1, 0 );
    header.setValue( "Host", u.host() );
    setHost( u.host(), u.port() != -1 ? u.port() : 80 );
    request( header );
}

/*! \reimp
*/
void TQHttp::operationPut( TQNetworkOperation *op )
{
    connect( this, SIGNAL(readyRead(const TQHttpResponseHeader&)),
	    this, SLOT(clientReply(const TQHttpResponseHeader&)) );
    connect( this, SIGNAL(done(bool)),
	    this, SLOT(clientDone(bool)) );
    connect( this, SIGNAL(stateChanged(int)),
	    this, SLOT(clientStateChanged(int)) );

    bytesRead = 0;
    op->setState( StInProgress );
    TQUrl u( operationInProgress()->arg( 0 ) );
    TQHttpRequestHeader header( "POST", u.encodedPathAndQuery(), 1, 0 );
    header.setValue( "Host", u.host() );
    setHost( u.host(), u.port() != -1 ? u.port() : 80 );
    request( header, op->rawArg(1) );
}

void TQHttp::clientReply( const TQHttpResponseHeader &rep )
{
    TQNetworkOperation *op = operationInProgress();
    if ( op ) {
	if ( rep.statusCode() >= 400 && rep.statusCode() < 600 ) {
	    op->setState( StFailed );
	    op->setProtocolDetail(
		    TQString("%1 %2").arg(rep.statusCode()).arg(rep.reasonPhrase())
						    );
	    switch ( rep.statusCode() ) {
		case 401:
		case 403:
		case 405:
		    op->setErrorCode( ErrPermissionDenied );
		    break;
		case 404:
		    op->setErrorCode(ErrFileNotExisting );
		    break;
		default:
		    if ( op->operation() == OpGet )
			op->setErrorCode( ErrGet );
		    else
			op->setErrorCode( ErrPut );
		    break;
	    }
	}
	// ### In cases of an error, should we still emit the data() signals?
	if ( op->operation() == OpGet && bytesAvailable() > 0 ) {
	    TQByteArray ba = readAll();
	    emit data( ba, op );
	    bytesRead += ba.size();
	    if ( rep.hasContentLength() ) {
		emit dataTransferProgress( bytesRead, rep.contentLength(), op );
	    }
	}
    }
}

void TQHttp::clientDone( bool err )
{
    disconnect( this, SIGNAL(readyRead(const TQHttpResponseHeader&)),
	    this, SLOT(clientReply(const TQHttpResponseHeader&)) );
    disconnect( this, SIGNAL(done(bool)),
	    this, SLOT(clientDone(bool)) );
    disconnect( this, SIGNAL(stateChanged(int)),
	    this, SLOT(clientStateChanged(int)) );

    if ( err ) {
	TQNetworkOperation *op = operationInProgress();
	if ( op ) {
	    op->setState( TQNetworkProtocol::StFailed );
	    op->setProtocolDetail( errorString() );
	    switch ( error() ) {
		case ConnectionRefused:
		    op->setErrorCode( ErrHostNotFound );
		    break;
		case HostNotFound:
		    op->setErrorCode( ErrHostNotFound );
		    break;
		default:
		    if ( op->operation() == OpGet )
			op->setErrorCode( ErrGet );
		    else
			op->setErrorCode( ErrPut );
		    break;
	    }
	    emit finished( op );
	}
    } else {
	TQNetworkOperation *op = operationInProgress();
	if ( op ) {
	    if ( op->state() != StFailed ) {
		op->setState( TQNetworkProtocol::StDone );
		op->setErrorCode( TQNetworkProtocol::NoError );
	    }
	    emit finished( op );
	}
    }

}

void TQHttp::clientStateChanged( int state )
{
    if ( url() ) {
	switch ( (State)state ) {
	    case Connecting:
		emit connectionStateChanged( ConHostFound, tr( "Host %1 found" ).arg( url()->host() ) );
		break;
	    case Sending:
		emit connectionStateChanged( ConConnected, tr( "Connected to host %1" ).arg( url()->host() ) );
		break;
	    case Unconnected:
		emit connectionStateChanged( ConClosed, tr( "Connection to %1 closed" ).arg( url()->host() ) );
		break;
	    default:
		break;
	}
    } else {
	switch ( (State)state ) {
	    case Connecting:
		emit connectionStateChanged( ConHostFound, tr( "Host found" ) );
		break;
	    case Sending:
		emit connectionStateChanged( ConConnected, tr( "Connected to host" ) );
		break;
	    case Unconnected:
		emit connectionStateChanged( ConClosed, tr( "Connection closed" ) );
		break;
	    default:
		break;
	}
    }
}

#endif