]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/util.py
17 from .decorators
import *
18 from .misc
import Object
20 # These lists are used to block access to the webapp
27 "b.barracudacentral.org",
31 "dnsbl-1.uceprotect.net",
32 "dnsbl-2.uceprotect.net",
33 "dnsbl-3.uceprotect.net",
35 "ix.dnsbl.manitu.net",
42 # Open location database
43 db
= location
.Database("/var/lib/location/database.db")
45 class Address(Object
):
46 def init(self
, address
):
47 self
.address
= ipaddress
.ip_address(address
)
50 return "%s" % self
.address
54 if isinstance(self
.address
, ipaddress
.IPv6Address
):
55 return socket
.AF_INET6
56 elif isinstance(self
.address
, ipaddress
.IPv4Address
):
61 return db
.lookup("%s" % self
.address
)
64 def country_code(self
):
66 return self
.network
.country_code
71 return self
.network
.asn
75 def _make_blacklist_rr(self
, blacklist
):
76 if self
.family
== socket
.AF_INET6
:
77 octets
= list(self
.address
.exploded
.replace(":", ""))
78 elif self
.family
== socket
.AF_INET
:
79 octets
= str(self
.address
).split(".")
81 raise NotImplementedError("Unknown IP protocol")
87 octets
.append(blacklist
)
89 return ".".join(octets
)
91 async def _resolve_blacklist(self
, blacklist
):
94 # Get resource record name
95 rr
= self
._make
_blacklist
_rr
(blacklist
)
97 # Get query type from IP protocol version
98 if self
.family
== socket
.AF_INET6
:
99 type = pycares
.QUERY_TYPE_AAAA
100 elif self
.family
== socket
.AF_INET
:
101 type = pycares
.QUERY_TYPE_A
103 raise NotImplementedError("Unknown IP protocol")
107 res
= await self
.backend
.resolver
.query(rr
, type=type)
111 return return_code
, "%s" % e
115 logging
.debug("%s is not blacklisted on %s" % (self
, blacklist
))
116 return return_code
, None
118 # Extract return code from DNS response
120 return_code
= row
.host
123 # If the IP address is on a blacklist, we will try to fetch the TXT record
124 reason
= await self
.backend
.resolver
.query(rr
, type=pycares
.QUERY_TYPE_TXT
)
127 logging
.debug("%s is blacklisted on %s: %s" % (self
, blacklist
, reason
or "N/A"))
129 # Take the first reason
132 return return_code
, i
.text
134 # Blocked, but no reason
135 return return_code
, None
137 async def get_blacklists(self
):
138 blacklists
= { bl
: await self
._resolve
_blacklist
(bl
) for bl
in BLACKLISTS
}
144 network
= db
.get_as(asn
)
147 return "%s" % network
151 def format_size(s
, max_unit
=None):
152 units
= ("B", "kB", "MB", "GB", "TB")
155 while s
>= 1024 and i
< len(units
) - 1:
159 if max_unit
and units
[i
] == max_unit
:
162 return "%.0f%s" % (s
, units
[i
])
164 def format_time(s
, shorter
=True):
165 #_ = handler.locale.translate
168 hrs
, s
= divmod(s
, 3600)
169 min, s
= divmod(s
, 60)
174 if shorter
and not hrs
:
175 return _("%(min)d min") % { "min" : min }
177 return _("%(hrs)d:%(min)02d hrs") % {"hrs" : hrs
, "min" : min}
179 def random_string(length
=8):
180 input_chars
= string
.ascii_letters
+ string
.digits
182 r
= (random
.choice(input_chars
) for i
in range(length
))
187 # Remove any non-ASCII characters
189 s
= unicodedata
.normalize("NFKD", s
)
193 # Remove excessive whitespace
194 s
= re
.sub(r
"[^\w]+", " ", s
)
196 return "-".join(s
.split())
198 def generate_thumbnail(data
, size
, square
=False, **args
):
199 assert data
, "No image data received"
201 image
= PIL
.Image
.open(io
.BytesIO(data
))
204 format
= image
.format
206 # Remove any alpha-channels
207 if image
.format
== "JPEG" and not image
.mode
== "RGB":
208 # Make a white background
209 background
= PIL
.Image
.new("RGBA", image
.size
, (255,255,255))
211 # Convert image to RGBA if not in RGBA, yet
212 if not image
.mode
== "RGBA":
213 image
= image
.convert("RGBA")
215 # Flatten both images together
216 flattened_image
= PIL
.Image
.alpha_composite(background
, image
)
218 # Remove the alpha channel
219 image
= flattened_image
.convert("RGB")
221 # Resize the image to the desired resolution
223 image
= PIL
.ImageOps
.fit(image
, (size
, size
), PIL
.Image
.LANCZOS
)
225 image
.thumbnail((size
, size
), PIL
.Image
.LANCZOS
)
227 if image
.format
== "JPEG":
228 # Apply a gaussian blur to make compression easier
229 image
= image
.filter(PIL
.ImageFilter
.GaussianBlur(radius
=0.05))
231 # Arguments to optimise the compression
233 "subsampling" : "4:2:0",
237 with io
.BytesIO() as f
:
238 # If writing out the image does not work with optimization,
239 # we try to write it out without any optimization.
241 image
.save(f
, format
, optimize
=True, **args
)
243 image
.save(f
, format
, **args
)