http.py 40.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""HTTP server module.

"""

import BaseHTTPServer
23
24
25
import cgi
import logging
import mimetools
26
import OpenSSL
27
28
29
30
import os
import select
import socket
import sys
31
import time
32
import signal
33
import logging
Michael Hanselmann's avatar
Michael Hanselmann committed
34
import errno
35
import threading
Michael Hanselmann's avatar
Michael Hanselmann committed
36
37

from cStringIO import StringIO
38

39
from ganeti import constants
40
from ganeti import serializer
Michael Hanselmann's avatar
Michael Hanselmann committed
41
from ganeti import workerpool
42
from ganeti import utils
43
44


Michael Hanselmann's avatar
Michael Hanselmann committed
45
46
HTTP_CLIENT_THREADS = 10

47
48
HTTP_GANETI_VERSION = "Ganeti %s" % constants.RELEASE_VERSION

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
WEEKDAYNAME = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
MONTHNAME = [None,
             'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

# Default error message
DEFAULT_ERROR_CONTENT_TYPE = "text/html"
DEFAULT_ERROR_MESSAGE = """\
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""

HTTP_OK = 200
HTTP_NO_CONTENT = 204
HTTP_NOT_MODIFIED = 304

HTTP_0_9 = "HTTP/0.9"
HTTP_1_0 = "HTTP/1.0"
HTTP_1_1 = "HTTP/1.1"

HTTP_GET = "GET"
HTTP_HEAD = "HEAD"
78
79
80
HTTP_POST = "POST"
HTTP_PUT = "PUT"

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
81
HTTP_ETAG = "ETag"
82
83
84
85
86
87
88
89
HTTP_HOST = "Host"
HTTP_SERVER = "Server"
HTTP_DATE = "Date"
HTTP_USER_AGENT = "User-Agent"
HTTP_CONTENT_TYPE = "Content-Type"
HTTP_CONTENT_LENGTH = "Content-Length"
HTTP_CONNECTION = "Connection"
HTTP_KEEP_ALIVE = "Keep-Alive"
90

91
92
_SSL_UNEXPECTED_EOF = "Unexpected EOF"

93
94
95
96
97
# Socket operations
(SOCKOP_SEND,
 SOCKOP_RECV,
 SOCKOP_SHUTDOWN) = range(3)

98
99
100
101
102

class SocketClosed(socket.error):
  pass


103
104
105
106
107
108
class _HttpClientError(Exception):
  """Internal exception for HTTP client errors.

  This should only be used for internal error reporting.

  """
109
110
111
112
113
114
115
116


class _HttpSocketTimeout(Exception):
  """Internal exception for socket timeouts.

  This should only be used for internal error reporting.

  """
Michael Hanselmann's avatar
Michael Hanselmann committed
117
118


119
120
121
122
123
class HTTPException(Exception):
  code = None
  message = None

  def __init__(self, message=None):
124
    Exception.__init__(self)
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
    if message is not None:
      self.message = message


class HTTPBadRequest(HTTPException):
  code = 400


class HTTPForbidden(HTTPException):
  code = 403


class HTTPNotFound(HTTPException):
  code = 404


class HTTPGone(HTTPException):
  code = 410


class HTTPLengthRequired(HTTPException):
  code = 411


class HTTPInternalError(HTTPException):
  code = 500


class HTTPNotImplemented(HTTPException):
  code = 501


class HTTPServiceUnavailable(HTTPException):
  code = 503


161
162
163
164
class HTTPVersionNotSupported(HTTPException):
  code = 505


165
166
167
168
169
170
171
172
173
174
class HTTPJsonConverter:
  CONTENT_TYPE = "application/json"

  def Encode(self, data):
    return serializer.DumpJson(data)

  def Decode(self, data):
    return serializer.LoadJson(data)


175
def WaitForSocketCondition(poller, sock, event, timeout):
176
177
178
179
  """Waits for a condition to occur on the socket.

  @type poller: select.Poller
  @param poller: Poller object as created by select.poll()
180
181
  @type sock: socket
  @param socket: Wait for events on this socket
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
  @type event: int
  @param event: ORed condition (see select module)
  @type timeout: float or None
  @param timeout: Timeout in seconds
  @rtype: int or None
  @return: None for timeout, otherwise occured conditions

  """
  check = (event | select.POLLPRI |
           select.POLLNVAL | select.POLLHUP | select.POLLERR)

  if timeout is not None:
    # Poller object expects milliseconds
    timeout *= 1000

  poller.register(sock, event)
  try:
    while True:
      # TODO: If the main thread receives a signal and we have no timeout, we
      # could wait forever. This should check a global "quit" flag or
      # something every so often.
      io_events = poller.poll(timeout)
      if not io_events:
        # Timeout
        return None
      for (evfd, evcond) in io_events:
        if evcond & check:
          return evcond
  finally:
    poller.unregister(sock)


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
def SocketOperation(poller, sock, op, arg1, timeout):
  """Wrapper around socket functions.

  This function abstracts error handling for socket operations, especially
  for the complicated interaction with OpenSSL.

  @type poller: select.Poller
  @param poller: Poller object as created by select.poll()
  @type sock: socket
  @param socket: Socket for the operation
  @type op: int
  @param op: Operation to execute (SOCKOP_* constants)
  @type arg1: any
  @param arg1: Parameter for function (if needed)
  @type timeout: None or float
  @param timeout: Timeout in seconds or None

  """
  # TODO: event_poll/event_check/override
  if op == SOCKOP_SEND:
    event_poll = select.POLLOUT
    event_check = select.POLLOUT

  elif op == SOCKOP_RECV:
    event_poll = select.POLLIN
    event_check = select.POLLIN | select.POLLPRI

  elif op == SOCKOP_SHUTDOWN:
    event_poll = None
    event_check = None

    # The timeout is only used when OpenSSL requests polling for a condition.
    # It is not advisable to have no timeout for shutdown.
    assert timeout

  else:
    raise AssertionError("Invalid socket operation")

  # No override by default
  event_override = 0

  while True:
    # Poll only for certain operations and when asked for by an override
    if event_override or op in (SOCKOP_SEND, SOCKOP_RECV):
      if event_override:
        wait_for_event = event_override
      else:
        wait_for_event = event_poll

      event = WaitForSocketCondition(poller, sock, wait_for_event, timeout)
      if event is None:
        raise _HttpSocketTimeout()

      if (op == SOCKOP_RECV and
          event & (select.POLLNVAL | select.POLLHUP | select.POLLERR)):
        return ""

      if not event & wait_for_event:
        continue

    # Reset override
    event_override = 0

    try:
      try:
        if op == SOCKOP_SEND:
          return sock.send(arg1)

        elif op == SOCKOP_RECV:
          return sock.recv(arg1)

        elif op == SOCKOP_SHUTDOWN:
          if isinstance(sock, OpenSSL.SSL.ConnectionType):
            # PyOpenSSL's shutdown() doesn't take arguments
            return sock.shutdown()
          else:
            return sock.shutdown(arg1)

      except OpenSSL.SSL.WantWriteError:
        # OpenSSL wants to write, poll for POLLOUT
        event_override = select.POLLOUT
        continue

      except OpenSSL.SSL.WantReadError:
        # OpenSSL wants to read, poll for POLLIN
        event_override = select.POLLIN | select.POLLPRI
        continue

      except OpenSSL.SSL.WantX509LookupError:
        continue

      except OpenSSL.SSL.SysCallError, err:
        if op == SOCKOP_SEND:
          # arg1 is the data when writing
          if err.args and err.args[0] == -1 and arg1 == "":
            # errors when writing empty strings are expected
            # and can be ignored
            return 0

        elif op == SOCKOP_RECV:
          if err.args == (-1, _SSL_UNEXPECTED_EOF):
            return ""

        raise socket.error(err.args)

      except OpenSSL.SSL.Error, err:
        raise socket.error(err.args)

    except socket.error, err:
      if err.args and err.args[0] == errno.EAGAIN:
        # Ignore EAGAIN
        continue

      raise


330
331
332
333
334
335
336
337
338
339
340
341
342
class HttpSslParams(object):
  """Data class for SSL key and certificate.

  """
  def __init__(self, ssl_key_path, ssl_cert_path):
    """Initializes this class.

    @type ssl_key_path: string
    @param ssl_key_path: Path to file containing SSL key in PEM format
    @type ssl_cert_path: string
    @param ssl_cert_path: Path to file containing SSL certificate in PEM format

    """
343
344
    self.ssl_key_pem = utils.ReadFile(ssl_key_path)
    self.ssl_cert_pem = utils.ReadFile(ssl_cert_path)
345

346
347
348
349
350
351
352
  def GetKey(self):
    return OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM,
                                          self.ssl_key_pem)

  def GetCertificate(self):
    return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                           self.ssl_cert_pem)
353
354


355
356
357
358
359
360
class _HttpSocketBase(object):
  """Base class for HTTP server and client.

  """
  def __init__(self):
    self._using_ssl = None
361
    self._ssl_params = None
362
363
    self._ssl_key = None
    self._ssl_cert = None
364

365
  def _CreateSocket(self, ssl_params, ssl_verify_peer):
366
367
    """Creates a TCP socket and initializes SSL if needed.

368
369
    @type ssl_params: HttpSslParams
    @param ssl_params: SSL key and certificate
370
371
372
373
374
    @type ssl_verify_peer: bool
    @param ssl_verify_peer: Whether to require client certificate and compare
                            it with our certificate

    """
375
376
    self._ssl_params = ssl_params

377
378
379
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Should we enable SSL?
380
    self._using_ssl = ssl_params is not None
381
382
383
384

    if not self._using_ssl:
      return sock

385
386
387
    self._ssl_key = ssl_params.GetKey()
    self._ssl_cert = ssl_params.GetCertificate()

388
389
390
    ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
    ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2)

391
392
    ctx.use_privatekey(self._ssl_key)
    ctx.use_certificate(self._ssl_cert)
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
    ctx.check_privatekey()

    if ssl_verify_peer:
      ctx.set_verify(OpenSSL.SSL.VERIFY_PEER |
                     OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                     self._SSLVerifyCallback)

    return OpenSSL.SSL.Connection(ctx, sock)

  def _SSLVerifyCallback(self, conn, cert, errnum, errdepth, ok):
    """Verify the certificate provided by the peer

    We only compare fingerprints. The client must use the same certificate as
    we do on our side.

    """
409
    assert self._ssl_params, "SSL not initialized"
410

411
412
    return (self._ssl_cert.digest("sha1") == cert.digest("sha1") and
            self._ssl_cert.digest("md5") == cert.digest("md5"))
413
414


415
class HttpServerRequestExecutor(object):
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
  """Implements server side of HTTP

  This class implements the server side of HTTP. It's based on code of Python's
  BaseHTTPServer, from both version 2.4 and 3k. It does not support non-ASCII
  character encodings. Keep-alive connections are not supported.

  """
  # The default request version.  This only affects responses up until
  # the point where the request line is parsed, so it mainly decides what
  # the client gets back when sending a malformed request line.
  # Most web servers default to HTTP 0.9, i.e. don't send a status line.
  default_request_version = HTTP_0_9

  # Error message settings
  error_message_format = DEFAULT_ERROR_MESSAGE
  error_content_type = DEFAULT_ERROR_CONTENT_TYPE

  responses = BaseHTTPServer.BaseHTTPRequestHandler.responses

  def __init__(self, server, conn, client_addr, fileio_class):
    """Initializes this class.

    Part of the initialization is reading the request and eventual POST/PUT
    data sent by the client.

    """
    self._server = server

    # We default rfile to buffered because otherwise it could be
    # really slow for large data (a getc() call per byte); we make
    # wfile unbuffered because (a) often after a write() we want to
    # read and we need to flush the line; (b) big writes to unbuffered
    # files are typically optimized by stdio even when big reads
    # aren't.
    self.rfile = fileio_class(conn, mode="rb", bufsize=-1)
    self.wfile = fileio_class(conn, mode="wb", bufsize=0)

    self.client_addr = client_addr

    self.request_headers = None
    self.request_method = None
    self.request_path = None
    self.request_requestline = None
    self.request_version = self.default_request_version

    self.response_body = None
    self.response_code = HTTP_OK
    self.response_content_type = None
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
464
    self.response_headers = {}
465

466
    logging.info("Connection from %s:%s", client_addr[0], client_addr[1])
467
    try:
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
      try:
        try:
          try:
            # Read, parse and handle request
            self._ReadRequest()
            self._ReadPostData()
            self._HandleRequest()
          except HTTPException, err:
            self._SetErrorStatus(err)
        finally:
          # Try to send a response
          self._SendResponse()
          self._Close()
      except SocketClosed:
        pass
    finally:
      logging.info("Disconnected %s:%s", client_addr[0], client_addr[1])

  def _Close(self):
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
    if not self.wfile.closed:
      self.wfile.flush()
    self.wfile.close()
    self.rfile.close()

  def _DateTimeHeader(self):
    """Return the current date and time formatted for a message header.

    """
    (year, month, day, hh, mm, ss, wd, _, _) = time.gmtime()
    return ("%s, %02d %3s %4d %02d:%02d:%02d GMT" %
            (WEEKDAYNAME[wd], day, MONTHNAME[month], year, hh, mm, ss))

  def _SetErrorStatus(self, err):
    """Sets the response code and body from a HTTPException.

    @type err: HTTPException
    @param err: Exception instance

    """
    try:
      (shortmsg, longmsg) = self.responses[err.code]
    except KeyError:
      shortmsg = longmsg = "Unknown"

    if err.message:
      message = err.message
    else:
      message = shortmsg

    values = {
      "code": err.code,
      "message": cgi.escape(message),
      "explain": longmsg,
      }

    self.response_code = err.code
    self.response_content_type = self.error_content_type
    self.response_body = self.error_message_format % values

527
  def _HandleRequest(self):
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
    """Handle the actual request.

    Calls the actual handler function and converts exceptions into HTTP errors.

    """
    # Don't do anything if there's already been a problem
    if self.response_code != HTTP_OK:
      return

    assert self.request_method, "Status code %s requires a method" % HTTP_OK

    # Check whether client is still there
    self.rfile.read(0)

    try:
      try:
        result = self._server.HandleRequest(self)

        # TODO: Content-type
        encoder = HTTPJsonConverter()
        body = encoder.Encode(result)

        self.response_content_type = encoder.CONTENT_TYPE
        self.response_body = body
      except (HTTPException, KeyboardInterrupt, SystemExit):
        raise
      except Exception, err:
        logging.exception("Caught exception")
        raise HTTPInternalError(message=str(err))
      except:
        logging.exception("Unknown exception")
        raise HTTPInternalError(message="Unknown error")

    except HTTPException, err:
      self._SetErrorStatus(err)

564
  def _SendResponse(self):
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    """Sends response to the client.

    """
    # Check whether client is still there
    self.rfile.read(0)

    logging.info("%s:%s %s %s", self.client_addr[0], self.client_addr[1],
                 self.request_requestline, self.response_code)

    if self.response_code in self.responses:
      response_message = self.responses[self.response_code][0]
    else:
      response_message = ""

    if self.request_version != HTTP_0_9:
      self.wfile.write("%s %d %s\r\n" %
                       (self.request_version, self.response_code,
                        response_message))
583
584
585
586
      self._SendHeader(HTTP_SERVER, HTTP_GANETI_VERSION)
      self._SendHeader(HTTP_DATE, self._DateTimeHeader())
      self._SendHeader(HTTP_CONTENT_TYPE, self.response_content_type)
      self._SendHeader(HTTP_CONTENT_LENGTH, str(len(self.response_body)))
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
587
588
589
      for key, val in self.response_headers.iteritems():
        self._SendHeader(key, val)

590
      # We don't support keep-alive at this time
591
      self._SendHeader(HTTP_CONNECTION, "close")
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
      self.wfile.write("\r\n")

    if (self.request_method != HTTP_HEAD and
        self.response_code >= HTTP_OK and
        self.response_code not in (HTTP_NO_CONTENT, HTTP_NOT_MODIFIED)):
      self.wfile.write(self.response_body)

  def _SendHeader(self, name, value):
    if self.request_version != HTTP_0_9:
      self.wfile.write("%s: %s\r\n" % (name, value))

  def _ReadRequest(self):
    """Reads and parses request line

    """
    raw_requestline = self.rfile.readline()

    requestline = raw_requestline
    if requestline[-2:] == '\r\n':
      requestline = requestline[:-2]
    elif requestline[-1:] == '\n':
      requestline = requestline[:-1]

    if not requestline:
      raise HTTPBadRequest("Empty request line")

    self.request_requestline = requestline

    logging.debug("HTTP request: %s", raw_requestline.rstrip("\r\n"))

    words = requestline.split()

    if len(words) == 3:
      [method, path, version] = words
      if version[:5] != 'HTTP/':
        raise HTTPBadRequest("Bad request version (%r)" % version)

      try:
        base_version_number = version.split('/', 1)[1]
        version_number = base_version_number.split(".")

        # RFC 2145 section 3.1 says there can be only one "." and
        #   - major and minor numbers MUST be treated as
        #      separate integers;
        #   - HTTP/2.4 is a lower version than HTTP/2.13, which in
        #      turn is lower than HTTP/12.3;
        #   - Leading zeros MUST be ignored by recipients.
        if len(version_number) != 2:
          raise HTTPBadRequest("Bad request version (%r)" % version)

        version_number = int(version_number[0]), int(version_number[1])
      except (ValueError, IndexError):
        raise HTTPBadRequest("Bad request version (%r)" % version)

      if version_number >= (2, 0):
        raise HTTPVersionNotSupported("Invalid HTTP Version (%s)" %
                                      base_version_number)

    elif len(words) == 2:
      version = HTTP_0_9
      [method, path] = words
      if method != HTTP_GET:
        raise HTTPBadRequest("Bad HTTP/0.9 request type (%r)" % method)

    else:
      raise HTTPBadRequest("Bad request syntax (%r)" % requestline)

    # Examine the headers and look for a Connection directive
    headers = mimetools.Message(self.rfile, 0)

    self.request_method = method
    self.request_path = path
    self.request_version = version
    self.request_headers = headers

  def _ReadPostData(self):
    """Reads POST/PUT data

670
671
672
673
674
    Quoting RFC1945, section 7.2 (HTTP/1.0): "The presence of an entity body in
    a request is signaled by the inclusion of a Content-Length header field in
    the request message headers. HTTP/1.0 requests containing an entity body
    must include a valid Content-Length header field."

675
    """
676
677
    # While not according to specification, we only support an entity body for
    # POST and PUT.
678
679
    if (not self.request_method or
        self.request_method.upper() not in (HTTP_POST, HTTP_PUT)):
680
681
682
      self.request_post_data = None
      return

683
    content_length = None
684
    try:
685
686
687
688
      if HTTP_CONTENT_LENGTH in self.request_headers:
        content_length = int(self.request_headers[HTTP_CONTENT_LENGTH])
    except TypeError:
      pass
689
    except ValueError:
690
691
692
693
694
695
      pass

    # 411 Length Required is specified in RFC2616, section 10.4.12 (HTTP/1.1)
    if content_length is None:
      raise HTTPLengthRequired("Missing Content-Length header or"
                               " invalid format")
696
697
698
699

    data = self.rfile.read(content_length)

    # TODO: Content-type, error handling
700
701
702
703
    if data:
      self.request_post_data = HTTPJsonConverter().Decode(data)
    else:
      self.request_post_data = None
704
705
706
707

    logging.debug("HTTP POST data: %s", self.request_post_data)


708
class HttpServer(_HttpSocketBase):
709
710
711
712
713
714
715
  """Generic HTTP server class

  Users of this class must subclass it and override the HandleRequest function.

  """
  MAX_CHILDREN = 20

716
  def __init__(self, mainloop, local_address, port,
717
               ssl_params=None, ssl_verify_peer=False):
718
719
720
721
722
723
724
725
    """Initializes the HTTP server

    @type mainloop: ganeti.daemon.Mainloop
    @param mainloop: Mainloop used to poll for I/O events
    @type local_addess: string
    @param local_address: Local IP address to bind to
    @type port: int
    @param port: TCP port to listen on
726
727
    @type ssl_params: HttpSslParams
    @param ssl_params: SSL key and certificate
728
729
730
    @type ssl_verify_peer: bool
    @param ssl_verify_peer: Whether to require client certificate and compare
                            it with our certificate
731
732

    """
733
734
    _HttpSocketBase.__init__(self)

735
    self.mainloop = mainloop
736
737
    self.local_address = local_address
    self.port = port
738

739
    self.socket = self._CreateSocket(ssl_params, ssl_verify_peer)
740

741
742
    # Allow port to be reused
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
743

744
    if self._using_ssl:
745
746
747
748
749
750
751
752
753
754
      self._fileio_class = _SSLFileObject
    else:
      self._fileio_class = socket._fileobject

    self._children = []

    mainloop.RegisterIO(self, self.socket.fileno(), select.POLLIN)
    mainloop.RegisterSignal(self)

  def Start(self):
755
    self.socket.bind((self.local_address, self.port))
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    self.socket.listen(5)

  def Stop(self):
    self.socket.close()

  def OnIO(self, fd, condition):
    if condition & select.POLLIN:
      self._IncomingConnection()

  def OnSignal(self, signum):
    if signum == signal.SIGCHLD:
      self._CollectChildren(True)

  def _CollectChildren(self, quick):
    """Checks whether any child processes are done

    @type quick: bool
    @param quick: Whether to only use non-blocking functions

    """
    if not quick:
      # Don't wait for other processes if it should be a quick check
      while len(self._children) > self.MAX_CHILDREN:
        try:
780
781
782
783
          # Waiting without a timeout brings us into a potential DoS situation.
          # As soon as too many children run, we'll not respond to new
          # requests. The real solution would be to add a timeout for children
          # and killing them after some time.
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
          pid, status = os.waitpid(0, 0)
        except os.error:
          pid = None
        if pid and pid in self._children:
          self._children.remove(pid)

    for child in self._children:
      try:
        pid, status = os.waitpid(child, os.WNOHANG)
      except os.error:
        pid = None
      if pid and pid in self._children:
        self._children.remove(pid)

  def _IncomingConnection(self):
799
    """Called for each incoming connection
800

801
802
    """
    (connection, client_addr) = self.socket.accept()
803
804
805
806
807
808
809

    self._CollectChildren(False)

    pid = os.fork()
    if pid == 0:
      # Child process
      try:
810
811
        HttpServerRequestExecutor(self, connection, client_addr,
                                  self._fileio_class)
812
813
814
815
816
817
818
819
820
821
822
823
      except:
        logging.exception("Error while handling request from %s:%s",
                          client_addr[0], client_addr[1])
        os._exit(1)
      os._exit(0)
    else:
      self._children.append(pid)

  def HandleRequest(self, req):
    raise NotImplementedError()


Michael Hanselmann's avatar
Michael Hanselmann committed
824
class HttpClientRequest(object):
825
  def __init__(self, host, port, method, path, headers=None, post_data=None,
826
               ssl_params=None, ssl_verify_peer=False):
Michael Hanselmann's avatar
Michael Hanselmann committed
827
828
829
830
831
832
833
834
835
836
837
838
839
840
    """Describes an HTTP request.

    @type host: string
    @param host: Hostname
    @type port: int
    @param port: Port
    @type method: string
    @param method: Method name
    @type path: string
    @param path: Request path
    @type headers: dict or None
    @param headers: Additional headers to send
    @type post_data: string or None
    @param post_data: Additional data to send
841
842
843
844
845
    @type ssl_params: HttpSslParams
    @param ssl_params: SSL key and certificate
    @type ssl_verify_peer: bool
    @param ssl_verify_peer: Whether to compare our certificate with server's
                            certificate
Michael Hanselmann's avatar
Michael Hanselmann committed
846
847
848
849
850
851
852
853
854
855

    """
    if post_data is not None:
      assert method.upper() in (HTTP_POST, HTTP_PUT), \
        "Only POST and GET requests support sending data"

    assert path.startswith("/"), "Path must start with slash (/)"

    self.host = host
    self.port = port
856
    self.ssl_params = ssl_params
857
    self.ssl_verify_peer = ssl_verify_peer
Michael Hanselmann's avatar
Michael Hanselmann committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
    self.method = method
    self.path = path
    self.headers = headers
    self.post_data = post_data

    self.success = None
    self.error = None

    self.resp_status_line = None
    self.resp_version = None
    self.resp_status = None
    self.resp_reason = None
    self.resp_headers = None
    self.resp_body = None


874
class HttpClientRequestExecutor(_HttpSocketBase):
Michael Hanselmann's avatar
Michael Hanselmann committed
875
876
877
878
879
880
881
882
883
884
885
  # Default headers
  DEFAULT_HEADERS = {
    HTTP_USER_AGENT: HTTP_GANETI_VERSION,
    # TODO: For keep-alive, don't send "Connection: close"
    HTTP_CONNECTION: "close",
    }

  # Length limits
  STATUS_LINE_LENGTH_MAX = 512
  HEADER_LENGTH_MAX = 4 * 1024

886
  # Timeouts in seconds for socket layer
Michael Hanselmann's avatar
Michael Hanselmann committed
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
  # TODO: Make read timeout configurable per OpCode
  CONNECT_TIMEOUT = 5.0
  WRITE_TIMEOUT = 10
  READ_TIMEOUT = None
  CLOSE_TIMEOUT = 1

  # Parser state machine
  PS_STATUS_LINE = "status-line"
  PS_HEADERS = "headers"
  PS_BODY = "body"
  PS_COMPLETE = "complete"

  def __init__(self, req):
    """Initializes the HttpClientRequestExecutor class.

    @type req: HttpClientRequest
    @param req: Request object

    """
906
907
    _HttpSocketBase.__init__(self)

Michael Hanselmann's avatar
Michael Hanselmann committed
908
909
910
911
912
913
914
915
916
917
918
919
    self.request = req

    self.parser_status = self.PS_STATUS_LINE
    self.header_buffer = StringIO()
    self.body_buffer = StringIO()
    self.content_length = None
    self.server_will_close = None

    self.poller = select.poll()

    try:
      # TODO: Implement connection caching/keep-alive
920
      self.sock = self._CreateSocket(req.ssl_params,
921
                                     req.ssl_verify_peer)
Michael Hanselmann's avatar
Michael Hanselmann committed
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

      # Disable Python's timeout
      self.sock.settimeout(None)

      # Operate in non-blocking mode
      self.sock.setblocking(0)

      force_close = True
      self._Connect()
      try:
        self._SendRequest()
        self._ReadResponse()

        # Only wait for server to close if we didn't have any exception.
        force_close = False
      finally:
        self._CloseConnection(force_close)

      self.sock.close()
      self.sock = None

      req.resp_body = self.body_buffer.getvalue()

      req.success = True
      req.error = None

948
    except _HttpClientError, err:
Michael Hanselmann's avatar
Michael Hanselmann committed
949
950
951
952
953
954
955
956
957
958
959
960
961
962
      req.success = False
      req.error = str(err)

  def _BuildRequest(self):
    """Build HTTP request.

    @rtype: string
    @return: Complete request

    """
    # Headers
    send_headers = self.DEFAULT_HEADERS.copy()

    if self.request.headers:
963
      send_headers.update(self.request.headers)
Michael Hanselmann's avatar
Michael Hanselmann committed
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

    send_headers[HTTP_HOST] = "%s:%s" % (self.request.host, self.request.port)

    if self.request.post_data:
      send_headers[HTTP_CONTENT_LENGTH] = len(self.request.post_data)

    buf = StringIO()

    # Add request line. We only support HTTP/1.0 (no chunked transfers and no
    # keep-alive).
    # TODO: For keep-alive, change to HTTP/1.1
    buf.write("%s %s %s\r\n" % (self.request.method.upper(),
                                self.request.path, HTTP_1_0))

    # Add headers
    for name, value in send_headers.iteritems():
      buf.write("%s: %s\r\n" % (name, value))

    buf.write("\r\n")

    if self.request.post_data:
      buf.write(self.request.post_data)

    return buf.getvalue()

  def _ParseStatusLine(self):
    """Parses the status line sent by the server.

    """
    line = self.request.resp_status_line

    if not line:
996
      raise _HttpClientError("Empty status line")
Michael Hanselmann's avatar
Michael Hanselmann committed
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012

    try:
      [version, status, reason] = line.split(None, 2)
    except ValueError:
      try:
        [version, status] = line.split(None, 1)
        reason = ""
      except ValueError:
        version = HTTP_9_0

    if version:
      version = version.upper()

    if version not in (HTTP_1_0, HTTP_1_1):
      # We do not support HTTP/0.9, despite the specification requiring it
      # (RFC2616, section 19.6)
1013
1014
      raise _HttpClientError("Only HTTP/1.0 and HTTP/1.1 are supported (%r)" %
                             line)
Michael Hanselmann's avatar
Michael Hanselmann committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024

    # The status code is a three-digit number
    try:
      status = int(status)
      if status < 100 or status > 999:
        status = -1
    except ValueError:
      status = -1

    if status == -1:
1025
      raise _HttpClientError("Invalid status code (%r)" % line)
Michael Hanselmann's avatar
Michael Hanselmann committed
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

    self.request.resp_version = version
    self.request.resp_status = status
    self.request.resp_reason = reason

  def _WillServerCloseConnection(self):
    """Evaluate whether server will close the connection.

    @rtype: bool
    @return: Whether server will close the connection

    """
    hdr_connection = self.request.resp_headers.get(HTTP_CONNECTION, None)
    if hdr_connection:
      hdr_connection = hdr_connection.lower()

    # An HTTP/1.1 server is assumed to stay open unless explicitly closed.
    if self.request.resp_version == HTTP_1_1:
      return (hdr_connection and "close" in hdr_connection)

    # Some HTTP/1.0 implementations have support for persistent connections,
    # using rules different than HTTP/1.1.

    # For older HTTP, Keep-Alive indicates persistent connection.
    if self.request.resp_headers.get(HTTP_KEEP_ALIVE):
      return False

    # At least Akamai returns a "Connection: Keep-Alive" header, which was
    # supposed to be sent by the client.
    if hdr_connection and "keep-alive" in hdr_connection:
      return False

    return True

  def _ParseHeaders(self):
    """Parses the headers sent by the server.

    This function also adjusts internal variables based on the header values.

    """
    req = self.request

    # Parse headers
    self.header_buffer.seek(0, 0)
    req.resp_headers = mimetools.Message(self.header_buffer, 0)

    self.server_will_close = self._WillServerCloseConnection()

    # Do we have a Content-Length header?
    hdr_content_length = req.resp_headers.get(HTTP_CONTENT_LENGTH, None)
    if hdr_content_length:
      try:
        self.content_length = int(hdr_content_length)
      except ValueError:
        pass
      if self.content_length is not None and self.content_length < 0:
        self.content_length = None

    # does the body have a fixed length? (of zero)
    if (req.resp_status in (HTTP_NO_CONTENT, HTTP_NOT_MODIFIED) or
        100 <= req.resp_status < 200 or req.method == HTTP_HEAD):
      self.content_length = 0

    # if the connection remains open and a content-length was not provided,
    # then assume that the connection WILL close.
    if self.content_length is None:
      self.server_will_close = True

  def _CheckStatusLineLength(self, length):
    if length > self.STATUS_LINE_LENGTH_MAX:
1096
1097
      raise _HttpClientError("Status line longer than %d chars" %
                             self.STATUS_LINE_LENGTH_MAX)
Michael Hanselmann's avatar
Michael Hanselmann committed
1098
1099
1100

  def _CheckHeaderLength(self, length):
    if length > self.HEADER_LENGTH_MAX:
1101
1102
      raise _HttpClientError("Headers longer than %d chars" %
                             self.HEADER_LENGTH_MAX)
Michael Hanselmann's avatar
Michael Hanselmann committed
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

  def _ParseBuffer(self, buf, eof):
    """Main function for HTTP response state machine.

    @type buf: string
    @param buf: Receive buffer
    @type eof: bool
    @param eof: Whether we've reached EOF on the socket
    @rtype: string
    @return: Updated receive buffer

    """
    if self.parser_status == self.PS_STATUS_LINE:
      # Expect status line
      idx = buf.find("\r\n")
      if idx >= 0:
        self.request.resp_status_line = buf[:idx]

        self._CheckStatusLineLength(len(self.request.resp_status_line))

        # Remove status line, including CRLF
        buf = buf[idx + 2:]

        self._ParseStatusLine()

        self.parser_status = self.PS_HEADERS
      else:
        # Check whether incoming data is getting too large, otherwise we just
        # fill our read buffer.
        self._CheckStatusLineLength(len(buf))

    if self.parser_status == self.PS_HEADERS:
      # Wait for header end
      idx = buf.find("\r\n\r\n")
      if idx >= 0:
        self.header_buffer.write(buf[:idx + 2])

        self._CheckHeaderLength(self.header_buffer.tell())

        # Remove headers, including CRLF
        buf = buf[idx + 4:]

        self._ParseHeaders()

        self.parser_status = self.PS_BODY
      else:
        # Check whether incoming data is getting too large, otherwise we just
        # fill our read buffer.
        self._CheckHeaderLength(len(buf))

    if self.parser_status == self.PS_BODY:
      self.body_buffer.write(buf)
      buf = ""

      # Check whether we've read everything
      if (eof or
          (self.content_length is not None and
           self.body_buffer.tell() >= self.content_length)):
        self.parser_status = self.PS_COMPLETE

    return buf

  def _Connect(self):
    """Non-blocking connect to host with timeout.

    """
    connected = False
    while True:
1171
1172
1173
1174
1175
1176
      try:
        connect_error = self.sock.connect_ex((self.request.host,
                                              self.request.port))
      except socket.gaierror, err:
        raise _HttpClientError("Connection failed: %s" % str(err))

Michael Hanselmann's avatar
Michael Hanselmann committed
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
      if connect_error == errno.EINTR:
        # Mask signals
        pass

      elif connect_error == 0:
        # Connection established
        connected = True
        break

      elif connect_error == errno.EINPROGRESS:
        # Connection started
        break

1190
1191
      raise _HttpClientError("Connection failed (%s: %s)" %
                             (connect_error, os.strerror(connect_error)))
Michael Hanselmann's avatar
Michael Hanselmann committed
1192
1193
1194

    if not connected:
      # Wait for connection
1195
      event = WaitForSocketCondition(self.poller, self.sock,
1196
                                     select.POLLOUT, self.CONNECT_TIMEOUT)
Michael Hanselmann's avatar
Michael Hanselmann committed
1197
      if event is None:
1198
        raise _HttpClientError("Timeout while connecting to server")
Michael Hanselmann's avatar
Michael Hanselmann committed
1199
1200
1201
1202

      # Get error code
      connect_error = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
      if connect_error != 0:
1203
1204
        raise _HttpClientError("Connection failed (%s: %s)" %
                               (connect_error, os.strerror(connect_error)))
Michael Hanselmann's avatar
Michael Hanselmann committed
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219

    # Enable TCP keep-alive
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

    # If needed, Linux specific options are available to change the TCP
    # keep-alive settings, see "man 7 tcp" for TCP_KEEPCNT, TCP_KEEPIDLE and
    # TCP_KEEPINTVL.

  def _SendRequest(self):
    """Sends request to server.

    """
    buf = self._BuildRequest()

    while buf:
1220
1221
      # Send only 4 KB at a time
      data = buf[:4096]
Michael Hanselmann's avatar
Michael Hanselmann committed
1222

1223
1224
1225
1226
1227
1228
1229
      try:
        sent = SocketOperation(self.poller, self.sock, SOCKOP_SEND, data,
                               self.WRITE_TIMEOUT)
      except _HttpSocketTimeout:
        raise _HttpClientError("Timeout while sending request")
      except socket.error, err:
        raise _HttpClientError("Error sending request: %s" % err)
Michael Hanselmann's avatar
Michael Hanselmann committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244

      # Remove sent bytes
      buf = buf[sent:]

    assert not buf, "Request wasn't sent completely"

  def _ReadResponse(self):
    """Read response from server.

    Calls the parser function after reading a chunk of data.

    """
    buf = ""
    eof = False
    while self.parser_status != self.PS_COMPLETE:
1245
1246
1247
1248
1249
1250
1251
      try:
        data = SocketOperation(self.poller, self.sock, SOCKOP_RECV, 4096,
                               self.READ_TIMEOUT)
      except _HttpSocketTimeout:
        raise _HttpClientError("Timeout while reading response")
      except socket.error, err:
        raise _HttpClientError("Error while reading response: %s" % err)
Michael Hanselmann's avatar
Michael Hanselmann committed
1252

1253
1254
1255
      if data:
        buf += data
      else:
Michael Hanselmann's avatar
Michael Hanselmann committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
        eof = True

      # Do some parsing and error checking while more data arrives
      buf = self._ParseBuffer(buf, eof)

      # Must be done only after the buffer has been evaluated
      if (eof and
          self.parser_status in (self.PS_STATUS_LINE,
                                 self.PS_HEADERS)):
1265
        raise _HttpClientError("Connection closed prematurely")
Michael Hanselmann's avatar
Michael Hanselmann committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278

    # Parse rest
    buf = self._ParseBuffer(buf, True)

    assert self.parser_status == self.PS_COMPLETE
    assert not buf, "Parser didn't read full response"

  def _CloseConnection(self, force):
    """Closes the connection.

    """
    if self.server_will_close and not force:
      # Wait for server to close
1279
1280
      try:
        # Check whether it's actually closed
1281
1282
        if not SocketOperation(self.poller, self.sock, SOCKOP_RECV, 1,
                               self.CLOSE_TIMEOUT):
1283
          return
1284
      except (socket.error, _HttpClientError, _HttpSocketTimeout):
1285
        # Ignore errors at this stage
Michael Hanselmann's avatar
Michael Hanselmann committed
1286
1287
1288
        pass

    # Close the connection from our side
1289
1290
1291
1292
1293
1294
1295
    try:
      SocketOperation(self.poller, self.sock, SOCKOP_SHUTDOWN,
                      socket.SHUT_RDWR, self.WRITE_TIMEOUT)
    except _HttpSocketTimeout:
      raise _HttpClientError("Timeout while shutting down connection")
    except socket.error, err:
      raise _HttpClientError("Error while shutting down connection: %s" % err)
Michael Hanselmann's avatar
Michael Hanselmann committed
1296
1297


1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
class _HttpClientPendingRequest(object):
  """Data class for pending requests.

  """
  def __init__(self, request):
    self.request = request

    # Thread synchronization
    self.done = threading.Event()


Michael Hanselmann's avatar
Michael Hanselmann committed
1309
1310
1311
1312
class HttpClientWorker(workerpool.BaseWorker):
  """HTTP client worker class.

  """
1313
1314
1315
1316
1317
  def RunTask(self, pend_req):
    try:
      HttpClientRequestExecutor(pend_req.request)
    finally:
      pend_req.done.set()
Michael Hanselmann's avatar
Michael Hanselmann committed
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327


class HttpClientWorkerPool(workerpool.WorkerPool):
  def __init__(self, manager):
    workerpool.WorkerPool.__init__(self, HTTP_CLIENT_THREADS,
                                   HttpClientWorker)
    self.manager = manager


class HttpClientManager(object):
1328
1329
1330
  """Manages HTTP requests.

  """
Michael Hanselmann's avatar
Michael Hanselmann committed
1331
1332
1333
1334
1335
1336
1337
  def __init__(self):
    self._wpool = HttpClientWorkerPool(self)

  def __del__(self):
    self.Shutdown()

  def ExecRequests(self, requests):
1338
    """Execute HTTP requests.
Michael Hanselmann's avatar
Michael Hanselmann committed
1339

1340
    This function can be called from multiple threads at the same time.
Michael Hanselmann's avatar
Michael Hanselmann committed
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
    @type requests: List of HttpClientRequest instances
    @param requests: The requests to execute
    @rtype: List of HttpClientRequest instances
    @returns: The list of requests passed in

    """
    # _HttpClientPendingRequest is used for internal thread synchronization
    pending = [_HttpClientPendingRequest(req) for req in requests]

    try:
      # Add requests to queue
      for pend_req in pending:
        self._wpool.AddTask(pend_req)

    finally:
      # In case of an exception we should still wait for the rest, otherwise
      # another thread from the worker pool could modify the request object
      # after we returned.

      # And wait for them to finish
      for pend_req in pending:
        pend_req.done.wait()

    # Return original list
Michael Hanselmann's avatar
Michael Hanselmann committed
1366
1367
1368
    return requests

  def Shutdown(self):
1369
    self._wpool.Quiesce()
Michael Hanselmann's avatar
Michael Hanselmann committed
1370
1371
1372
    self._wpool.TerminateWorkers()


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
class _SSLFileObject(object):
  """Wrapper around socket._fileobject

  This wrapper is required to handle OpenSSL exceptions.

  """
  def _RequireOpenSocket(fn):
    def wrapper(self, *args, **kwargs):
      if self.closed:
        raise SocketClosed("Socket is closed")
      return fn(self, *args, **kwargs)
    return wrapper

  def __init__(self, sock, mode='rb', bufsize=-1):
    self._base = socket._fileobject(sock, mode=mode, bufsize=bufsize)

  def _ConnectionLost(self):
    self._base = None

  def _getclosed(self):
    return self._base is None or self._base.closed
  closed = property(_getclosed, doc="True if the file is closed")

  @_RequireOpenSocket
  def close(self):
    return self._base.close()

  @_RequireOpenSocket
  def flush(self):
    return self._base.flush()

  @_RequireOpenSocket
  def fileno(self):
    return self._base.fileno()

  @_RequireOpenSocket
  def read(self, size=-1):
    return self._ReadWrapper(self._base.read, size=size)

  @_RequireOpenSocket
  def readline(self, size=-1):
    return self._ReadWrapper(self._base.readline, size=size)

  def _ReadWrapper(self, fn, *args, **kwargs):
    while True:
      try:
        return fn(*args, **kwargs)

      except OpenSSL.SSL.ZeroReturnError, err:
        self._ConnectionLost()
        return ""

      except OpenSSL.SSL.WantReadError:
        continue

      #except OpenSSL.SSL.WantWriteError:
      # TODO

      except OpenSSL.SSL.SysCallError, (retval, desc):
1432
        if ((retval == -1 and desc == _SSL_UNEXPECTED_EOF)
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
            or retval > 0):
          self._ConnectionLost()
          return ""

        logging.exception("Error in OpenSSL")
        self._ConnectionLost()
        raise socket.error(err.args)

      except OpenSSL.SSL.Error, err:
        self._ConnectionLost()
        raise socket.error(err.args)

  @_RequireOpenSocket
  def write(self, data):
    return self._WriteWrapper(self._base.write, data)

  def _WriteWrapper(self, fn, *args, **kwargs):
    while True:
      try:
        return fn(*args, **kwargs)
      except OpenSSL.SSL.ZeroReturnError, err:
        self._ConnectionLost()
        return 0

      except OpenSSL.SSL.WantWriteError:
        continue

      #except OpenSSL.SSL.WantReadError:
      # TODO

      except OpenSSL.SSL.SysCallError, err:
        if err.args[0] == -1 and data == "":
          # errors when writing empty strings are expected
          # and can be ignored
          return 0

        self._ConnectionLost()
        raise socket.error(err.args)

      except OpenSSL.SSL.Error, err:
        self._ConnectionLost()
        raise socket.error(err.args)