Statistics
| Branch: | Tag: | Revision:

root / lib / serializer.py @ 89b70f39

History | View | Annotate | Download (3.7 kB)

1
#
2
#
3

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

    
21
"""Serializer abstraction module
22

23
This module introduces a simple abstraction over the serialization
24
backend (currently json).
25

26
"""
27
# pylint: disable-msg=C0103
28

    
29
# C0103: Invalid name, since pylint doesn't see that Dump points to a
30
# function and not a constant
31

    
32
import simplejson
33
import re
34
import hmac
35

    
36
from ganeti import errors
37

    
38
try:
39
  from hashlib import sha1
40
except ImportError:
41
  import sha as sha1
42

    
43

    
44
_JSON_INDENT = 2
45

    
46
_RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
47

    
48

    
49
def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
50
  """Returns two JSON functions to serialize data.
51

52
  @rtype: (callable, callable)
53
  @return: The function to generate a compact form of JSON and another one to
54
           generate a more readable, indented form of JSON (if supported)
55

56
  """
57
  plain_encoder = _encoder_class(sort_keys=True)
58

    
59
  # Check whether the simplejson module supports indentation
60
  try:
61
    indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
62
  except TypeError:
63
    # Indentation not supported
64
    indent_encoder = plain_encoder
65

    
66
  return (plain_encoder.encode, indent_encoder.encode)
67

    
68

    
69
(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
70

    
71

    
72
def DumpJson(data, indent=True):
73
  """Serialize a given object.
74

75
  @param data: the data to serialize
76
  @param indent: whether to indent output (depends on simplejson version)
77

78
  @return: the string representation of data
79

80
  """
81
  if indent:
82
    fn = _DumpJsonIndent
83
  else:
84
    fn = _DumpJson
85

    
86
  txt = _RE_EOLSP.sub("", fn(data))
87
  if not txt.endswith('\n'):
88
    txt += '\n'
89

    
90
  return txt
91

    
92

    
93
def LoadJson(txt):
94
  """Unserialize data from a string.
95

96
  @param txt: the json-encoded form
97

98
  @return: the original data
99

100
  """
101
  return simplejson.loads(txt)
102

    
103

    
104
def DumpSignedJson(data, key, salt=None):
105
  """Serialize a given object and authenticate it.
106

107
  @param data: the data to serialize
108
  @param key: shared hmac key
109
  @return: the string representation of data signed by the hmac key
110

111
  """
112
  txt = DumpJson(data, indent=False)
113
  if salt is None:
114
    salt = ''
115
  signed_dict = {
116
    'msg': txt,
117
    'salt': salt,
118
    'hmac': hmac.new(key, salt + txt, sha1).hexdigest(),
119
  }
120
  return DumpJson(signed_dict, indent=False)
121

    
122

    
123
def LoadSignedJson(txt, key):
124
  """Verify that a given message was signed with the given key, and load it.
125

126
  @param txt: json-encoded hmac-signed message
127
  @param key: shared hmac key
128
  @rtype: tuple of original data, string
129
  @return: original data, salt
130
  @raises errors.SignatureError: if the message signature doesn't verify
131

132
  """
133
  signed_dict = LoadJson(txt)
134
  if not isinstance(signed_dict, dict):
135
    raise errors.SignatureError('Invalid external message')
136
  try:
137
    msg = signed_dict['msg']
138
    salt = signed_dict['salt']
139
    hmac_sign = signed_dict['hmac']
140
  except KeyError:
141
    raise errors.SignatureError('Invalid external message')
142

    
143
  if hmac.new(key, salt + msg, sha1).hexdigest() != hmac_sign:
144
    raise errors.SignatureError('Invalid Signature')
145

    
146
  return LoadJson(msg), salt
147

    
148

    
149
Dump = DumpJson
150
Load = LoadJson
151
DumpSigned = DumpSignedJson
152
LoadSigned = LoadSignedJson