1.9.30 sync.
[gae.git] / python / google / appengine / api / dosinfo.py
blobc7d2f5f59dc7e19deccbaec97987a69027e078f9
1 #!/usr/bin/env python
3 # Copyright 2007 Google Inc.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
21 """DOS configuration tools.
23 Library for parsing dos.yaml files and working with these in memory.
24 """
33 import re
34 import google
35 import ipaddr
37 from google.appengine.api import appinfo
38 from google.appengine.api import validation
39 from google.appengine.api import yaml_builder
40 from google.appengine.api import yaml_listener
41 from google.appengine.api import yaml_object
43 _DESCRIPTION_REGEX = r'^.{0,499}$'
45 BLACKLIST = 'blacklist'
46 DESCRIPTION = 'description'
47 SUBNET = 'subnet'
50 class SubnetValidator(validation.Validator):
51 """Checks that a subnet can be parsed and is a valid IPv4 or IPv6 subnet."""
53 def Validate(self, value, unused_key=None):
54 """Validates a subnet."""
55 if value is None:
56 raise validation.MissingAttribute('subnet must be specified')
57 if not isinstance(value, basestring):
58 raise validation.ValidationError('subnet must be a string, not \'%r\'' %
59 type(value))
60 try:
61 ipaddr.IPNetwork(value)
62 except ValueError:
63 raise validation.ValidationError('%s is not a valid IPv4 or IPv6 subnet' %
64 value)
67 parts = value.split('/')
68 if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
69 raise validation.ValidationError('Prefix length of subnet %s must be an '
70 'integer (quad-dotted masks are not '
71 'supported)' % value)
73 return value
76 class MalformedDosConfiguration(Exception):
77 """Configuration file for DOS API is malformed."""
80 class BlacklistEntry(validation.Validated):
81 """A blacklist entry describes a blocked IP address or subnet."""
82 ATTRIBUTES = {
83 DESCRIPTION: validation.Optional(_DESCRIPTION_REGEX),
84 SUBNET: SubnetValidator(),
88 class DosInfoExternal(validation.Validated):
89 """Describes the format of a dos.yaml file."""
90 ATTRIBUTES = {
91 appinfo.APPLICATION: validation.Optional(appinfo.APPLICATION_RE_STRING),
92 BLACKLIST: validation.Optional(validation.Repeated(BlacklistEntry)),
96 def LoadSingleDos(dos_info, open_fn=None):
97 """Load a dos.yaml file or string and return a DosInfoExternal object.
99 Args:
100 dos_info: The contents of a dos.yaml file as a string, or an open file
101 object.
102 open_fn: Function for opening files. Unused.
104 Returns:
105 A DosInfoExternal instance which represents the contents of the parsed yaml
106 file.
108 Raises:
109 MalformedDosConfiguration: The yaml file contains multiple blacklist
110 sections.
111 yaml_errors.EventError: An error occured while parsing the yaml file.
113 builder = yaml_object.ObjectBuilder(DosInfoExternal)
114 handler = yaml_builder.BuilderHandler(builder)
115 listener = yaml_listener.EventListener(handler)
116 listener.Parse(dos_info)
118 parsed_yaml = handler.GetResults()
119 if not parsed_yaml:
120 return DosInfoExternal()
121 if len(parsed_yaml) > 1:
122 raise MalformedDosConfiguration('Multiple blacklist: sections '
123 'in configuration.')
124 return parsed_yaml[0]