Initial import to Tizen
[profile/ivi/python-twisted.git] / twisted / web / _newclient.py
1 # -*- test-case-name: twisted.web.test.test_newclient -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4
5 """
6 An U{HTTP 1.1<http://www.w3.org/Protocols/rfc2616/rfc2616.html>} client.
7
8 The way to use the functionality provided by this module is to:
9
10   - Connect a L{HTTP11ClientProtocol} to an HTTP server
11   - Create a L{Request} with the appropriate data
12   - Pass the request to L{HTTP11ClientProtocol.request}
13   - The returned Deferred will fire with a L{Response} object
14   - Create a L{IProtocol} provider which can handle the response body
15   - Connect it to the response with L{Response.deliverBody}
16   - When the protocol's C{connectionLost} method is called, the response is
17     complete.  See L{Response.deliverBody} for details.
18
19 Various other classes in this module support this usage:
20
21   - HTTPParser is the basic HTTP parser.  It can handle the parts of HTTP which
22     are symmetric between requests and responses.
23
24   - HTTPClientParser extends HTTPParser to handle response-specific parts of
25     HTTP.  One instance is created for each request to parse the corresponding
26     response.
27 """
28
29 __metaclass__ = type
30
31 from zope.interface import implements
32
33 from twisted.python import log
34 from twisted.python.reflect import fullyQualifiedName
35 from twisted.python.failure import Failure
36 from twisted.python.compat import set
37 from twisted.internet.interfaces import IConsumer, IPushProducer
38 from twisted.internet.error import ConnectionDone
39 from twisted.internet.defer import Deferred, succeed, fail, maybeDeferred
40 from twisted.internet.protocol import Protocol
41 from twisted.protocols.basic import LineReceiver
42 from twisted.web.iweb import UNKNOWN_LENGTH, IResponse
43 from twisted.web.http_headers import Headers
44 from twisted.web.http import NO_CONTENT, NOT_MODIFIED
45 from twisted.web.http import _DataLoss, PotentialDataLoss
46 from twisted.web.http import _IdentityTransferDecoder, _ChunkedTransferDecoder
47
48 # States HTTPParser can be in
49 STATUS = 'STATUS'
50 HEADER = 'HEADER'
51 BODY = 'BODY'
52 DONE = 'DONE'
53
54
55 class BadHeaders(Exception):
56     """
57     Headers passed to L{Request} were in some way invalid.
58     """
59
60
61
62 class ExcessWrite(Exception):
63     """
64     The body L{IBodyProducer} for a request tried to write data after
65     indicating it had finished writing data.
66     """
67
68
69 class ParseError(Exception):
70     """
71     Some received data could not be parsed.
72
73     @ivar data: The string which could not be parsed.
74     """
75     def __init__(self, reason, data):
76         Exception.__init__(self, reason, data)
77         self.data = data
78
79
80
81 class BadResponseVersion(ParseError):
82     """
83     The version string in a status line was unparsable.
84     """
85
86
87
88 class _WrapperException(Exception):
89     """
90     L{_WrapperException} is the base exception type for exceptions which
91     include one or more other exceptions as the low-level causes.
92
93     @ivar reasons: A list of exceptions.  See subclass documentation for more
94         details.
95     """
96     def __init__(self, reasons):
97         Exception.__init__(self, reasons)
98         self.reasons = reasons
99
100
101
102 class RequestGenerationFailed(_WrapperException):
103     """
104     There was an error while creating the bytes which make up a request.
105
106     @ivar reasons: A C{list} of one or more L{Failure} instances giving the
107         reasons the request generation was considered to have failed.
108     """
109
110
111
112 class RequestTransmissionFailed(_WrapperException):
113     """
114     There was an error while sending the bytes which make up a request.
115
116     @ivar reasons: A C{list} of one or more L{Failure} instances giving the
117         reasons the request transmission was considered to have failed.
118     """
119
120
121
122 class ConnectionAborted(Exception):
123     """
124     The connection was explicitly aborted by application code.
125     """
126
127
128
129 class WrongBodyLength(Exception):
130     """
131     An L{IBodyProducer} declared the number of bytes it was going to
132     produce (via its C{length} attribute) and then produced a different number
133     of bytes.
134     """
135
136
137
138 class ResponseDone(Exception):
139     """
140     L{ResponseDone} may be passed to L{IProtocol.connectionLost} on the
141     protocol passed to L{Response.deliverBody} and indicates that the entire
142     response has been delivered.
143     """
144
145
146
147 class ResponseFailed(_WrapperException):
148     """
149     L{ResponseFailed} indicates that all of the response to a request was not
150     received for some reason.
151
152     @ivar reasons: A C{list} of one or more L{Failure} instances giving the
153         reasons the response was considered to have failed.
154
155     @ivar response: If specified, the L{Response} received from the server (and
156         in particular the status code and the headers).
157     """
158
159     def __init__(self, reasons, response=None):
160         _WrapperException.__init__(self, reasons)
161         self.response = response
162
163
164
165 class ResponseNeverReceived(ResponseFailed):
166     """
167     A L{ResponseFailed} that knows no response bytes at all have been received.
168     """
169
170
171
172 class RequestNotSent(Exception):
173     """
174     L{RequestNotSent} indicates that an attempt was made to issue a request but
175     for reasons unrelated to the details of the request itself, the request
176     could not be sent.  For example, this may indicate that an attempt was made
177     to send a request using a protocol which is no longer connected to a
178     server.
179     """
180
181
182
183 def _callAppFunction(function):
184     """
185     Call C{function}.  If it raises an exception, log it with a minimal
186     description of the source.
187
188     @return: C{None}
189     """
190     try:
191         function()
192     except:
193         log.err(None, "Unexpected exception from %s" % (
194                 fullyQualifiedName(function),))
195
196
197
198 class HTTPParser(LineReceiver):
199     """
200     L{HTTPParser} handles the parsing side of HTTP processing. With a suitable
201     subclass, it can parse either the client side or the server side of the
202     connection.
203
204     @ivar headers: All of the non-connection control message headers yet
205         received.
206
207     @ivar state: State indicator for the response parsing state machine.  One
208         of C{STATUS}, C{HEADER}, C{BODY}, C{DONE}.
209
210     @ivar _partialHeader: C{None} or a C{list} of the lines of a multiline
211         header while that header is being received.
212     """
213
214     # NOTE: According to HTTP spec, we're supposed to eat the
215     # 'Proxy-Authenticate' and 'Proxy-Authorization' headers also, but that
216     # doesn't sound like a good idea to me, because it makes it impossible to
217     # have a non-authenticating transparent proxy in front of an authenticating
218     # proxy. An authenticating proxy can eat them itself. -jknight
219     #
220     # Further, quoting
221     # http://homepages.tesco.net/J.deBoynePollard/FGA/web-proxy-connection-header.html
222     # regarding the 'Proxy-Connection' header:
223     #
224     #    The Proxy-Connection: header is a mistake in how some web browsers
225     #    use HTTP. Its name is the result of a false analogy. It is not a
226     #    standard part of the protocol. There is a different standard
227     #    protocol mechanism for doing what it does. And its existence
228     #    imposes a requirement upon HTTP servers such that no proxy HTTP
229     #    server can be standards-conforming in practice.
230     #
231     # -exarkun
232
233     # Some servers (like http://news.ycombinator.com/) return status lines and
234     # HTTP headers delimited by \n instead of \r\n.
235     delimiter = '\n'
236
237     CONNECTION_CONTROL_HEADERS = set([
238             'content-length', 'connection', 'keep-alive', 'te', 'trailers',
239             'transfer-encoding', 'upgrade', 'proxy-connection'])
240
241     def connectionMade(self):
242         self.headers = Headers()
243         self.connHeaders = Headers()
244         self.state = STATUS
245         self._partialHeader = None
246
247
248     def switchToBodyMode(self, decoder):
249         """
250         Switch to body parsing mode - interpret any more bytes delivered as
251         part of the message body and deliver them to the given decoder.
252         """
253         if self.state == BODY:
254             raise RuntimeError("already in body mode")
255
256         self.bodyDecoder = decoder
257         self.state = BODY
258         self.setRawMode()
259
260
261     def lineReceived(self, line):
262         """
263         Handle one line from a response.
264         """
265         # Handle the normal CR LF case.
266         if line[-1:] == '\r':
267             line = line[:-1]
268
269         if self.state == STATUS:
270             self.statusReceived(line)
271             self.state = HEADER
272         elif self.state == HEADER:
273             if not line or line[0] not in ' \t':
274                 if self._partialHeader is not None:
275                     header = ''.join(self._partialHeader)
276                     name, value = header.split(':', 1)
277                     value = value.strip()
278                     self.headerReceived(name, value)
279                 if not line:
280                     # Empty line means the header section is over.
281                     self.allHeadersReceived()
282                 else:
283                     # Line not beginning with LWS is another header.
284                     self._partialHeader = [line]
285             else:
286                 # A line beginning with LWS is a continuation of a header
287                 # begun on a previous line.
288                 self._partialHeader.append(line)
289
290
291     def rawDataReceived(self, data):
292         """
293         Pass data from the message body to the body decoder object.
294         """
295         self.bodyDecoder.dataReceived(data)
296
297
298     def isConnectionControlHeader(self, name):
299         """
300         Return C{True} if the given lower-cased name is the name of a
301         connection control header (rather than an entity header).
302
303         According to RFC 2616, section 14.10, the tokens in the Connection
304         header are probably relevant here.  However, I am not sure what the
305         practical consequences of either implementing or ignoring that are.
306         So I leave it unimplemented for the time being.
307         """
308         return name in self.CONNECTION_CONTROL_HEADERS
309
310
311     def statusReceived(self, status):
312         """
313         Callback invoked whenever the first line of a new message is received.
314         Override this.
315
316         @param status: The first line of an HTTP request or response message
317             without trailing I{CR LF}.
318         @type status: C{str}
319         """
320
321
322     def headerReceived(self, name, value):
323         """
324         Store the given header in C{self.headers}.
325         """
326         name = name.lower()
327         if self.isConnectionControlHeader(name):
328             headers = self.connHeaders
329         else:
330             headers = self.headers
331         headers.addRawHeader(name, value)
332
333
334     def allHeadersReceived(self):
335         """
336         Callback invoked after the last header is passed to C{headerReceived}.
337         Override this to change to the C{BODY} or C{DONE} state.
338         """
339         self.switchToBodyMode(None)
340
341
342
343 class HTTPClientParser(HTTPParser):
344     """
345     An HTTP parser which only handles HTTP responses.
346
347     @ivar request: The request with which the expected response is associated.
348     @type request: L{Request}
349
350     @ivar NO_BODY_CODES: A C{set} of response codes which B{MUST NOT} have a
351         body.
352
353     @ivar finisher: A callable to invoke when this response is fully parsed.
354
355     @ivar _responseDeferred: A L{Deferred} which will be called back with the
356         response when all headers in the response have been received.
357         Thereafter, C{None}.
358
359     @ivar _everReceivedData: C{True} if any bytes have been received.
360     """
361     NO_BODY_CODES = set([NO_CONTENT, NOT_MODIFIED])
362
363     _transferDecoders = {
364         'chunked': _ChunkedTransferDecoder,
365         }
366
367     bodyDecoder = None
368
369     def __init__(self, request, finisher):
370         self.request = request
371         self.finisher = finisher
372         self._responseDeferred = Deferred()
373         self._everReceivedData = False
374
375
376     def dataReceived(self, data):
377         """
378         Override so that we know if any response has been received.
379         """
380         self._everReceivedData = True
381         HTTPParser.dataReceived(self, data)
382
383
384     def parseVersion(self, strversion):
385         """
386         Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
387         'HTTP/1.1'.  Returns (protocol, major, minor).  Will raise ValueError
388         on bad syntax.
389         """
390         try:
391             proto, strnumber = strversion.split('/')
392             major, minor = strnumber.split('.')
393             major, minor = int(major), int(minor)
394         except ValueError, e:
395             raise BadResponseVersion(str(e), strversion)
396         if major < 0 or minor < 0:
397             raise BadResponseVersion("version may not be negative", strversion)
398         return (proto, major, minor)
399
400
401     def statusReceived(self, status):
402         """
403         Parse the status line into its components and create a response object
404         to keep track of this response's state.
405         """
406         parts = status.split(' ', 2)
407         if len(parts) != 3:
408             raise ParseError("wrong number of parts", status)
409
410         try:
411             statusCode = int(parts[1])
412         except ValueError:
413             raise ParseError("non-integer status code", status)
414
415         self.response = Response(
416             self.parseVersion(parts[0]),
417             statusCode,
418             parts[2],
419             self.headers,
420             self.transport)
421
422
423     def _finished(self, rest):
424         """
425         Called to indicate that an entire response has been received.  No more
426         bytes will be interpreted by this L{HTTPClientParser}.  Extra bytes are
427         passed up and the state of this L{HTTPClientParser} is set to I{DONE}.
428
429         @param rest: A C{str} giving any extra bytes delivered to this
430             L{HTTPClientParser} which are not part of the response being
431             parsed.
432         """
433         self.state = DONE
434         self.finisher(rest)
435
436
437     def isConnectionControlHeader(self, name):
438         """
439         Content-Length in the response to a HEAD request is an entity header,
440         not a connection control header.
441         """
442         if self.request.method == 'HEAD' and name == 'content-length':
443             return False
444         return HTTPParser.isConnectionControlHeader(self, name)
445
446
447     def allHeadersReceived(self):
448         """
449         Figure out how long the response body is going to be by examining
450         headers and stuff.
451         """
452         if (self.response.code in self.NO_BODY_CODES
453             or self.request.method == 'HEAD'):
454             self.response.length = 0
455             self._finished(self.clearLineBuffer())
456         else:
457             transferEncodingHeaders = self.connHeaders.getRawHeaders(
458                 'transfer-encoding')
459             if transferEncodingHeaders:
460
461                 # This could be a KeyError.  However, that would mean we do not
462                 # know how to decode the response body, so failing the request
463                 # is as good a behavior as any.  Perhaps someday we will want
464                 # to normalize/document/test this specifically, but failing
465                 # seems fine to me for now.
466                 transferDecoder = self._transferDecoders[transferEncodingHeaders[0].lower()]
467
468                 # If anyone ever invents a transfer encoding other than
469                 # chunked (yea right), and that transfer encoding can predict
470                 # the length of the response body, it might be sensible to
471                 # allow the transfer decoder to set the response object's
472                 # length attribute.
473             else:
474                 contentLengthHeaders = self.connHeaders.getRawHeaders('content-length')
475                 if contentLengthHeaders is None:
476                     contentLength = None
477                 elif len(contentLengthHeaders) == 1:
478                     contentLength = int(contentLengthHeaders[0])
479                     self.response.length = contentLength
480                 else:
481                     # "HTTP Message Splitting" or "HTTP Response Smuggling"
482                     # potentially happening.  Or it's just a buggy server.
483                     raise ValueError(
484                         "Too many Content-Length headers; response is invalid")
485
486                 if contentLength == 0:
487                     self._finished(self.clearLineBuffer())
488                     transferDecoder = None
489                 else:
490                     transferDecoder = lambda x, y: _IdentityTransferDecoder(
491                         contentLength, x, y)
492
493             if transferDecoder is None:
494                 self.response._bodyDataFinished()
495             else:
496                 # Make sure as little data as possible from the response body
497                 # gets delivered to the response object until the response
498                 # object actually indicates it is ready to handle bytes
499                 # (probably because an application gave it a way to interpret
500                 # them).
501                 self.transport.pauseProducing()
502                 self.switchToBodyMode(transferDecoder(
503                         self.response._bodyDataReceived,
504                         self._finished))
505
506         # This must be last.  If it were first, then application code might
507         # change some state (for example, registering a protocol to receive the
508         # response body).  Then the pauseProducing above would be wrong since
509         # the response is ready for bytes and nothing else would ever resume
510         # the transport.
511         self._responseDeferred.callback(self.response)
512         del self._responseDeferred
513
514
515     def connectionLost(self, reason):
516         if self.bodyDecoder is not None:
517             try:
518                 try:
519                     self.bodyDecoder.noMoreData()
520                 except PotentialDataLoss:
521                     self.response._bodyDataFinished(Failure())
522                 except _DataLoss:
523                     self.response._bodyDataFinished(
524                         Failure(ResponseFailed([reason, Failure()],
525                                                self.response)))
526                 else:
527                     self.response._bodyDataFinished()
528             except:
529                 # Handle exceptions from both the except suites and the else
530                 # suite.  Those functions really shouldn't raise exceptions,
531                 # but maybe there's some buggy application code somewhere
532                 # making things difficult.
533                 log.err()
534         elif self.state != DONE:
535             if self._everReceivedData:
536                 exceptionClass = ResponseFailed
537             else:
538                 exceptionClass = ResponseNeverReceived
539             self._responseDeferred.errback(Failure(exceptionClass([reason])))
540             del self._responseDeferred
541
542
543
544 class Request:
545     """
546     A L{Request} instance describes an HTTP request to be sent to an HTTP
547     server.
548
549     @ivar method: The HTTP method to for this request, ex: 'GET', 'HEAD',
550         'POST', etc.
551     @type method: C{str}
552
553     @ivar uri: The relative URI of the resource to request.  For example,
554         C{'/foo/bar?baz=quux'}.
555     @type uri: C{str}
556
557     @ivar headers: Headers to be sent to the server.  It is important to
558         note that this object does not create any implicit headers.  So it
559         is up to the HTTP Client to add required headers such as 'Host'.
560     @type headers: L{twisted.web.http_headers.Headers}
561
562     @ivar bodyProducer: C{None} or an L{IBodyProducer} provider which
563         produces the content body to send to the remote HTTP server.
564
565     @ivar persistent: Set to C{True} when you use HTTP persistent connection.
566     @type persistent: C{bool}
567     """
568     def __init__(self, method, uri, headers, bodyProducer, persistent=False):
569         self.method = method
570         self.uri = uri
571         self.headers = headers
572         self.bodyProducer = bodyProducer
573         self.persistent = persistent
574
575
576     def _writeHeaders(self, transport, TEorCL):
577         hosts = self.headers.getRawHeaders('host', ())
578         if len(hosts) != 1:
579             raise BadHeaders("Exactly one Host header required")
580
581         # In the future, having the protocol version be a parameter to this
582         # method would probably be good.  It would be nice if this method
583         # weren't limited to issueing HTTP/1.1 requests.
584         requestLines = []
585         requestLines.append(
586             '%s %s HTTP/1.1\r\n' % (self.method, self.uri))
587         if not self.persistent:
588             requestLines.append('Connection: close\r\n')
589         if TEorCL is not None:
590             requestLines.append(TEorCL)
591         for name, values in self.headers.getAllRawHeaders():
592             requestLines.extend(['%s: %s\r\n' % (name, v) for v in values])
593         requestLines.append('\r\n')
594         transport.writeSequence(requestLines)
595
596
597     def _writeToChunked(self, transport):
598         """
599         Write this request to the given transport using chunked
600         transfer-encoding to frame the body.
601         """
602         self._writeHeaders(transport, 'Transfer-Encoding: chunked\r\n')
603         encoder = ChunkedEncoder(transport)
604         encoder.registerProducer(self.bodyProducer, True)
605         d = self.bodyProducer.startProducing(encoder)
606
607         def cbProduced(ignored):
608             encoder.unregisterProducer()
609         def ebProduced(err):
610             encoder._allowNoMoreWrites()
611             # Don't call the encoder's unregisterProducer because it will write
612             # a zero-length chunk.  This would indicate to the server that the
613             # request body is complete.  There was an error, though, so we
614             # don't want to do that.
615             transport.unregisterProducer()
616             return err
617         d.addCallbacks(cbProduced, ebProduced)
618         return d
619
620
621     def _writeToContentLength(self, transport):
622         """
623         Write this request to the given transport using content-length to frame
624         the body.
625         """
626         self._writeHeaders(
627             transport,
628             'Content-Length: %d\r\n' % (self.bodyProducer.length,))
629
630         # This Deferred is used to signal an error in the data written to the
631         # encoder below.  It can only errback and it will only do so before too
632         # many bytes have been written to the encoder and before the producer
633         # Deferred fires.
634         finishedConsuming = Deferred()
635
636         # This makes sure the producer writes the correct number of bytes for
637         # the request body.
638         encoder = LengthEnforcingConsumer(
639             self.bodyProducer, transport, finishedConsuming)
640
641         transport.registerProducer(self.bodyProducer, True)
642
643         finishedProducing = self.bodyProducer.startProducing(encoder)
644
645         def combine(consuming, producing):
646             # This Deferred is returned and will be fired when the first of
647             # consuming or producing fires.
648             ultimate = Deferred()
649
650             # Keep track of what has happened so far.  This initially
651             # contains None, then an integer uniquely identifying what
652             # sequence of events happened.  See the callbacks and errbacks
653             # defined below for the meaning of each value.
654             state = [None]
655
656             def ebConsuming(err):
657                 if state == [None]:
658                     # The consuming Deferred failed first.  This means the
659                     # overall writeTo Deferred is going to errback now.  The
660                     # producing Deferred should not fire later (because the
661                     # consumer should have called stopProducing on the
662                     # producer), but if it does, a callback will be ignored
663                     # and an errback will be logged.
664                     state[0] = 1
665                     ultimate.errback(err)
666                 else:
667                     # The consuming Deferred errbacked after the producing
668                     # Deferred fired.  This really shouldn't ever happen.
669                     # If it does, I goofed.  Log the error anyway, just so
670                     # there's a chance someone might notice and complain.
671                     log.err(
672                         err,
673                         "Buggy state machine in %r/[%d]: "
674                         "ebConsuming called" % (self, state[0]))
675
676             def cbProducing(result):
677                 if state == [None]:
678                     # The producing Deferred succeeded first.  Nothing will
679                     # ever happen to the consuming Deferred.  Tell the
680                     # encoder we're done so it can check what the producer
681                     # wrote and make sure it was right.
682                     state[0] = 2
683                     try:
684                         encoder._noMoreWritesExpected()
685                     except:
686                         # Fail the overall writeTo Deferred - something the
687                         # producer did was wrong.
688                         ultimate.errback()
689                     else:
690                         # Success - succeed the overall writeTo Deferred.
691                         ultimate.callback(None)
692                 # Otherwise, the consuming Deferred already errbacked.  The
693                 # producing Deferred wasn't supposed to fire, but it did
694                 # anyway.  It's buggy, but there's not really anything to be
695                 # done about it.  Just ignore this result.
696
697             def ebProducing(err):
698                 if state == [None]:
699                     # The producing Deferred failed first.  This means the
700                     # overall writeTo Deferred is going to errback now.
701                     # Tell the encoder that we're done so it knows to reject
702                     # further writes from the producer (which should not
703                     # happen, but the producer may be buggy).
704                     state[0] = 3
705                     encoder._allowNoMoreWrites()
706                     ultimate.errback(err)
707                 else:
708                     # The producing Deferred failed after the consuming
709                     # Deferred failed.  It shouldn't have, so it's buggy.
710                     # Log the exception in case anyone who can fix the code
711                     # is watching.
712                     log.err(err, "Producer is buggy")
713
714             consuming.addErrback(ebConsuming)
715             producing.addCallbacks(cbProducing, ebProducing)
716
717             return ultimate
718
719         d = combine(finishedConsuming, finishedProducing)
720         def f(passthrough):
721             # Regardless of what happens with the overall Deferred, once it
722             # fires, the producer registered way up above the definition of
723             # combine should be unregistered.
724             transport.unregisterProducer()
725             return passthrough
726         d.addBoth(f)
727         return d
728
729
730     def writeTo(self, transport):
731         """
732         Format this L{Request} as an HTTP/1.1 request and write it to the given
733         transport.  If bodyProducer is not None, it will be associated with an
734         L{IConsumer}.
735
736         @return: A L{Deferred} which fires with C{None} when the request has
737             been completely written to the transport or with a L{Failure} if
738             there is any problem generating the request bytes.
739         """
740         if self.bodyProducer is not None:
741             if self.bodyProducer.length is UNKNOWN_LENGTH:
742                 return self._writeToChunked(transport)
743             else:
744                 return self._writeToContentLength(transport)
745         else:
746             self._writeHeaders(transport, None)
747             return succeed(None)
748
749
750     def stopWriting(self):
751         """
752         Stop writing this request to the transport.  This can only be called
753         after C{writeTo} and before the L{Deferred} returned by C{writeTo}
754         fires.  It should cancel any asynchronous task started by C{writeTo}.
755         The L{Deferred} returned by C{writeTo} need not be fired if this method
756         is called.
757         """
758         # If bodyProducer is None, then the Deferred returned by writeTo has
759         # fired already and this method cannot be called.
760         _callAppFunction(self.bodyProducer.stopProducing)
761
762
763
764 class LengthEnforcingConsumer:
765     """
766     An L{IConsumer} proxy which enforces an exact length requirement on the
767     total data written to it.
768
769     @ivar _length: The number of bytes remaining to be written.
770
771     @ivar _producer: The L{IBodyProducer} which is writing to this
772         consumer.
773
774     @ivar _consumer: The consumer to which at most C{_length} bytes will be
775         forwarded.
776
777     @ivar _finished: A L{Deferred} which will be fired with a L{Failure} if too
778         many bytes are written to this consumer.
779     """
780     def __init__(self, producer, consumer, finished):
781         self._length = producer.length
782         self._producer = producer
783         self._consumer = consumer
784         self._finished = finished
785
786
787     def _allowNoMoreWrites(self):
788         """
789         Indicate that no additional writes are allowed.  Attempts to write
790         after calling this method will be met with an exception.
791         """
792         self._finished = None
793
794
795     def write(self, bytes):
796         """
797         Write C{bytes} to the underlying consumer unless
798         C{_noMoreWritesExpected} has been called or there are/have been too
799         many bytes.
800         """
801         if self._finished is None:
802             # No writes are supposed to happen any more.  Try to convince the
803             # calling code to stop calling this method by calling its
804             # stopProducing method and then throwing an exception at it.  This
805             # exception isn't documented as part of the API because you're
806             # never supposed to expect it: only buggy code will ever receive
807             # it.
808             self._producer.stopProducing()
809             raise ExcessWrite()
810
811         if len(bytes) <= self._length:
812             self._length -= len(bytes)
813             self._consumer.write(bytes)
814         else:
815             # No synchronous exception is raised in *this* error path because
816             # we still have _finished which we can use to report the error to a
817             # better place than the direct caller of this method (some
818             # arbitrary application code).
819             _callAppFunction(self._producer.stopProducing)
820             self._finished.errback(WrongBodyLength("too many bytes written"))
821             self._allowNoMoreWrites()
822
823
824     def _noMoreWritesExpected(self):
825         """
826         Called to indicate no more bytes will be written to this consumer.
827         Check to see that the correct number have been written.
828
829         @raise WrongBodyLength: If not enough bytes have been written.
830         """
831         if self._finished is not None:
832             self._allowNoMoreWrites()
833             if self._length:
834                 raise WrongBodyLength("too few bytes written")
835
836
837
838 def makeStatefulDispatcher(name, template):
839     """
840     Given a I{dispatch} name and a function, return a function which can be
841     used as a method and which, when called, will call another method defined
842     on the instance and return the result.  The other method which is called is
843     determined by the value of the C{_state} attribute of the instance.
844
845     @param name: A string which is used to construct the name of the subsidiary
846         method to invoke.  The subsidiary method is named like C{'_%s_%s' %
847         (name, _state)}.
848
849     @param template: A function object which is used to give the returned
850         function a docstring.
851
852     @return: The dispatcher function.
853     """
854     def dispatcher(self, *args, **kwargs):
855         func = getattr(self, '_' + name + '_' + self._state, None)
856         if func is None:
857             raise RuntimeError(
858                 "%r has no %s method in state %s" % (self, name, self._state))
859         return func(*args, **kwargs)
860     dispatcher.__doc__ = template.__doc__
861     return dispatcher
862
863
864
865 class Response:
866     """
867     A L{Response} instance describes an HTTP response received from an HTTP
868     server.
869
870     L{Response} should not be subclassed or instantiated.
871
872     @ivar _transport: The transport which is delivering this response.
873
874     @ivar _bodyProtocol: The L{IProtocol} provider to which the body is
875         delivered.  C{None} before one has been registered with
876         C{deliverBody}.
877
878     @ivar _bodyBuffer: A C{list} of the strings passed to C{bodyDataReceived}
879         before C{deliverBody} is called.  C{None} afterwards.
880
881     @ivar _state: Indicates what state this L{Response} instance is in,
882         particularly with respect to delivering bytes from the response body
883         to an application-suppled protocol object.  This may be one of
884         C{'INITIAL'}, C{'CONNECTED'}, C{'DEFERRED_CLOSE'}, or C{'FINISHED'},
885         with the following meanings:
886
887           - INITIAL: This is the state L{Response} objects start in.  No
888             protocol has yet been provided and the underlying transport may
889             still have bytes to deliver to it.
890
891           - DEFERRED_CLOSE: If the underlying transport indicates all bytes
892             have been delivered but no application-provided protocol is yet
893             available, the L{Response} moves to this state.  Data is
894             buffered and waiting for a protocol to be delivered to.
895
896           - CONNECTED: If a protocol is provided when the state is INITIAL,
897             the L{Response} moves to this state.  Any buffered data is
898             delivered and any data which arrives from the transport
899             subsequently is given directly to the protocol.
900
901           - FINISHED: If a protocol is provided in the DEFERRED_CLOSE state,
902             the L{Response} moves to this state after delivering all
903             buffered data to the protocol.  Otherwise, if the L{Response} is
904             in the CONNECTED state, if the transport indicates there is no
905             more data, the L{Response} moves to this state.  Nothing else
906             can happen once the L{Response} is in this state.
907     """
908     implements(IResponse)
909
910     length = UNKNOWN_LENGTH
911
912     _bodyProtocol = None
913     _bodyFinished = False
914
915     def __init__(self, version, code, phrase, headers, _transport):
916         self.version = version
917         self.code = code
918         self.phrase = phrase
919         self.headers = headers
920         self._transport = _transport
921         self._bodyBuffer = []
922         self._state = 'INITIAL'
923
924
925     def deliverBody(self, protocol):
926         """
927         Dispatch the given L{IProtocol} depending of the current state of the
928         response.
929         """
930     deliverBody = makeStatefulDispatcher('deliverBody', deliverBody)
931
932
933     def _deliverBody_INITIAL(self, protocol):
934         """
935         Deliver any buffered data to C{protocol} and prepare to deliver any
936         future data to it.  Move to the C{'CONNECTED'} state.
937         """
938         # Now that there's a protocol to consume the body, resume the
939         # transport.  It was previously paused by HTTPClientParser to avoid
940         # reading too much data before it could be handled.
941         self._transport.resumeProducing()
942
943         protocol.makeConnection(self._transport)
944         self._bodyProtocol = protocol
945         for data in self._bodyBuffer:
946             self._bodyProtocol.dataReceived(data)
947         self._bodyBuffer = None
948         self._state = 'CONNECTED'
949
950
951     def _deliverBody_CONNECTED(self, protocol):
952         """
953         It is invalid to attempt to deliver data to a protocol when it is
954         already being delivered to another protocol.
955         """
956         raise RuntimeError(
957             "Response already has protocol %r, cannot deliverBody "
958             "again" % (self._bodyProtocol,))
959
960
961     def _deliverBody_DEFERRED_CLOSE(self, protocol):
962         """
963         Deliver any buffered data to C{protocol} and then disconnect the
964         protocol.  Move to the C{'FINISHED'} state.
965         """
966         # Unlike _deliverBody_INITIAL, there is no need to resume the
967         # transport here because all of the response data has been received
968         # already.  Some higher level code may want to resume the transport if
969         # that code expects further data to be received over it.
970
971         protocol.makeConnection(self._transport)
972
973         for data in self._bodyBuffer:
974             protocol.dataReceived(data)
975         self._bodyBuffer = None
976         protocol.connectionLost(self._reason)
977         self._state = 'FINISHED'
978
979
980     def _deliverBody_FINISHED(self, protocol):
981         """
982         It is invalid to attempt to deliver data to a protocol after the
983         response body has been delivered to another protocol.
984         """
985         raise RuntimeError(
986             "Response already finished, cannot deliverBody now.")
987
988
989     def _bodyDataReceived(self, data):
990         """
991         Called by HTTPClientParser with chunks of data from the response body.
992         They will be buffered or delivered to the protocol passed to
993         deliverBody.
994         """
995     _bodyDataReceived = makeStatefulDispatcher('bodyDataReceived',
996                                                _bodyDataReceived)
997
998
999     def _bodyDataReceived_INITIAL(self, data):
1000         """
1001         Buffer any data received for later delivery to a protocol passed to
1002         C{deliverBody}.
1003
1004         Little or no data should be buffered by this method, since the
1005         transport has been paused and will not be resumed until a protocol
1006         is supplied.
1007         """
1008         self._bodyBuffer.append(data)
1009
1010
1011     def _bodyDataReceived_CONNECTED(self, data):
1012         """
1013         Deliver any data received to the protocol to which this L{Response}
1014         is connected.
1015         """
1016         self._bodyProtocol.dataReceived(data)
1017
1018
1019     def _bodyDataReceived_DEFERRED_CLOSE(self, data):
1020         """
1021         It is invalid for data to be delivered after it has been indicated
1022         that the response body has been completely delivered.
1023         """
1024         raise RuntimeError("Cannot receive body data after _bodyDataFinished")
1025
1026
1027     def _bodyDataReceived_FINISHED(self, data):
1028         """
1029         It is invalid for data to be delivered after the response body has
1030         been delivered to a protocol.
1031         """
1032         raise RuntimeError("Cannot receive body data after protocol disconnected")
1033
1034
1035     def _bodyDataFinished(self, reason=None):
1036         """
1037         Called by HTTPClientParser when no more body data is available.  If the
1038         optional reason is supplied, this indicates a problem or potential
1039         problem receiving all of the response body.
1040         """
1041     _bodyDataFinished = makeStatefulDispatcher('bodyDataFinished',
1042                                                _bodyDataFinished)
1043
1044
1045     def _bodyDataFinished_INITIAL(self, reason=None):
1046         """
1047         Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to
1048         which to deliver the response body.
1049         """
1050         self._state = 'DEFERRED_CLOSE'
1051         if reason is None:
1052             reason = Failure(ResponseDone("Response body fully received"))
1053         self._reason = reason
1054
1055
1056     def _bodyDataFinished_CONNECTED(self, reason=None):
1057         """
1058         Disconnect the protocol and move to the C{'FINISHED'} state.
1059         """
1060         if reason is None:
1061             reason = Failure(ResponseDone("Response body fully received"))
1062         self._bodyProtocol.connectionLost(reason)
1063         self._bodyProtocol = None
1064         self._state = 'FINISHED'
1065
1066
1067     def _bodyDataFinished_DEFERRED_CLOSE(self):
1068         """
1069         It is invalid to attempt to notify the L{Response} of the end of the
1070         response body data more than once.
1071         """
1072         raise RuntimeError("Cannot finish body data more than once")
1073
1074
1075     def _bodyDataFinished_FINISHED(self):
1076         """
1077         It is invalid to attempt to notify the L{Response} of the end of the
1078         response body data more than once.
1079         """
1080         raise RuntimeError("Cannot finish body data after protocol disconnected")
1081
1082
1083
1084 class ChunkedEncoder:
1085     """
1086     Helper object which exposes L{IConsumer} on top of L{HTTP11ClientProtocol}
1087     for streaming request bodies to the server.
1088     """
1089     implements(IConsumer)
1090
1091     def __init__(self, transport):
1092         self.transport = transport
1093
1094
1095     def _allowNoMoreWrites(self):
1096         """
1097         Indicate that no additional writes are allowed.  Attempts to write
1098         after calling this method will be met with an exception.
1099         """
1100         self.transport = None
1101
1102
1103     def registerProducer(self, producer, streaming):
1104         """
1105         Register the given producer with C{self.transport}.
1106         """
1107         self.transport.registerProducer(producer, streaming)
1108
1109
1110     def write(self, data):
1111         """
1112         Write the given request body bytes to the transport using chunked
1113         encoding.
1114
1115         @type data: C{str}
1116         """
1117         if self.transport is None:
1118             raise ExcessWrite()
1119         self.transport.writeSequence(("%x\r\n" % len(data), data, "\r\n"))
1120
1121
1122     def unregisterProducer(self):
1123         """
1124         Indicate that the request body is complete and finish the request.
1125         """
1126         self.write('')
1127         self.transport.unregisterProducer()
1128         self._allowNoMoreWrites()
1129
1130
1131
1132 class TransportProxyProducer:
1133     """
1134     An L{IPushProducer} implementation which wraps another such thing and
1135     proxies calls to it until it is told to stop.
1136
1137     @ivar _producer: The wrapped L{IPushProducer} provider or C{None} after
1138         this proxy has been stopped.
1139     """
1140     implements(IPushProducer)
1141
1142     # LineReceiver uses this undocumented attribute of transports to decide
1143     # when to stop calling lineReceived or rawDataReceived (if it finds it to
1144     # be true, it doesn't bother to deliver any more data).  Set disconnecting
1145     # to False here and never change it to true so that all data is always
1146     # delivered to us and so that LineReceiver doesn't fail with an
1147     # AttributeError.
1148     disconnecting = False
1149
1150     def __init__(self, producer):
1151         self._producer = producer
1152
1153
1154     def _stopProxying(self):
1155         """
1156         Stop forwarding calls of L{IPushProducer} methods to the underlying
1157         L{IPushProvider} provider.
1158         """
1159         self._producer = None
1160
1161
1162     def stopProducing(self):
1163         """
1164         Proxy the stoppage to the underlying producer, unless this proxy has
1165         been stopped.
1166         """
1167         if self._producer is not None:
1168             self._producer.stopProducing()
1169
1170
1171     def resumeProducing(self):
1172         """
1173         Proxy the resumption to the underlying producer, unless this proxy has
1174         been stopped.
1175         """
1176         if self._producer is not None:
1177             self._producer.resumeProducing()
1178
1179
1180     def pauseProducing(self):
1181         """
1182         Proxy the pause to the underlying producer, unless this proxy has been
1183         stopped.
1184         """
1185         if self._producer is not None:
1186             self._producer.pauseProducing()
1187
1188
1189
1190 class HTTP11ClientProtocol(Protocol):
1191     """
1192     L{HTTP11ClientProtocol} is an implementation of the HTTP 1.1 client
1193     protocol.  It supports as few features as possible.
1194
1195     @ivar _parser: After a request is issued, the L{HTTPClientParser} to
1196         which received data making up the response to that request is
1197         delivered.
1198
1199     @ivar _finishedRequest: After a request is issued, the L{Deferred} which
1200         will fire when a L{Response} object corresponding to that request is
1201         available.  This allows L{HTTP11ClientProtocol} to fail the request
1202         if there is a connection or parsing problem.
1203
1204     @ivar _currentRequest: After a request is issued, the L{Request}
1205         instance used to make that request.  This allows
1206         L{HTTP11ClientProtocol} to stop request generation if necessary (for
1207         example, if the connection is lost).
1208
1209     @ivar _transportProxy: After a request is issued, the
1210         L{TransportProxyProducer} to which C{_parser} is connected.  This
1211         allows C{_parser} to pause and resume the transport in a way which
1212         L{HTTP11ClientProtocol} can exert some control over.
1213
1214     @ivar _responseDeferred: After a request is issued, the L{Deferred} from
1215         C{_parser} which will fire with a L{Response} when one has been
1216         received.  This is eventually chained with C{_finishedRequest}, but
1217         only in certain cases to avoid double firing that Deferred.
1218
1219     @ivar _state: Indicates what state this L{HTTP11ClientProtocol} instance
1220         is in with respect to transmission of a request and reception of a
1221         response.  This may be one of the following strings:
1222
1223           - QUIESCENT: This is the state L{HTTP11ClientProtocol} instances
1224             start in.  Nothing is happening: no request is being sent and no
1225             response is being received or expected.
1226
1227           - TRANSMITTING: When a request is made (via L{request}), the
1228             instance moves to this state.  L{Request.writeTo} has been used
1229             to start to send a request but it has not yet finished.
1230
1231           - TRANSMITTING_AFTER_RECEIVING_RESPONSE: The server has returned a
1232             complete response but the request has not yet been fully sent
1233             yet.  The instance will remain in this state until the request
1234             is fully sent.
1235
1236           - GENERATION_FAILED: There was an error while the request.  The
1237             request was not fully sent to the network.
1238
1239           - WAITING: The request was fully sent to the network.  The
1240             instance is now waiting for the response to be fully received.
1241
1242           - ABORTING: Application code has requested that the HTTP connection
1243             be aborted.
1244
1245           - CONNECTION_LOST: The connection has been lost.
1246
1247     @ivar _abortDeferreds: A list of C{Deferred} instances that will fire when
1248         the connection is lost.
1249     """
1250     _state = 'QUIESCENT'
1251     _parser = None
1252     _finishedRequest = None
1253     _currentRequest = None
1254     _transportProxy = None
1255     _responseDeferred = None
1256
1257
1258     def __init__(self, quiescentCallback=lambda c: None):
1259         self._quiescentCallback = quiescentCallback
1260         self._abortDeferreds = []
1261
1262
1263     @property
1264     def state(self):
1265         return self._state
1266
1267
1268     def request(self, request):
1269         """
1270         Issue C{request} over C{self.transport} and return a L{Deferred} which
1271         will fire with a L{Response} instance or an error.
1272
1273         @param request: The object defining the parameters of the request to
1274            issue.
1275         @type request: L{Request}
1276
1277         @rtype: L{Deferred}
1278         @return: The deferred may errback with L{RequestGenerationFailed} if
1279             the request was not fully written to the transport due to a local
1280             error.  It may errback with L{RequestTransmissionFailed} if it was
1281             not fully written to the transport due to a network error.  It may
1282             errback with L{ResponseFailed} if the request was sent (not
1283             necessarily received) but some or all of the response was lost.  It
1284             may errback with L{RequestNotSent} if it is not possible to send
1285             any more requests using this L{HTTP11ClientProtocol}.
1286         """
1287         if self._state != 'QUIESCENT':
1288             return fail(RequestNotSent())
1289
1290         self._state = 'TRANSMITTING'
1291         _requestDeferred = maybeDeferred(request.writeTo, self.transport)
1292         self._finishedRequest = Deferred()
1293
1294         # Keep track of the Request object in case we need to call stopWriting
1295         # on it.
1296         self._currentRequest = request
1297
1298         self._transportProxy = TransportProxyProducer(self.transport)
1299         self._parser = HTTPClientParser(request, self._finishResponse)
1300         self._parser.makeConnection(self._transportProxy)
1301         self._responseDeferred = self._parser._responseDeferred
1302
1303         def cbRequestWrotten(ignored):
1304             if self._state == 'TRANSMITTING':
1305                 self._state = 'WAITING'
1306                 self._responseDeferred.chainDeferred(self._finishedRequest)
1307
1308         def ebRequestWriting(err):
1309             if self._state == 'TRANSMITTING':
1310                 self._state = 'GENERATION_FAILED'
1311                 self.transport.loseConnection()
1312                 self._finishedRequest.errback(
1313                     Failure(RequestGenerationFailed([err])))
1314             else:
1315                 log.err(err, 'Error writing request, but not in valid state '
1316                              'to finalize request: %s' % self._state)
1317
1318         _requestDeferred.addCallbacks(cbRequestWrotten, ebRequestWriting)
1319
1320         return self._finishedRequest
1321
1322
1323     def _finishResponse(self, rest):
1324         """
1325         Called by an L{HTTPClientParser} to indicate that it has parsed a
1326         complete response.
1327
1328         @param rest: A C{str} giving any trailing bytes which were given to
1329             the L{HTTPClientParser} which were not part of the response it
1330             was parsing.
1331         """
1332     _finishResponse = makeStatefulDispatcher('finishResponse', _finishResponse)
1333
1334
1335     def _finishResponse_WAITING(self, rest):
1336         # Currently the rest parameter is ignored. Don't forget to use it if
1337         # we ever add support for pipelining. And maybe check what trailers
1338         # mean.
1339         if self._state == 'WAITING':
1340             self._state = 'QUIESCENT'
1341         else:
1342             # The server sent the entire response before we could send the
1343             # whole request.  That sucks.  Oh well.  Fire the request()
1344             # Deferred with the response.  But first, make sure that if the
1345             # request does ever finish being written that it won't try to fire
1346             # that Deferred.
1347             self._state = 'TRANSMITTING_AFTER_RECEIVING_RESPONSE'
1348             self._responseDeferred.chainDeferred(self._finishedRequest)
1349
1350         # This will happen if we're being called due to connection being lost;
1351         # if so, no need to disconnect parser again, or to call
1352         # _quiescentCallback.
1353         if self._parser is None:
1354             return
1355
1356         reason = ConnectionDone("synthetic!")
1357         connHeaders = self._parser.connHeaders.getRawHeaders('connection', ())
1358         if (('close' in connHeaders) or self._state != "QUIESCENT" or
1359             not self._currentRequest.persistent):
1360             self._giveUp(Failure(reason))
1361         else:
1362             # We call the quiescent callback first, to ensure connection gets
1363             # added back to connection pool before we finish the request.
1364             try:
1365                 self._quiescentCallback(self)
1366             except:
1367                 # If callback throws exception, just log it and disconnect;
1368                 # keeping persistent connections around is an optimisation:
1369                 log.err()
1370                 self.transport.loseConnection()
1371             self._disconnectParser(reason)
1372
1373
1374     _finishResponse_TRANSMITTING = _finishResponse_WAITING
1375
1376
1377     def _disconnectParser(self, reason):
1378         """
1379         If there is still a parser, call its C{connectionLost} method with the
1380         given reason.  If there is not, do nothing.
1381
1382         @type reason: L{Failure}
1383         """
1384         if self._parser is not None:
1385             parser = self._parser
1386             self._parser = None
1387             self._currentRequest = None
1388             self._finishedRequest = None
1389             self._responseDeferred = None
1390
1391             # The parser is no longer allowed to do anything to the real
1392             # transport.  Stop proxying from the parser's transport to the real
1393             # transport before telling the parser it's done so that it can't do
1394             # anything.
1395             self._transportProxy._stopProxying()
1396             self._transportProxy = None
1397             parser.connectionLost(reason)
1398
1399
1400     def _giveUp(self, reason):
1401         """
1402         Lose the underlying connection and disconnect the parser with the given
1403         L{Failure}.
1404
1405         Use this method instead of calling the transport's loseConnection
1406         method directly otherwise random things will break.
1407         """
1408         self.transport.loseConnection()
1409         self._disconnectParser(reason)
1410
1411
1412     def dataReceived(self, bytes):
1413         """
1414         Handle some stuff from some place.
1415         """
1416         try:
1417             self._parser.dataReceived(bytes)
1418         except:
1419             self._giveUp(Failure())
1420
1421
1422     def connectionLost(self, reason):
1423         """
1424         The underlying transport went away.  If appropriate, notify the parser
1425         object.
1426         """
1427     connectionLost = makeStatefulDispatcher('connectionLost', connectionLost)
1428
1429
1430     def _connectionLost_QUIESCENT(self, reason):
1431         """
1432         Nothing is currently happening.  Move to the C{'CONNECTION_LOST'}
1433         state but otherwise do nothing.
1434         """
1435         self._state = 'CONNECTION_LOST'
1436
1437
1438     def _connectionLost_GENERATION_FAILED(self, reason):
1439         """
1440         The connection was in an inconsistent state.  Move to the
1441         C{'CONNECTION_LOST'} state but otherwise do nothing.
1442         """
1443         self._state = 'CONNECTION_LOST'
1444
1445
1446     def _connectionLost_TRANSMITTING(self, reason):
1447         """
1448         Fail the L{Deferred} for the current request, notify the request
1449         object that it does not need to continue transmitting itself, and
1450         move to the C{'CONNECTION_LOST'} state.
1451         """
1452         self._state = 'CONNECTION_LOST'
1453         self._finishedRequest.errback(
1454             Failure(RequestTransmissionFailed([reason])))
1455         del self._finishedRequest
1456
1457         # Tell the request that it should stop bothering now.
1458         self._currentRequest.stopWriting()
1459
1460
1461     def _connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSE(self, reason):
1462         """
1463         Move to the C{'CONNECTION_LOST'} state.
1464         """
1465         self._state = 'CONNECTION_LOST'
1466
1467
1468     def _connectionLost_WAITING(self, reason):
1469         """
1470         Disconnect the response parser so that it can propagate the event as
1471         necessary (for example, to call an application protocol's
1472         C{connectionLost} method, or to fail a request L{Deferred}) and move
1473         to the C{'CONNECTION_LOST'} state.
1474         """
1475         self._disconnectParser(reason)
1476         self._state = 'CONNECTION_LOST'
1477
1478
1479     def _connectionLost_ABORTING(self, reason):
1480         """
1481         Disconnect the response parser with a L{ConnectionAborted} failure, and
1482         move to the C{'CONNECTION_LOST'} state.
1483         """
1484         self._disconnectParser(Failure(ConnectionAborted()))
1485         self._state = 'CONNECTION_LOST'
1486         for d in self._abortDeferreds:
1487             d.callback(None)
1488         self._abortDeferreds = []
1489
1490
1491     def abort(self):
1492         """
1493         Close the connection and cause all outstanding L{request} L{Deferred}s
1494         to fire with an error.
1495         """
1496         if self._state == "CONNECTION_LOST":
1497             return succeed(None)
1498         self.transport.loseConnection()
1499         self._state = 'ABORTING'
1500         d = Deferred()
1501         self._abortDeferreds.append(d)
1502         return d