http.py 20.3 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
34

35
from ganeti import constants
36
from ganeti import serializer
37
from ganeti import utils
38
39


40
41
HTTP_GANETI_VERSION = "Ganeti %s" % constants.RELEASE_VERSION

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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"
71
72
73
HTTP_POST = "POST"
HTTP_PUT = "PUT"

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
74
HTTP_ETAG = "ETag"
75
76
77
78
79
80
81
82
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"
83
84
85
86
87
88


class SocketClosed(socket.error):
  pass


89
90
91
92
93
class HTTPException(Exception):
  code = None
  message = None

  def __init__(self, message=None):
94
    Exception.__init__(self)
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    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


131
132
133
134
class HTTPVersionNotSupported(HTTPException):
  code = 505


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
class ApacheLogfile:
  """Utility class to write HTTP server log files.

  The written format is the "Common Log Format" as defined by Apache:
  http://httpd.apache.org/docs/2.2/mod/mod_log_config.html#examples

  """
  def __init__(self, fd):
    """Constructor for ApacheLogfile class.

    Args:
    - fd: Open file object

    """
    self._fd = fd

  def LogRequest(self, request, format, *args):
    self._fd.write("%s %s %s [%s] %s\n" % (
      # Remote host address
      request.address_string(),

      # RFC1413 identity (identd)
      "-",

      # Remote user
      "-",

      # Request time
      self._FormatCurrentTime(),

      # Message
      format % args,
      ))
168
    self._fd.flush()
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185

  def _FormatCurrentTime(self):
    """Formats current time in Common Log Format.

    """
    return self._FormatLogTime(time.time())

  def _FormatLogTime(self, seconds):
    """Formats time for Common Log Format.

    All timestamps are logged in the UTC timezone.

    Args:
    - seconds: Time in seconds since the epoch

    """
    (_, month, _, _, _, _, _, _, _) = tm = time.gmtime(seconds)
186
    format = "%d/" + MONTHNAME[month] + "/%Y:%H:%M:%S +0000"
187
188
189
190
191
192
193
194
195
196
197
198
199
    return time.strftime(format, tm)


class HTTPJsonConverter:
  CONTENT_TYPE = "application/json"

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

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


200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
class _HttpConnectionHandler(object):
  """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
249
    self.response_headers = {}
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

    self.should_fork = False

    try:
      self._ReadRequest()
      self._ReadPostData()
    except HTTPException, err:
      self._SetErrorStatus(err)

  def Close(self):
    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

  def HandleRequest(self):
    """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)

  def SendResponse(self):
    """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))
356
357
358
359
      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
360
361
362
      for key, val in self.response_headers.iteritems():
        self._SendHeader(key, val)

363
      # We don't support keep-alive at this time
364
      self._SendHeader(HTTP_CONNECTION, "close")
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
      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

443
444
445
446
447
    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."

448
    """
449
450
    # While not according to specification, we only support an entity body for
    # POST and PUT.
451
452
    if (not self.request_method or
        self.request_method.upper() not in (HTTP_POST, HTTP_PUT)):
453
454
455
      self.request_post_data = None
      return

456
    content_length = None
457
    try:
458
459
460
461
      if HTTP_CONTENT_LENGTH in self.request_headers:
        content_length = int(self.request_headers[HTTP_CONTENT_LENGTH])
    except TypeError:
      pass
462
    except ValueError:
463
464
465
466
467
468
      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")
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

    data = self.rfile.read(content_length)

    # TODO: Content-type, error handling
    self.request_post_data = HTTPJsonConverter().Decode(data)

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


class HttpServer(object):
  """Generic HTTP server class

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

  """
  MAX_CHILDREN = 20

486
487
  def __init__(self, mainloop, local_address, port,
               ssl_key_path=None, ssl_cert_path=None, ssl_verify_peer=False):
488
489
490
491
492
493
494
495
    """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
496
497
498
499
500
501
502
    @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
    @type ssl_verify_peer: bool
    @param ssl_verify_peer: Whether to require client certificate and compare
                            it with our certificate
503
504

    """
505
    self.mainloop = mainloop
506
507
    self.local_address = local_address
    self.port = port
508
509
510

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

511
    if ssl_cert_path and ssl_key_path:
512
513
514
      ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD)
      ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2)

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
      ssl_key_pem = utils.ReadFile(ssl_key_path)
      ssl_cert_pem = utils.ReadFile(ssl_cert_path)

      cr = OpenSSL.crypto
      self._ssl_cert = cr.load_certificate(cr.FILETYPE_PEM, ssl_cert_pem)
      self._ssl_key = cr.load_privatekey(cr.FILETYPE_PEM, ssl_key_pem)
      del cr

      ctx.use_privatekey(self._ssl_key)
      ctx.use_certificate(self._ssl_cert)
      ctx.check_privatekey()

      if ssl_verify_peer:
        ctx.set_verify(OpenSSL.SSL.VERIFY_PEER |
                       OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                       self._VerifyCallback)
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

      self.socket = OpenSSL.SSL.Connection(ctx, sock)
      self._fileio_class = _SSLFileObject
    else:
      self.socket = sock
      self._fileio_class = socket._fileobject

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

    self._children = []

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

546
547
548
549
550
551
552
553
554
555
  def _VerifyCallback(self, conn, cert, errno, errdepth, ok):
    """Verify the certificate provided by the peer

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

    """
    return (self._ssl_cert.digest("sha1") == cert.digest("sha1") and
            self._ssl_cert.digest("md5") == cert.digest("md5"))

556
  def Start(self):
557
    self.socket.bind((self.local_address, self.port))
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    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:
582
583
584
585
          # 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.
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
          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):
601
    """Called for each incoming connection
602

603
604
    """
    (connection, client_addr) = self.socket.accept()
605
606
607
608
609
610

    self._CollectChildren(False)

    pid = os.fork()
    if pid == 0:
      # Child process
611
612
      logging.info("Connection from %s:%s", client_addr[0], client_addr[1])

613
      try:
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
        try:
          try:
            handler = None
            try:
              # Read, parse and handle request
              handler = _HttpConnectionHandler(self, connection, client_addr,
                                               self._fileio_class)
              handler.HandleRequest()
            finally:
              # Try to send a response
              if handler:
                handler.SendResponse()
                handler.Close()
          except SocketClosed:
            pass
        finally:
          logging.info("Disconnected %s:%s", client_addr[0], client_addr[1])
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
      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()


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):
        if ((retval == -1 and desc == "Unexpected EOF")
            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)