source: trunk/src/network/access/qhttpnetworkreply.cpp@ 769

Last change on this file since 769 was 769, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.3 sources from branches/vendor/nokia/qt.

  • Property svn:eol-style set to native
File size: 25.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qhttpnetworkreply_p.h"
43#include "qhttpnetworkconnection_p.h"
44
45#include <qbytearraymatcher.h>
46
47#ifndef QT_NO_HTTP
48
49#ifndef QT_NO_OPENSSL
50# include <QtNetwork/qsslkey.h>
51# include <QtNetwork/qsslcipher.h>
52# include <QtNetwork/qsslconfiguration.h>
53#endif
54
55QT_BEGIN_NAMESPACE
56
57QHttpNetworkReply::QHttpNetworkReply(const QUrl &url, QObject *parent)
58 : QObject(*new QHttpNetworkReplyPrivate(url), parent)
59{
60}
61
62QHttpNetworkReply::~QHttpNetworkReply()
63{
64 Q_D(QHttpNetworkReply);
65 if (d->connection) {
66 d->connection->d_func()->removeReply(this);
67 }
68}
69
70QUrl QHttpNetworkReply::url() const
71{
72 return d_func()->url;
73}
74void QHttpNetworkReply::setUrl(const QUrl &url)
75{
76 Q_D(QHttpNetworkReply);
77 d->url = url;
78}
79
80qint64 QHttpNetworkReply::contentLength() const
81{
82 return d_func()->contentLength();
83}
84
85void QHttpNetworkReply::setContentLength(qint64 length)
86{
87 Q_D(QHttpNetworkReply);
88 d->setContentLength(length);
89}
90
91QList<QPair<QByteArray, QByteArray> > QHttpNetworkReply::header() const
92{
93 return d_func()->fields;
94}
95
96QByteArray QHttpNetworkReply::headerField(const QByteArray &name, const QByteArray &defaultValue) const
97{
98 return d_func()->headerField(name, defaultValue);
99}
100
101void QHttpNetworkReply::setHeaderField(const QByteArray &name, const QByteArray &data)
102{
103 Q_D(QHttpNetworkReply);
104 d->setHeaderField(name, data);
105}
106
107void QHttpNetworkReply::parseHeader(const QByteArray &header)
108{
109 Q_D(QHttpNetworkReply);
110 d->parseHeader(header);
111}
112
113QHttpNetworkRequest QHttpNetworkReply::request() const
114{
115 return d_func()->request;
116}
117
118void QHttpNetworkReply::setRequest(const QHttpNetworkRequest &request)
119{
120 Q_D(QHttpNetworkReply);
121 d->request = request;
122}
123
124int QHttpNetworkReply::statusCode() const
125{
126 return d_func()->statusCode;
127}
128
129void QHttpNetworkReply::setStatusCode(int code)
130{
131 Q_D(QHttpNetworkReply);
132 d->statusCode = code;
133}
134
135QString QHttpNetworkReply::errorString() const
136{
137 return d_func()->errorString;
138}
139
140QString QHttpNetworkReply::reasonPhrase() const
141{
142 return d_func()->reasonPhrase;
143}
144
145void QHttpNetworkReply::setErrorString(const QString &error)
146{
147 Q_D(QHttpNetworkReply);
148 d->errorString = error;
149}
150
151int QHttpNetworkReply::majorVersion() const
152{
153 return d_func()->majorVersion;
154}
155
156int QHttpNetworkReply::minorVersion() const
157{
158 return d_func()->minorVersion;
159}
160
161qint64 QHttpNetworkReply::bytesAvailable() const
162{
163 Q_D(const QHttpNetworkReply);
164 if (d->connection)
165 return d->connection->d_func()->uncompressedBytesAvailable(*this);
166 else
167 return -1;
168}
169
170qint64 QHttpNetworkReply::bytesAvailableNextBlock() const
171{
172 Q_D(const QHttpNetworkReply);
173 if (d->connection)
174 return d->connection->d_func()->uncompressedBytesAvailableNextBlock(*this);
175 else
176 return -1;
177}
178
179QByteArray QHttpNetworkReply::readAny()
180{
181 Q_D(QHttpNetworkReply);
182 if (d->responseData.bufferCount() == 0)
183 return QByteArray();
184
185 // we'll take the last buffer, so schedule another read from http
186 if (d->downstreamLimited && d->responseData.bufferCount() == 1)
187 d->connection->d_func()->readMoreLater(this);
188 return d->responseData.read();
189}
190
191void QHttpNetworkReply::setDownstreamLimited(bool dsl)
192{
193 Q_D(QHttpNetworkReply);
194 d->downstreamLimited = dsl;
195 d->connection->d_func()->readMoreLater(this);
196}
197
198bool QHttpNetworkReply::isFinished() const
199{
200 return d_func()->state == QHttpNetworkReplyPrivate::AllDoneState;
201}
202
203bool QHttpNetworkReply::isPipeliningUsed() const
204{
205 return d_func()->pipeliningUsed;
206}
207
208
209QHttpNetworkReplyPrivate::QHttpNetworkReplyPrivate(const QUrl &newUrl)
210 : QHttpNetworkHeaderPrivate(newUrl), state(NothingDoneState), statusCode(100),
211 majorVersion(0), minorVersion(0), bodyLength(0), contentRead(0), totalProgress(0),
212 chunkedTransferEncoding(false),
213 connectionCloseEnabled(true),
214 forceConnectionCloseEnabled(false),
215 currentChunkSize(0), currentChunkRead(0), connection(0), initInflate(false),
216 autoDecompress(false), responseData(), requestIsPrepared(false)
217 ,pipeliningUsed(false), downstreamLimited(false)
218{
219}
220
221QHttpNetworkReplyPrivate::~QHttpNetworkReplyPrivate()
222{
223}
224
225void QHttpNetworkReplyPrivate::clearHttpLayerInformation()
226{
227 state = NothingDoneState;
228 statusCode = 100;
229 bodyLength = 0;
230 contentRead = 0;
231 totalProgress = 0;
232 currentChunkSize = 0;
233 currentChunkRead = 0;
234 connectionCloseEnabled = true;
235#ifndef QT_NO_COMPRESS
236 if (initInflate)
237 inflateEnd(&inflateStrm);
238#endif
239 initInflate = false;
240 streamEnd = false;
241 fields.clear();
242}
243
244// TODO: Isn't everything HTTP layer related? We don't need to set connection and connectionChannel to 0 at all
245void QHttpNetworkReplyPrivate::clear()
246{
247 connection = 0;
248 connectionChannel = 0;
249 autoDecompress = false;
250 clearHttpLayerInformation();
251}
252
253// QHttpNetworkReplyPrivate
254qint64 QHttpNetworkReplyPrivate::bytesAvailable() const
255{
256 return (state != ReadingDataState ? 0 : fragment.size());
257}
258
259bool QHttpNetworkReplyPrivate::isGzipped()
260{
261 QByteArray encoding = headerField("content-encoding");
262 return qstricmp(encoding.constData(), "gzip") == 0;
263}
264
265void QHttpNetworkReplyPrivate::removeAutoDecompressHeader()
266{
267 // The header "Content-Encoding = gzip" is retained.
268 // Content-Length is removed since the actual one send by the server is for compressed data
269 QByteArray name("content-length");
270 QList<QPair<QByteArray, QByteArray> >::Iterator it = fields.begin(),
271 end = fields.end();
272 while (it != end) {
273 if (qstricmp(name.constData(), it->first.constData()) == 0) {
274 fields.erase(it);
275 break;
276 }
277 ++it;
278 }
279
280}
281
282bool QHttpNetworkReplyPrivate::findChallenge(bool forProxy, QByteArray &challenge) const
283{
284 challenge.clear();
285 // find out the type of authentication protocol requested.
286 QByteArray header = forProxy ? "proxy-authenticate" : "www-authenticate";
287 // pick the best protocol (has to match parsing in QAuthenticatorPrivate)
288 QList<QByteArray> challenges = headerFieldValues(header);
289 for (int i = 0; i<challenges.size(); i++) {
290 QByteArray line = challenges.at(i);
291 // todo use qstrincmp
292 if (!line.toLower().startsWith("negotiate"))
293 challenge = line;
294 }
295 return !challenge.isEmpty();
296}
297
298QAuthenticatorPrivate::Method QHttpNetworkReplyPrivate::authenticationMethod(bool isProxy) const
299{
300 // The logic is same as the one used in void QAuthenticatorPrivate::parseHttpResponse()
301 QAuthenticatorPrivate::Method method = QAuthenticatorPrivate::None;
302 QByteArray header = isProxy ? "proxy-authenticate" : "www-authenticate";
303 QList<QByteArray> challenges = headerFieldValues(header);
304 for (int i = 0; i<challenges.size(); i++) {
305 QByteArray line = challenges.at(i).trimmed().toLower();
306 if (method < QAuthenticatorPrivate::Basic
307 && line.startsWith("basic")) {
308 method = QAuthenticatorPrivate::Basic;
309 } else if (method < QAuthenticatorPrivate::Ntlm
310 && line.startsWith("ntlm")) {
311 method = QAuthenticatorPrivate::Ntlm;
312 } else if (method < QAuthenticatorPrivate::DigestMd5
313 && line.startsWith("digest")) {
314 method = QAuthenticatorPrivate::DigestMd5;
315 }
316 }
317 return method;
318}
319
320#ifndef QT_NO_COMPRESS
321bool QHttpNetworkReplyPrivate::gzipCheckHeader(QByteArray &content, int &pos)
322{
323 int method = 0; // method byte
324 int flags = 0; // flags byte
325 bool ret = false;
326
327 // Assure two bytes in the buffer so we can peek ahead -- handle case
328 // where first byte of header is at the end of the buffer after the last
329 // gzip segment
330 pos = -1;
331 QByteArray &body = content;
332 int maxPos = body.size()-1;
333 if (maxPos < 1) {
334 return ret;
335 }
336
337 // Peek ahead to check the gzip magic header
338 if (body[0] != char(gz_magic[0]) ||
339 body[1] != char(gz_magic[1])) {
340 return ret;
341 }
342 pos += 2;
343 // Check the rest of the gzip header
344 if (++pos <= maxPos)
345 method = body[pos];
346 if (pos++ <= maxPos)
347 flags = body[pos];
348 if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
349 return ret;
350 }
351
352 // Discard time, xflags and OS code:
353 pos += 6;
354 if (pos > maxPos)
355 return ret;
356 if ((flags & EXTRA_FIELD) && ((pos+2) <= maxPos)) { // skip the extra field
357 unsigned len = (unsigned)body[++pos];
358 len += ((unsigned)body[++pos])<<8;
359 pos += len;
360 if (pos > maxPos)
361 return ret;
362 }
363 if ((flags & ORIG_NAME) != 0) { // skip the original file name
364 while(++pos <= maxPos && body[pos]) {}
365 }
366 if ((flags & COMMENT) != 0) { // skip the .gz file comment
367 while(++pos <= maxPos && body[pos]) {}
368 }
369 if ((flags & HEAD_CRC) != 0) { // skip the header crc
370 pos += 2;
371 if (pos > maxPos)
372 return ret;
373 }
374 ret = (pos < maxPos); // return failed, if no more bytes left
375 return ret;
376}
377
378int QHttpNetworkReplyPrivate::gunzipBodyPartially(QByteArray &compressed, QByteArray &inflated)
379{
380 int ret = Z_DATA_ERROR;
381 unsigned have;
382 unsigned char out[CHUNK];
383 int pos = -1;
384
385 if (!initInflate) {
386 // check the header
387 if (!gzipCheckHeader(compressed, pos))
388 return ret;
389 // allocate inflate state
390 inflateStrm.zalloc = Z_NULL;
391 inflateStrm.zfree = Z_NULL;
392 inflateStrm.opaque = Z_NULL;
393 inflateStrm.avail_in = 0;
394 inflateStrm.next_in = Z_NULL;
395 ret = inflateInit2(&inflateStrm, -MAX_WBITS);
396 if (ret != Z_OK)
397 return ret;
398 initInflate = true;
399 streamEnd = false;
400 }
401
402 //remove the header.
403 compressed.remove(0, pos+1);
404 // expand until deflate stream ends
405 inflateStrm.next_in = (unsigned char *)compressed.data();
406 inflateStrm.avail_in = compressed.size();
407 do {
408 inflateStrm.avail_out = sizeof(out);
409 inflateStrm.next_out = out;
410 ret = inflate(&inflateStrm, Z_NO_FLUSH);
411 switch (ret) {
412 case Z_NEED_DICT:
413 ret = Z_DATA_ERROR;
414 // and fall through
415 case Z_DATA_ERROR:
416 case Z_MEM_ERROR:
417 inflateEnd(&inflateStrm);
418 initInflate = false;
419 return ret;
420 }
421 have = sizeof(out) - inflateStrm.avail_out;
422 inflated.append(QByteArray((const char *)out, have));
423 } while (inflateStrm.avail_out == 0);
424 // clean up and return
425 if (ret <= Z_ERRNO || ret == Z_STREAM_END) {
426 inflateEnd(&inflateStrm);
427 initInflate = false;
428 }
429 streamEnd = (ret == Z_STREAM_END);
430 return ret;
431}
432#endif
433
434qint64 QHttpNetworkReplyPrivate::readStatus(QAbstractSocket *socket)
435{
436 if (fragment.isEmpty()) {
437 // reserve bytes for the status line. This is better than always append() which reallocs the byte array
438 fragment.reserve(32);
439 }
440
441 qint64 bytes = 0;
442 char c;
443 qint64 haveRead = 0;
444
445 do {
446 haveRead = socket->read(&c, 1);
447 if (haveRead == -1)
448 return -1; // unexpected EOF
449 else if (haveRead == 0)
450 break; // read more later
451
452 bytes++;
453
454 // allow both CRLF & LF (only) line endings
455 if (c == '\n') {
456 // remove the CR at the end
457 if (fragment.endsWith('\r')) {
458 fragment.truncate(fragment.length()-1);
459 }
460 bool ok = parseStatus(fragment);
461 state = ReadingHeaderState;
462 fragment.clear();
463 if (!ok) {
464 return -1;
465 }
466 break;
467 } else {
468 fragment.append(c);
469 }
470
471 // is this a valid reply?
472 if (fragment.length() >= 5 && !fragment.startsWith("HTTP/"))
473 {
474 fragment.clear();
475 return -1;
476 }
477 } while (haveRead == 1);
478
479 return bytes;
480}
481
482bool QHttpNetworkReplyPrivate::parseStatus(const QByteArray &status)
483{
484 // from RFC 2616:
485 // Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
486 // HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
487 // that makes: 'HTTP/n.n xxx Message'
488 // byte count: 0123456789012
489
490 static const int minLength = 11;
491 static const int dotPos = 6;
492 static const int spacePos = 8;
493 static const char httpMagic[] = "HTTP/";
494
495 if (status.length() < minLength
496 || !status.startsWith(httpMagic)
497 || status.at(dotPos) != '.'
498 || status.at(spacePos) != ' ') {
499 // I don't know how to parse this status line
500 return false;
501 }
502
503 // optimize for the valid case: defer checking until the end
504 majorVersion = status.at(dotPos - 1) - '0';
505 minorVersion = status.at(dotPos + 1) - '0';
506
507 int i = spacePos;
508 int j = status.indexOf(' ', i + 1); // j == -1 || at(j) == ' ' so j+1 == 0 && j+1 <= length()
509 const QByteArray code = status.mid(i + 1, j - i - 1);
510
511 bool ok;
512 statusCode = code.toInt(&ok);
513 reasonPhrase = QString::fromLatin1(status.constData() + j + 1);
514
515 return ok && uint(majorVersion) <= 9 && uint(minorVersion) <= 9;
516}
517
518qint64 QHttpNetworkReplyPrivate::readHeader(QAbstractSocket *socket)
519{
520 if (fragment.isEmpty()) {
521 // according to http://dev.opera.com/articles/view/mama-http-headers/ the average size of the header
522 // block is 381 bytes.
523 // reserve bytes. This is better than always append() which reallocs the byte array.
524 fragment.reserve(512);
525 }
526
527 qint64 bytes = 0;
528 char c = 0;
529 bool allHeaders = false;
530 qint64 haveRead = 0;
531 do {
532 haveRead = socket->read(&c, 1);
533 if (haveRead == 0) {
534 // read more later
535 break;
536 } else if (haveRead == -1) {
537 // connection broke down
538 return -1;
539 } else {
540 fragment.append(c);
541 bytes++;
542
543 if (c == '\n') {
544 // check for possible header endings. As per HTTP rfc,
545 // the header endings will be marked by CRLFCRLF. But
546 // we will allow CRLFCRLF, CRLFLF, LFLF
547 if (fragment.endsWith("\r\n\r\n")
548 || fragment.endsWith("\r\n\n")
549 || fragment.endsWith("\n\n"))
550 allHeaders = true;
551
552 // there is another case: We have no headers. Then the fragment equals just the line ending
553 if ((fragment.length() == 2 && fragment.endsWith("\r\n"))
554 || (fragment.length() == 1 && fragment.endsWith("\n")))
555 allHeaders = true;
556 }
557 }
558 } while (!allHeaders && haveRead > 0);
559
560 // we received all headers now parse them
561 if (allHeaders) {
562 parseHeader(fragment);
563 state = ReadingDataState;
564 fragment.clear(); // next fragment
565 bodyLength = contentLength(); // cache the length
566
567 // cache isChunked() since it is called often
568 chunkedTransferEncoding = headerField("transfer-encoding").toLower().contains("chunked");
569
570 // cache isConnectionCloseEnabled since it is called often
571 QByteArray connectionHeaderField = headerField("connection");
572 // check for explicit indication of close or the implicit connection close of HTTP/1.0
573 connectionCloseEnabled = (connectionHeaderField.toLower().contains("close") ||
574 headerField("proxy-connection").toLower().contains("close")) ||
575 (majorVersion == 1 && minorVersion == 0 && connectionHeaderField.isEmpty());
576 }
577 return bytes;
578}
579
580void QHttpNetworkReplyPrivate::parseHeader(const QByteArray &header)
581{
582 // see rfc2616, sec 4 for information about HTTP/1.1 headers.
583 // allows relaxed parsing here, accepts both CRLF & LF line endings
584 const QByteArrayMatcher lf("\n");
585 const QByteArrayMatcher colon(":");
586 int i = 0;
587 while (i < header.count()) {
588 int j = colon.indexIn(header, i); // field-name
589 if (j == -1)
590 break;
591 const QByteArray field = header.mid(i, j - i).trimmed();
592 j++;
593 // any number of LWS is allowed before and after the value
594 QByteArray value;
595 do {
596 i = lf.indexIn(header, j);
597 if (i == -1)
598 break;
599 if (!value.isEmpty())
600 value += ' ';
601 // check if we have CRLF or only LF
602 bool hasCR = (i && header[i-1] == '\r');
603 int length = i -(hasCR ? 1: 0) - j;
604 value += header.mid(j, length).trimmed();
605 j = ++i;
606 } while (i < header.count() && (header.at(i) == ' ' || header.at(i) == '\t'));
607 if (i == -1)
608 break; // something is wrong
609
610 fields.append(qMakePair(field, value));
611 }
612}
613
614bool QHttpNetworkReplyPrivate::isChunked()
615{
616 return chunkedTransferEncoding;
617}
618
619bool QHttpNetworkReplyPrivate::isConnectionCloseEnabled()
620{
621 return connectionCloseEnabled || forceConnectionCloseEnabled;
622}
623
624// note this function can only be used for non-chunked, non-compressed with
625// known content length
626qint64 QHttpNetworkReplyPrivate::readBodyFast(QAbstractSocket *socket, QByteDataBuffer *rb)
627{
628 qint64 toBeRead = qMin(socket->bytesAvailable(), bodyLength - contentRead);
629 QByteArray bd;
630 bd.resize(toBeRead);
631 qint64 haveRead = socket->read(bd.data(), bd.size());
632 if (haveRead == -1) {
633 bd.clear();
634 return 0; // ### error checking here;
635 }
636 bd.resize(haveRead);
637
638 rb->append(bd);
639
640 if (contentRead + haveRead == bodyLength) {
641 state = AllDoneState;
642 }
643
644 contentRead += haveRead;
645 return haveRead;
646}
647
648
649qint64 QHttpNetworkReplyPrivate::readBody(QAbstractSocket *socket, QByteDataBuffer *out)
650{
651 qint64 bytes = 0;
652 if (isChunked()) {
653 bytes += readReplyBodyChunked(socket, out); // chunked transfer encoding (rfc 2616, sec 3.6)
654 } else if (bodyLength > 0) { // we have a Content-Length
655 bytes += readReplyBodyRaw(socket, out, bodyLength - contentRead);
656 if (contentRead + bytes == bodyLength)
657 state = AllDoneState;
658 } else {
659 bytes += readReplyBodyRaw(socket, out, socket->bytesAvailable());
660 }
661 contentRead += bytes;
662 return bytes;
663}
664
665qint64 QHttpNetworkReplyPrivate::readReplyBodyRaw(QIODevice *in, QByteDataBuffer *out, qint64 size)
666{
667 qint64 bytes = 0;
668 Q_ASSERT(in);
669 Q_ASSERT(out);
670
671 int toBeRead = qMin<qint64>(128*1024, qMin<qint64>(size, in->bytesAvailable()));
672 while (toBeRead > 0) {
673 QByteArray byteData;
674 byteData.resize(toBeRead);
675 qint64 haveRead = in->read(byteData.data(), byteData.size());
676 if (haveRead <= 0) {
677 // ### error checking here
678 byteData.clear();
679 return bytes;
680 }
681
682 byteData.resize(haveRead);
683 out->append(byteData);
684 bytes += haveRead;
685 size -= haveRead;
686
687 toBeRead = qMin<qint64>(128*1024, qMin<qint64>(size, in->bytesAvailable()));
688 }
689 return bytes;
690
691}
692
693qint64 QHttpNetworkReplyPrivate::readReplyBodyChunked(QIODevice *in, QByteDataBuffer *out)
694{
695 qint64 bytes = 0;
696 while (in->bytesAvailable()) { // while we can read from input
697 // if we are done with the current chunk, get the size of the new chunk
698 if (currentChunkRead >= currentChunkSize) {
699 currentChunkSize = 0;
700 currentChunkRead = 0;
701 if (bytes) {
702 char crlf[2];
703 bytes += in->read(crlf, 2); // read the "\r\n" after the chunk
704 }
705 bytes += getChunkSize(in, &currentChunkSize);
706 if (currentChunkSize == -1)
707 break;
708 }
709 // if the chunk size is 0, end of the stream
710 if (currentChunkSize == 0) {
711 state = AllDoneState;
712 break;
713 }
714
715 // otherwise, try to read what is missing for this chunk
716 qint64 haveRead = readReplyBodyRaw (in, out, currentChunkSize - currentChunkRead);
717 currentChunkRead += haveRead;
718 bytes += haveRead;
719
720 // ### error checking here
721
722 }
723 return bytes;
724}
725
726qint64 QHttpNetworkReplyPrivate::getChunkSize(QIODevice *in, qint64 *chunkSize)
727{
728 qint64 bytes = 0;
729 char crlf[2];
730 *chunkSize = -1;
731 int bytesAvailable = in->bytesAvailable();
732 while (bytesAvailable > bytes) {
733 qint64 sniffedBytes = in->peek(crlf, 2);
734 int fragmentSize = fragment.size();
735 // check the next two bytes for a "\r\n", skip blank lines
736 if ((fragmentSize && sniffedBytes == 2 && crlf[0] == '\r' && crlf[1] == '\n')
737 ||(fragmentSize > 1 && fragment.endsWith('\r') && crlf[0] == '\n'))
738 {
739 bytes += in->read(crlf, 1); // read the \r or \n
740 if (crlf[0] == '\r')
741 bytes += in->read(crlf, 1); // read the \n
742 bool ok = false;
743 // ignore the chunk-extension
744 fragment = fragment.mid(0, fragment.indexOf(';')).trimmed();
745 *chunkSize = fragment.toLong(&ok, 16);
746 fragment.clear();
747 break; // size done
748 } else {
749 // read the fragment to the buffer
750 char c = 0;
751 bytes += in->read(&c, 1);
752 fragment.append(c);
753 }
754 }
755 return bytes;
756}
757
758void QHttpNetworkReplyPrivate::appendUncompressedReplyData(QByteArray &qba)
759{
760 responseData.append(qba);
761
762 // clear the original! helps with implicit sharing and
763 // avoiding memcpy when the user is reading the data
764 qba.clear();
765}
766
767void QHttpNetworkReplyPrivate::appendUncompressedReplyData(QByteDataBuffer &data)
768{
769 responseData.append(data);
770
771 // clear the original! helps with implicit sharing and
772 // avoiding memcpy when the user is reading the data
773 data.clear();
774}
775
776void QHttpNetworkReplyPrivate::appendCompressedReplyData(QByteDataBuffer &data)
777{
778 // Work in progress: Later we will directly use a list of QByteArray or a QRingBuffer
779 // instead of one QByteArray.
780 for(int i = 0; i < data.bufferCount(); i++) {
781 QByteArray &byteData = data[i];
782 compressedData.append(byteData.constData(), byteData.size());
783 }
784 data.clear();
785}
786
787
788bool QHttpNetworkReplyPrivate::shouldEmitSignals()
789{
790 // for 401 & 407 don't emit the data signals. Content along with these
791 // responses are send only if the authentication fails.
792 return (statusCode != 401 && statusCode != 407);
793}
794
795bool QHttpNetworkReplyPrivate::expectContent()
796{
797 // check whether we can expect content after the headers (rfc 2616, sec4.4)
798 if ((statusCode >= 100 && statusCode < 200)
799 || statusCode == 204 || statusCode == 304)
800 return false;
801 if (request.operation() == QHttpNetworkRequest::Head)
802 return !shouldEmitSignals();
803 if (contentLength() == 0)
804 return false;
805 return true;
806}
807
808void QHttpNetworkReplyPrivate::eraseData()
809{
810 compressedData.clear();
811 responseData.clear();
812}
813
814
815// SSL support below
816#ifndef QT_NO_OPENSSL
817
818QSslConfiguration QHttpNetworkReply::sslConfiguration() const
819{
820 Q_D(const QHttpNetworkReply);
821
822 if (!d->connectionChannel)
823 return QSslConfiguration();
824
825 QSslSocket *sslSocket = qobject_cast<QSslSocket*>(d->connectionChannel->socket);
826 if (!sslSocket)
827 return QSslConfiguration();
828
829 return sslSocket->sslConfiguration();
830}
831
832void QHttpNetworkReply::setSslConfiguration(const QSslConfiguration &config)
833{
834 Q_D(QHttpNetworkReply);
835 if (d->connection)
836 d->connection->setSslConfiguration(config);
837}
838
839void QHttpNetworkReply::ignoreSslErrors()
840{
841 Q_D(QHttpNetworkReply);
842 if (d->connection)
843 d->connection->ignoreSslErrors();
844}
845
846void QHttpNetworkReply::ignoreSslErrors(const QList<QSslError> &errors)
847{
848 Q_D(QHttpNetworkReply);
849 if (d->connection)
850 d->connection->ignoreSslErrors(errors);
851}
852
853
854#endif //QT_NO_OPENSSL
855
856
857QT_END_NAMESPACE
858
859#endif // QT_NO_HTTP
Note: See TracBrowser for help on using the repository browser.